View Javadoc

    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one
    3    * or more contributor license agreements.  See the NOTICE file
    4    * distributed with this work for additional information
    5    * regarding copyright ownership.  The ASF licenses this file
    6    * to you under the Apache License, Version 2.0 (the
    7    * "License"); you may not use this file except in compliance
    8    * with the License.  You may obtain a copy of the License at
    9    *
    10   *   http://www.apache.org/licenses/LICENSE-2.0
    11   *
    12   * Unless required by applicable law or agreed to in writing,
    13   * software distributed under the License is distributed on an
    14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    15   * KIND, either express or implied.  See the License for the
    16   * specific language governing permissions and limitations
    17   * under the License.
    18   */
    19  package org.apache.mina.util;
    20
    21  import org.slf4j.Logger;
    22  import org.slf4j.LoggerFactory;
    23
    24  /**
    25   * A {@link Runnable} wrapper that preserves the name of the thread after the runnable is
    26   * complete (for {@link Runnable}s that change the name of the Thread they use.)
    27   *
    28   * @author The Apache MINA Project (dev@mina.apache.org)
    29   * @version $Rev: 446581 $, $Date: 2006-09-15 11:36:12Z $,
    30   */
    31  public class NamePreservingRunnable implements Runnable {
    32      private final Logger logger = LoggerFactory.getLogger(NamePreservingRunnable.class);
    33
    34      private final String newName;
    35      private final Runnable runnable;
    36
    37      public NamePreservingRunnable(Runnable runnable, String newName) {
    38          this.runnable = runnable;
    39          this.newName = newName;
    40      }
    41
    42      public void run() {
    43          Thread currentThread = Thread.currentThread();
    44          String oldName = currentThread.getName();
    45
    46          if (newName != null) {
    47              setName(currentThread, newName);
    48          }
    49
    50          try {
    51              runnable.run();
    52          } finally {
    53              setName(currentThread, oldName);
    54          }
    55      }
    56
    57      /**
    58       * Wraps {@link Thread#setName(String)} to catch a possible {@link Exception}s such as
    59       * {@link SecurityException} in sandbox environments, such as applets
    60       */
    61      private void setName(Thread thread, String name) {
    62          try {
    63              thread.setName(name);
    64          } catch (Exception e) {
    65              // Probably SecurityException.
    66              if (logger.isWarnEnabled()) {
    67                  logger.warn("Failed to set the thread name.", e);
    68              }
    69          }
    70      }
    71  }