001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.J2ktIncompatible;
022import com.google.common.base.Supplier;
023import java.util.concurrent.Callable;
024import org.checkerframework.checker.nullness.qual.Nullable;
025
026/**
027 * Static utility methods pertaining to the {@link Callable} interface.
028 *
029 * @author Isaac Shum
030 * @since 1.0
031 */
032@GwtCompatible(emulated = true)
033public final class Callables {
034  private Callables() {}
035
036  /** Creates a {@code Callable} which immediately returns a preset value each time it is called. */
037  public static <T extends @Nullable Object> Callable<T> returning(@ParametricNullness T value) {
038    return () -> value;
039  }
040
041  /**
042   * Creates an {@link AsyncCallable} from a {@link Callable}.
043   *
044   * <p>The {@link AsyncCallable} returns the {@link ListenableFuture} resulting from {@link
045   * ListeningExecutorService#submit(Callable)}.
046   *
047   * @since 20.0
048   */
049  @J2ktIncompatible
050  @GwtIncompatible
051  public static <T extends @Nullable Object> AsyncCallable<T> asAsyncCallable(
052      Callable<T> callable, ListeningExecutorService listeningExecutorService) {
053    checkNotNull(callable);
054    checkNotNull(listeningExecutorService);
055    return () -> listeningExecutorService.submit(callable);
056  }
057
058  /**
059   * Wraps the given callable such that for the duration of {@link Callable#call} the thread that is
060   * running will have the given name.
061   *
062   * @param callable The callable to wrap
063   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
064   *     for each invocation of the wrapped callable.
065   */
066  @J2ktIncompatible
067  @GwtIncompatible // threads
068  static <T extends @Nullable Object> Callable<T> threadRenaming(
069      Callable<T> callable, Supplier<String> nameSupplier) {
070    checkNotNull(nameSupplier);
071    checkNotNull(callable);
072    return () -> {
073      Thread currentThread = Thread.currentThread();
074      String oldName = currentThread.getName();
075      boolean restoreName = trySetName(nameSupplier.get(), currentThread);
076      try {
077        return callable.call();
078      } finally {
079        if (restoreName) {
080          boolean unused = trySetName(oldName, currentThread);
081        }
082      }
083    };
084  }
085
086  /**
087   * Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is
088   * running with have the given name.
089   *
090   * @param task The Runnable to wrap
091   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
092   *     for each invocation of the wrapped callable.
093   */
094  @J2ktIncompatible
095  @GwtIncompatible // threads
096  static Runnable threadRenaming(Runnable task, Supplier<String> nameSupplier) {
097    checkNotNull(nameSupplier);
098    checkNotNull(task);
099    return () -> {
100      Thread currentThread = Thread.currentThread();
101      String oldName = currentThread.getName();
102      boolean restoreName = trySetName(nameSupplier.get(), currentThread);
103      try {
104        task.run();
105      } finally {
106        if (restoreName) {
107          boolean unused = trySetName(oldName, currentThread);
108        }
109      }
110    };
111  }
112
113  /** Tries to set name of the given {@link Thread}, returns true if successful. */
114  @J2ktIncompatible
115  @GwtIncompatible // threads
116  private static boolean trySetName(String threadName, Thread currentThread) {
117    /*
118     * setName should usually succeed, but the security manager can prohibit it. Is there a way to
119     * see if we have the modifyThread permission without catching an exception?
120     */
121    try {
122      currentThread.setName(threadName);
123      return true;
124    } catch (SecurityException e) {
125      return false;
126    }
127  }
128}