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