title: Obtaining the thread ID for Java threads in Linux
body: <p>I have a Java application where some threads are created (via <code>new Thread()</code>). Using <code>ps</code> I can see they have different thread IDs (LWP column) and I would like to obtain those IDs from within the Java application.</p>
  
  <p>In most of the posts related to this topic that I have found (e.g., <a href="https://stackoverflow.com/questions/35842/process-id-in-java">this one</a>), the solution is to use <code>ManagementFactory.getRuntimeMXBean().getName()</code>.</p>
  
  <p>Using that method, however, gives me the PID of the main thread (even if I call it from one of the threads), so it is not really solving my problem.</p>
  
  <p>Is there any way to obtain the thread ID for every single <code>Thread</code> created by an application?</p>
  
  <p>Would it be possible to use JNI to accomplish it? If somehow I could interface to a C function where I could call <code>syscall(__NR_gettid)</code>, that could solve my problem. I really do not care about portability, so I am totally okay with a solution that would only work for a Linux machine.</p>
  
  <p><strong>UPDATE:</strong> I have actually solved my problem by using JNI. Details are explained in my answer. Thank you all for your suggestions/comments.</p>