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.Beta;
020import com.google.common.annotations.GwtCompatible;
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.base.Supplier;
023import java.util.concurrent.Callable;
024import org.checkerframework.checker.nullness.compatqual.NullableDecl;
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> Callable<T> returning(@NullableDecl final T value) {
038    return new Callable<T>() {
039      @Override
040      public T call() {
041        return value;
042      }
043    };
044  }
045
046  /**
047   * Creates an {@link AsyncCallable} from a {@link Callable}.
048   *
049   * <p>The {@link AsyncCallable} returns the {@link ListenableFuture} resulting from {@link
050   * ListeningExecutorService#submit(Callable)}.
051   *
052   * @since 20.0
053   */
054  @Beta
055  @GwtIncompatible
056  public static <T> AsyncCallable<T> asAsyncCallable(
057      final Callable<T> callable, final ListeningExecutorService listeningExecutorService) {
058    checkNotNull(callable);
059    checkNotNull(listeningExecutorService);
060    return new AsyncCallable<T>() {
061      @Override
062      public ListenableFuture<T> call() throws Exception {
063        return listeningExecutorService.submit(callable);
064      }
065    };
066  }
067
068  /**
069   * Wraps the given callable such that for the duration of {@link Callable#call} the thread that is
070   * running will have the given name.
071   *
072   * @param callable The callable to wrap
073   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
074   *     for each invocation of the wrapped callable.
075   */
076  @GwtIncompatible // threads
077  static <T> Callable<T> threadRenaming(
078      final Callable<T> callable, final Supplier<String> nameSupplier) {
079    checkNotNull(nameSupplier);
080    checkNotNull(callable);
081    return new Callable<T>() {
082      @Override
083      public T call() throws Exception {
084        Thread currentThread = Thread.currentThread();
085        String oldName = currentThread.getName();
086        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
087        try {
088          return callable.call();
089        } finally {
090          if (restoreName) {
091            boolean unused = trySetName(oldName, currentThread);
092          }
093        }
094      }
095    };
096  }
097
098  /**
099   * Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is
100   * running with have the given name.
101   *
102   * @param task The Runnable to wrap
103   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
104   *     for each invocation of the wrapped callable.
105   */
106  @GwtIncompatible // threads
107  static Runnable threadRenaming(final Runnable task, final Supplier<String> nameSupplier) {
108    checkNotNull(nameSupplier);
109    checkNotNull(task);
110    return new Runnable() {
111      @Override
112      public void run() {
113        Thread currentThread = Thread.currentThread();
114        String oldName = currentThread.getName();
115        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
116        try {
117          task.run();
118        } finally {
119          if (restoreName) {
120            boolean unused = trySetName(oldName, currentThread);
121          }
122        }
123      }
124    };
125  }
126
127  /** Tries to set name of the given {@link Thread}, returns true if successful. */
128  @GwtIncompatible // threads
129  private static boolean trySetName(final String threadName, Thread currentThread) {
130    /*
131     * setName should usually succeed, but the security manager can prohibit it. Is there a way to
132     * see if we have the modifyThread permission without catching an exception?
133     */
134    try {
135      currentThread.setName(threadName);
136      return true;
137    } catch (SecurityException e) {
138      return false;
139    }
140  }
141}