Oook! I created the ThreadUtil class and refactored all the
Thread.setName invocations to use the new class.

Attached is the patch (sorry for the absolute paths)

Does this do or shall I create an issue in the tracker?

On 10/24/07, Trustin Lee <[EMAIL PROTECTED]> wrote:
> On 10/24/07, Andres Martinez Quijano <[EMAIL PROTECTED]> wrote:
> > Hi
> >
> > I've noticed that in several places (Executors and Connectors) it is
> > called the method Thread.setName
> >
> > In an applet context (I'm developing multiplayer games) this is
> > forbidden by the sandbox, and a SecurityException arises.
> >
> > I haven't looked deeply into the code... is this naming thing for
> > logging purposes only or does it have another meaning?
>
> It is often helpful for a developer to analyze full thread dump.
>
> > Can it be configured so in applet contexts for instance threads
> > doesn't get renamed? Or maybe wrap the call within a try / catch
> >
> > If any of the answers is yes, I can modify it and supply a patch
>
> Yes.  We could create a class 'org.apache.mina.util.ThreadUtil' and
> 'org.apache.mina.util.ThreadUtil.setName(Thread)' method, which wraps
> Thread.setName() with a try / catch block.  Please go ahead!
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/common/ExecutorThreadModel.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/common/ExecutorThreadModel.java
      (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/common/ExecutorThreadModel.java
      (working copy)
@@ -27,6 +27,7 @@
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.mina.filter.executor.ExecutorFilter;
+import org.apache.mina.util.ThreadUtil;
 
 /**
  * A [EMAIL PROTECTED] ThreadModel} which represents a thread model with an 
[EMAIL PROTECTED] Executor}
@@ -88,8 +89,8 @@
 
             public Thread newThread(Runnable runnable) {
                 Thread t = originalThreadFactory.newThread(runnable);
-                t.setName(ExecutorThreadModel.this.threadNamePrefix + '-'
-                        + threadId.incrementAndGet());
+                ThreadUtil.setName(t, ExecutorThreadModel.this.threadNamePrefix
+                        + '-' + threadId.incrementAndGet());
                 t.setDaemon(true);
                 return t;
             }
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketConnector.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketConnector.java
    (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketConnector.java
    (working copy)
@@ -43,6 +43,7 @@
 import org.apache.mina.common.support.DefaultConnectFuture;
 import org.apache.mina.util.NamePreservingRunnable;
 import org.apache.mina.util.NewThreadExecutor;
+import org.apache.mina.util.ThreadUtil;
 
 /**
  * [EMAIL PROTECTED] IoConnector} for socket transport (TCP/IP).
@@ -199,10 +200,10 @@
                 } catch (IOException e2) {
                     ExceptionMonitor.getInstance().exceptionCaught(e2);
                 }
-    
+
                 return DefaultConnectFuture.newFailedFuture(e);
             }
-    
+
             connectQueue.add(request);
             selector.wakeup();
         }
@@ -351,7 +352,8 @@
         private long lastActive = System.currentTimeMillis();
 
         public void run() {
-            Thread.currentThread().setName(SocketConnector.this.threadName);
+            ThreadUtil.setName(Thread.currentThread(),
+                    SocketConnector.this.threadName);
 
             Selector selector = SocketConnector.this.selector;
             for (;;) {
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketAcceptor.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketAcceptor.java
     (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketAcceptor.java
     (working copy)
@@ -45,6 +45,7 @@
 import org.apache.mina.common.support.BaseIoAcceptor;
 import org.apache.mina.util.NamePreservingRunnable;
 import org.apache.mina.util.NewThreadExecutor;
+import org.apache.mina.util.ThreadUtil;
 
 /**
  * [EMAIL PROTECTED] IoAcceptor} for socket transport (TCP/IP).
@@ -139,9 +140,9 @@
 
         synchronized (lock) {
             startupWorker();
-    
+
             registerQueue.add(request);
-    
+
             selector.wakeup();
         }
 
@@ -182,11 +183,12 @@
                 // running and failed to open a selector.  We simply throw
                 // IllegalArgumentException here because we can simply
                 // conclude that nothing is bound to the selector.
-                throw new IllegalArgumentException("Address not bound: " + 
address);
+                throw new IllegalArgumentException("Address not bound: "
+                        + address);
             }
-    
+
             cancelQueue.add(request);
-    
+
             selector.wakeup();
         }
 
@@ -214,7 +216,8 @@
 
     private class Worker implements Runnable {
         public void run() {
-            Thread.currentThread().setName(SocketAcceptor.this.threadName);
+            ThreadUtil.setName(Thread.currentThread(),
+                    SocketAcceptor.this.threadName);
 
             Selector selector = SocketAcceptor.this.selector;
             for (;;) {
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketIoProcessor.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketIoProcessor.java
  (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/SocketIoProcessor.java
  (working copy)
@@ -34,6 +34,7 @@
 import org.apache.mina.common.IoFilter.WriteRequest;
 import org.apache.mina.common.WriteTimeoutException;
 import org.apache.mina.util.NamePreservingRunnable;
+import org.apache.mina.util.ThreadUtil;
 
 /**
  * Performs all I/O operations for sockets which is connected or bound. This 
class is used by MINA internally.
@@ -89,7 +90,7 @@
     }
 
     void flush(SocketSessionImpl session) {
-        if ( scheduleFlush(session) ) {
+        if (scheduleFlush(session)) {
             Selector selector = this.selector;
             if (selector != null) {
                 selector.wakeup();
@@ -320,8 +321,9 @@
 
             try {
                 boolean flushedAll = doFlush(session);
-                if( flushedAll && !session.getWriteRequestQueue().isEmpty() && 
!session.isScheduledForFlush()) {
-                    scheduleFlush( session );
+                if (flushedAll && !session.getWriteRequestQueue().isEmpty()
+                        && !session.isScheduledForFlush()) {
+                    scheduleFlush(session);
                 }
             } catch (IOException e) {
                 scheduleRemove(session);
@@ -372,7 +374,8 @@
         Queue<WriteRequest> writeRequestQueue = session.getWriteRequestQueue();
 
         int writtenBytes = 0;
-        int maxWrittenBytes = ((SocketSessionConfig) 
session.getConfig()).getSendBufferSize() << 1;
+        int maxWrittenBytes = ((SocketSessionConfig) session.getConfig())
+                .getSendBufferSize() << 1;
         try {
             for (;;) {
                 WriteRequest req = writeRequestQueue.peek();
@@ -385,11 +388,11 @@
                     writeRequestQueue.poll();
 
                     buf.reset();
-                    
+
                     if (!buf.hasRemaining()) {
                         session.increaseWrittenMessages();
                     }
-                    
+
                     session.getFilterChain().fireMessageSent(session, req);
                     continue;
                 }
@@ -453,7 +456,8 @@
 
     private class Worker implements Runnable {
         public void run() {
-            Thread.currentThread().setName(SocketIoProcessor.this.threadName);
+            ThreadUtil.setName(Thread.currentThread(),
+                    SocketIoProcessor.this.threadName);
 
             Selector selector = SocketIoProcessor.this.selector;
             for (;;) {
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java
  (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java
  (working copy)
@@ -48,6 +48,7 @@
 import org.apache.mina.transport.socket.nio.DatagramServiceConfig;
 import org.apache.mina.transport.socket.nio.DatagramSessionConfig;
 import org.apache.mina.util.NamePreservingRunnable;
+import org.apache.mina.util.ThreadUtil;
 
 /**
  * [EMAIL PROTECTED] IoConnector} for datagram transport (UDP/IP).
@@ -292,7 +293,7 @@
 
     private class Worker implements Runnable {
         public void run() {
-            Thread.currentThread().setName("DatagramConnector-" + id);
+            ThreadUtil.setName(Thread.currentThread(), "DatagramConnector-" + 
id);
 
             Selector selector = DatagramConnectorDelegate.this.selector;
             for (;;) {
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java
   (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java
   (working copy)
@@ -51,6 +51,7 @@
 import org.apache.mina.transport.socket.nio.DatagramServiceConfig;
 import org.apache.mina.transport.socket.nio.DatagramSessionConfig;
 import org.apache.mina.util.NamePreservingRunnable;
+import org.apache.mina.util.ThreadUtil;
 
 /**
  * [EMAIL PROTECTED] IoAcceptor} for datagram transport (UDP/IP).
@@ -109,7 +110,7 @@
 
         RegistrationRequest request = new RegistrationRequest(address, handler,
                 config);
-        
+
         synchronized (lock) {
             startupWorker();
             registerQueue.add(request);
@@ -145,9 +146,10 @@
                 // running and failed to open a selector.  We simply throw
                 // IllegalArgumentException here because we can simply
                 // conclude that nothing is bound to the selector.
-                throw new IllegalArgumentException("Address not bound: " + 
address);
+                throw new IllegalArgumentException("Address not bound: "
+                        + address);
             }
-    
+
             cancelQueue.add(request);
             selector.wakeup();
         }
@@ -308,7 +310,8 @@
 
     private class Worker implements Runnable {
         public void run() {
-            Thread.currentThread().setName("DatagramAcceptor-" + id);
+            ThreadUtil
+                    .setName(Thread.currentThread(), "DatagramAcceptor-" + id);
 
             Selector selector = DatagramAcceptorDelegate.this.selector;
             for (;;) {
@@ -419,7 +422,8 @@
 
             try {
                 boolean flushedAll = flush(session);
-                if (flushedAll && !session.getWriteRequestQueue().isEmpty() && 
!session.isScheduledForFlush()) {
+                if (flushedAll && !session.getWriteRequestQueue().isEmpty()
+                        && !session.isScheduledForFlush()) {
                     scheduleFlush(session);
                 }
             } catch (IOException e) {
@@ -444,36 +448,37 @@
         Queue<WriteRequest> writeRequestQueue = session.getWriteRequestQueue();
 
         int writtenBytes = 0;
-        int maxWrittenBytes = ((DatagramSessionConfig) 
session.getConfig()).getSendBufferSize() << 1;
+        int maxWrittenBytes = ((DatagramSessionConfig) session.getConfig())
+                .getSendBufferSize() << 1;
         try {
             for (;;) {
                 WriteRequest req = writeRequestQueue.peek();
-    
+
                 if (req == null)
                     break;
-    
+
                 ByteBuffer buf = (ByteBuffer) req.getMessage();
                 if (buf.remaining() == 0) {
                     // pop and fire event
                     writeRequestQueue.poll();
-    
+
                     buf.reset();
-                    
+
                     if (!buf.hasRemaining()) {
                         session.increaseWrittenMessages();
                     }
                     session.getFilterChain().fireMessageSent(session, req);
                     continue;
                 }
-    
+
                 SocketAddress destination = req.getDestination();
                 if (destination == null) {
                     destination = session.getRemoteAddress();
                 }
-    
+
                 int localWrittenBytes = ch.send(buf.buf(), destination);
                 writtenBytes += localWrittenBytes;
-    
+
                 if (localWrittenBytes == 0 || writtenBytes >= maxWrittenBytes) 
{
                     // Kernel buffer is full or wrote too much
                     key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
@@ -481,9 +486,9 @@
                 } else {
                     // pop and fire event
                     writeRequestQueue.poll();
-    
+
                     buf.reset();
-                    
+
                     if (!buf.hasRemaining()) {
                         session.increaseWrittenMessages();
                     }
@@ -494,7 +499,7 @@
         } finally {
             session.increaseWrittenBytes(writtenBytes);
         }
-        
+
         return true;
     }
 
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/util/ThreadUtil.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/util/ThreadUtil.java
 (revision 0)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/util/ThreadUtil.java
 (revision 0)
@@ -0,0 +1,43 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+package org.apache.mina.util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ThreadUtil {
+
+    private final static Logger logger = LoggerFactory
+            .getLogger(ThreadUtil.class);
+
+    /**
+     * Wraps Thread.setName(name) to catch a possible 
<code>SecurityException</code> in sandbox environments, such as applets
+     * @param name
+     */
+    public static void setName(Thread thread, String name) {
+        try {
+            thread.setName(name);
+        } catch (SecurityException se) {
+            if (logger.isWarnEnabled()) {
+                logger.warn(se.getMessage());
+            }
+        }
+    }
+}
Index: 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/util/NamePreservingRunnable.java
===================================================================
--- 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/util/NamePreservingRunnable.java
     (revision 587882)
+++ 
C:/eclipse/taringa/Mina-1.1/core/src/main/java/org/apache/mina/util/NamePreservingRunnable.java
     (working copy)
@@ -38,7 +38,7 @@
         try {
             runnable.run();
         } finally {
-            Thread.currentThread().setName(name);
+            ThreadUtil.setName(Thread.currentThread(), name);
         }
     }
 }

Reply via email to