title: Attach metadata to thread in Java
body: <p>Is there any way to attach some kind of custom metadata(any object) to the thread in java? For example if I run couple of threads using ThreadPoolExecutor with some attached to each metadata and pass these threads into some processor which will be able to read this metadata?</p>
  
  <p>As far as I see from the source code of the Thread, the only thing I can do - just set thread name.</p>
  
  <p>Thanks to AlexR I've solved the problem. That one remember's Id of the thread which launches this thread.</p>
  
  <pre><code>public class StarterThreadAwareThread extends Thread {
  
      private volatile long startedThreadId;
  
      public StarterThreadAwareThread(ThreadGroup group, Runnable target, String name) {
          super(group, target, name);
      }
  
      public long getStartedThreadId() {
          return startedThreadId;
      }
  
      @Override
      public synchronized void start() {
          this.startedThreadId = Thread.currentThread().getId();
          super.start();
      }
  }
  </code></pre>
  
  <p>Then some magic with ThreadFactory - overriding the creation of the new thread</p>
  
  <pre><code>Thread newThread(Runnable r) {
      return new StarterThreadAwareThread(getThreadGroup(), runnable, nextThreadName());
  }
  </code></pre>
  
  <p>And then in each place we can access statically to the submitter's thread id like</p>
  
  <pre><code>StarterThreadAwareThread thread = (StarterThreadAwareThread)Thread.currentThread(); // check with instaneof before casting if required
  thread.getStartedThreadId();
  </code></pre>
  
  <p>PS: this solution works, if ThreadPoolExecutor creates new thread each time you call submit. If not, I've created more complicated solution but it should work always and everywhere:
  1. <a href="http://pastebin.com/GU4S793Y" rel="nofollow">http://pastebin.com/GU4S793Y</a>
  2. <a href="http://pastebin.com/f936R2rc" rel="nofollow">http://pastebin.com/f936R2rc</a>
  3. <a href="http://pastebin.com/YxuGXHiT" rel="nofollow">http://pastebin.com/YxuGXHiT</a></p>