Local thread variable or new thread - Java
<p>I have a class that implements Runnable.  For logging reasons I want to know the Thread that has been used to run the class.  In that case would it be best to do</p>

<pre><code>public class WebSocketHandle implements Runnable {
   private Thread myThread; // access to thread for logging

   public void start() {
      myThread = new Thread(this);
      myThread.start();
   }
}
</code></pre>

<p>Then in the method that creates these I do something like:</p>

<pre><code>    public void newSocket(Socket socket)
{
    WebSocketHandle handle = new WebSocketHandle(this, socket,_identity);
    _sockets.add(handle);

    EventLog.write("Socket assigned for new connection (" + _sockets.size() + ") "  + handle.toString() +  ". No value received yet yet...", getClass().getName(), "register");

    // Start thread listening for data
    new Thread(handle).start();
}
</code></pre>

<p>Or is it best to have something like:</p>

<pre><code>public class WebSocketHandle implements Runnable {
   private String myThread;

   public void setThreadOwner(string threadId) {
      myThread = threadId;
   }
}
</code></pre>

<p>Then it would be used as such:</p>

<pre><code>WebSocketHandle handle = new WebSocketHandle();
Thread newThread = new Thread(handle);

newThread.start();

handle.setThreadOwner(handle.toString());
</code></pre>

<p>I can't help but feel the second option is better practice but the code to write seems clumsier??</p>

<p>EDIT:  In response to Aaron's comments:</p>

<ol>
<li><p>This is for a Web server socket handling code so the Thread will be running indefinetly.  I had not considered using ThreadPools so maybe that is something I need to consider</p></li>
<li><p>I log various activities (i.e. data received and sent) in the the WebSocketHandle class so I wanted to tie the logging events to the Thread instance that it is running on.  To do that I found the easiest way was to log the thread.toString() as part of the log output.</p></li>
</ol>
