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   *
073   * @param callable The callable to wrap
074   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
075   *     for each invocation of the wrapped callable.
076   */
077  @GwtIncompatible // threads
078  static <T> Callable<T> threadRenaming(
079      final Callable<T> callable, final Supplier<String> nameSupplier) {
080    checkNotNull(nameSupplier);
081    checkNotNull(callable);
082    return new Callable<T>() {
083      @Override
084      public T call() throws Exception {
085        Thread currentThread = Thread.currentThread();
086        String oldName = currentThread.getName();
087        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
088        try {
089          return callable.call();
090        } finally {
091          if (restoreName) {
092            boolean unused = trySetName(oldName, currentThread);
093          }
094        }
095      }
096    };
097  }
098
099  /**
100   * Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is
101   * running with have the given name.
102   *
103   *
104   * @param task The Runnable to wrap
105   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
106   *     for each invocation of the wrapped callable.
107   */
108  @GwtIncompatible // threads
109  static Runnable threadRenaming(final Runnable task, final Supplier<String> nameSupplier) {
110    checkNotNull(nameSupplier);
111    checkNotNull(task);
112    return new Runnable() {
113      @Override
114      public void run() {
115        Thread currentThread = Thread.currentThread();
116        String oldName = currentThread.getName();
117        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
118        try {
119          task.run();
120        } finally {
121          if (restoreName) {
122            boolean unused = trySetName(oldName, currentThread);
123          }
124        }
125      }
126    };
127  }
128
129  /** Tries to set name of the given {@link Thread}, returns true if successful. */
130  @GwtIncompatible // threads
131  private static boolean trySetName(final String threadName, Thread currentThread) {
132    // In AppEngine, this will always fail. Should we test for that explicitly using
133    // MoreExecutors.isAppEngine? More generally, is there a way to see if we have the modifyThread
134    // permission without catching an exception?
135    try {
136      currentThread.setName(threadName);
137      return true;
138    } catch (SecurityException e) {
139      return false;
140    }
141  }
142}