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   *
053   * @param callable The callable to wrap
054   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
055   *     for each invocation of the wrapped callable.
056   */
057  static <T> Callable<T> threadRenaming(final Callable<T> callable,
058      final Supplier<String> nameSupplier) {
059    checkNotNull(nameSupplier);
060    checkNotNull(callable);
061    return new Callable<T>() {
062      @Override public T call() throws Exception {
063        Thread currentThread = Thread.currentThread();
064        String oldName = currentThread.getName();
065        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
066        try {
067          return callable.call();
068        } finally {
069          if (restoreName) {
070            trySetName(oldName, currentThread);
071          }
072        }
073      }
074    };
075  }
076
077  /**
078   * Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is
079   * running with have the given name.
080   *
081   *
082   * @param task The Runnable to wrap
083   * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
084   *     for each invocation of the wrapped callable.
085   */
086  static Runnable threadRenaming(final Runnable task, final Supplier<String> nameSupplier) {
087    checkNotNull(nameSupplier);
088    checkNotNull(task);
089    return new Runnable() {
090      @Override public void run() {
091        Thread currentThread = Thread.currentThread();
092        String oldName = currentThread.getName();
093        boolean restoreName = trySetName(nameSupplier.get(), currentThread);
094        try {
095          task.run();
096        } finally {
097          if (restoreName) {
098            trySetName(oldName, currentThread);
099          }
100        }
101      }
102    };
103  }
104
105  /** Tries to set name of the given {@link Thread}, returns true if successful. */
106  private static boolean trySetName(final String threadName, Thread currentThread) {
107    // In AppEngine this will always fail, should we test for that explicitly using
108    // MoreExecutors.isAppEngine.  More generally, is there a way to see if we have the modifyThread
109    // permission without catching an exception?
110    try {
111      currentThread.setName(threadName);
112      return true;
113    } catch (SecurityException e) {
114      return false;
115    }
116  }
117}