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.base.Supplier;
022
023import java.util.concurrent.Callable;
024
025import javax.annotation.Nullable;
026
027/**
028 * Static utility methods pertaining to the {@link Callable} interface.
029 *
030 * @author Isaac Shum
031 * @since 1.0
032 */
033public final class Callables {
034  private Callables() {}
035
036  /**
037   * Creates a {@code Callable} which immediately returns a preset value each
038   * time it is called.
039   */
040  public static <T> Callable<T> returning(final @Nullable T value) {
041    return new Callable<T>() {
042      @Override public T call() {
043        return value;
044      }
045    };
046  }
047
048  /**
049   * Wraps the given callable such that for the duration of {@link Callable#call} the thread that is
050   * running will have the given name.
051   *
052   * @param callable The callable to wrap
053   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
054   *     for each invocation of the wrapped callable.
055   */
056  static <T> Callable<T> threadRenaming(final Callable<T> callable,
057      final Supplier<String> nameSupplier) {
058    checkNotNull(nameSupplier);
059    checkNotNull(callable);
060    return new Callable<T>() {
061      @Override public T call() throws Exception {
062        Thread currentThread = Thread.currentThread();
063        String oldName = currentThread.getName();
064        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
065        try {
066          return callable.call();
067        } finally {
068          if (restoreName) {
069            trySetName(oldName, currentThread);
070          }
071        }
072      }
073    };
074  }
075
076  /**
077   * Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is
078   * running with have the given name.
079   *
080   * @param task The Runnable to wrap
081   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
082   *     for each invocation of the wrapped callable.
083   */
084  static Runnable threadRenaming(final Runnable task, final Supplier<String> nameSupplier) {
085    checkNotNull(nameSupplier);
086    checkNotNull(task);
087    return new Runnable() {
088      @Override public void run() {
089        Thread currentThread = Thread.currentThread();
090        String oldName = currentThread.getName();
091        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
092        try {
093          task.run();
094        } finally {
095          if (restoreName) {
096            trySetName(oldName, currentThread);
097          }
098        }
099      }
100    };
101  }
102
103  /** Tries to set name of the given {@link Thread}, returns true if successful. */
104  private static boolean trySetName(final String threadName, Thread currentThread) {
105    // In AppEngine this will always fail, should we test for that explicitly using
106    // MoreExecutors.isAppEngine.  More generally, is there a way to see if we have the modifyThread
107    // permission without catching an exception?
108    try {
109      currentThread.setName(threadName);
110      return true;
111    } catch (SecurityException e) {
112      return false;
113    }
114  }
115}