by BehindJava

How to distinguishing between Java threads and OS threads

Home » java » How to distinguishing between Java threads and OS threads

In this tutorial we are going learn about the differences between the Java Threads and OS Threads.

On Linux, Java threads are implemented with native threads, so a Java program using threads is no different from a native program using threads. A “Java thread” is just a thread belonging to a JVM process.

On a modern Linux system (one using NPTL), all threads belonging to a process have the same process ID and parent process ID, but different thread IDs. You can see these IDs by running ps -eLf.

The PID column is the process ID, the PPID column is the parent process ID, and the LWP column is the thread (LightWeight Process) ID. The “main” thread has a thread ID that’s the same as the process ID, and additional threads will have different thread ID values.

Older Linux systems may use the “linuxthreads” threading implementation, which is not fully POSIX-compliant, instead of NPTL. On a linuxthreads system, threads have different process IDs.

You can check whether your system is using NPTL or linuxthreads by running the system’s C library (libc) as a standalone program and looking under “Available extensions” in its output. It should mention either “Native POSIX Threads Library” or linuxthreads.

The path to the C library varies from system to system: it may be /lib/libc.so.6, /lib64/libc.so.6 (on 64-bit RedHat-based systems), or something like /lib/x86_64-linux-gnu/libc.so.6 (on modern Debian-based systems such as Ubuntu).

At the OS level, theads don’t have names; those exist only within the JVM.

The pthread_kill() C function can be used to send a signal to a specific thread, which you could use to try to kill that specific thread from outside the JVM, but I don’t know how the JVM would respond to it. It might just kill the whole JVM.

There is also a pure Java thread implementation, called green threads. This is used as a fallback if native threads aren’t supported or the system isn’t multithreaded at all. You won’t see any green threads at your OS.

Can a running Java threads can be suspended or killed from another Java code?

If they are running at the same JVM, yes, with stop(). But that’s not a good solution and may work, or not. interrupt() allows the thread so safely shut itself down.

There is no way to kill threads outside of the JVM I know of. If a OS really supports killing of threads, I wouldn’t expect the Java application to run correctly afterwards!