Process, thread, green threads in Java

Difference between process and thread

A process is an instance of a program at runtime, an independent object to which system resources (such as CPU time and memory) are allocated. Each process runs in a separate address space: one process cannot access the variables and data structures of another. If a process wants to access someone else's resources, it must use interprocess communication. These can be pipelines, files, communication channels between computers, and much more.

For each process, the OS creates a so-called "virtual address space", to which the process has direct access. This space belongs to the process, contains only its data and is at its complete disposal. The operating system is responsible for how the virtual space of the process is projected onto the physical memory.

A thread is a particular way of executing a process that determines the sequence of execution of code in a process. Threads are always created in the context of a process, and their whole life passes only within its boundaries. Threads can execute the same code and manipulate the same data, or share kernel object descriptors, since the descriptor table is not created in separate threads, but in processes. Since threads consume significantly less resources than processes, it is more profitable to create additional threads in the process of performing work and avoid creating new processes.

Green threads

Green (lightweight) threads are threads emulated by a virtual machine or runtime. Creating a green thread does not imply creating a real OS thread.

The Java virtual machine takes care of switching between different green threads, and the machine itself operates as one OS thread. This has several benefits. OS threads are relatively expensive on most POSIX systems. Also, switching between native threads is much slower than between green threads.

This all means that in some situations green threads are much more profitable than native threads. The system can support many more green threads than OS threads. For example, it is much more practical to start a new green thread for a new HTTP connection to the web server, instead of creating a new native thread.

However, there are also disadvantages. The biggest one is that you cannot execute two threads at the same time. Since there is only one native thread, only it is called by the OS scheduler. Even if you have multiple processors and multiple green threads, only one processor can call a green thread. And this is because from the point of view of the OS task scheduler, it all looks like one thread.

Since version 1.2 Java supports native threads and they have been used by default ever since.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed