01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
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
33: .getLogger(NamePreservingRunnable.class);
34:
35: private final String newName;
36: private final Runnable runnable;
37:
38: public NamePreservingRunnable(Runnable runnable, String newName) {
39: this .runnable = runnable;
40: this .newName = newName;
41: }
42:
43: public void run() {
44: Thread currentThread = Thread.currentThread();
45: String oldName = currentThread.getName();
46:
47: if (newName != null) {
48: setName(currentThread, newName);
49: }
50:
51: try {
52: runnable.run();
53: } finally {
54: setName(currentThread, oldName);
55: }
56: }
57:
58: /**
59: * Wraps {@link Thread#setName(String)} to catch a possible {@link Exception}s such as
60: * {@link SecurityException} in sandbox environments, such as applets
61: */
62: private void setName(Thread thread, String name) {
63: try {
64: thread.setName(name);
65: } catch (Exception e) {
66: // Probably SecurityException.
67: if (logger.isWarnEnabled()) {
68: logger.warn("Failed to set the thread name.", e);
69: }
70: }
71: }
72: }
|