Java thread Overview

Source: Internet
Author: User

Java thread Overview

I don't know when it will start, and it seems that there is a high concurrency everywhere. It may be due to the difficulties that I have encountered in online ticketing, or the various promotions on various shopping websites, therefore, in various recruitment notices, there are clear requirements for high concurrency and scalability. How many concurrent jobs can be referred to as high concurrency? How can I evaluate my skills and experience in highly concurrent server programs? I cannot give clear answers to these questions because I have not developed highly concurrent server programs (large projects I have participated in are ssh-based web applications ), second, in the age of computer programming, various advantages of Java object-oriented were promoted everywhere, such as the allocation and release of memory, portability (in fact, many languages have portability ), you don't need to duplicate the wheel (after work, you can find out how happy it is to make the wheel yourself), Java multithreading is very easy to implement, Java provides a variety of data structure sets, etc, as a result, a lot of basic underlying knowledge is skipped. When we find that we want to further find out the root cause of some problems, we often find bottlenecks everywhere and even don't know What we need Baidu. As a result, I began to reread operating systems, algorithms, and other related books after work. When I learned these basic but important knowledge again, I always got different inspirations, it may be because I went to school to cope with the exam.

From the needs of interest and work, to the fields related to big data, we began to use open-source big data storage, processing and analysis tools, such as Hadoop, Hive, and HBase, we also came into contact with the OpenStack cloud computing framework, where the Swift module is used. These software or frameworks are all advertised as having high concurrency, high availability, and scalability, so they are thinking about how they achieve high concurrency? Because I am a little familiar with Java programming, I naturally think of multithreading. Will it be highly concurrent after I create a Java multithreading? The answer is obviously inconsistent. In some cases, multithreading can improve the efficiency. For example, a single task can be divided into sub-tasks that do not affect each other, on the contrary, if a task is executed in sequence, the subsequent code must wait until the previous code is executed to continue execution. In this case, multithreading may reduce the efficiency. From this, we can draw a simple conclusion that the use of multithreading depends on specific scenarios. This is also a word that many open-source software like to use when introducing a parameter, but for me, I really don't like this sentence because it doesn't give me the only answer (Chinese students always like the only answer ). In order to find your favorite, I had to pick up "Operating System Concepts" again and prepare the source code of Hadoop and HBase for reference and reference at any time.

1.1 thread Concept

Although the concept of multi-threaded programming has become very popular, it is necessary to reiterate the concept of thread and Its Relationship with processes. A thread is the basic unit running in the CPU. For a system that does not support multiple threads-although there are few such systems, it does exist-this statement is also true. Some people may ask if the basic unit running on the CPU is not a process, so it is necessary to clarify the concept of the process, although the process is everywhere. Broadly or broadly speaking, a process refers to a running program, so it is an activity entity. More specifically, a process includes program code (text or code segment ), the value of the program counter and the content, data segment, and stack in the register set. A thread is the execution flow of Process Code, including the thread ID, program counter, register set, and thread stack, and other threads that belong to the same process (if any) share code segments, data segments, and other operating system resources, such as opening files and signals. Because a thread has certain attributes of a process, such as program counters and registers, it is also called a lightweight process. in the traditional sense, a process is called a heavyweight process, the following figure shows the differences between a single-threaded process and a multi-threaded process:

 

It can be clearly found that a thread is a process in a single-threaded process, and multiple threads exist in a multi-threaded process, this means that many tasks can be done at the same time (not in the real sense at the same time in a single processor at the same time, but because the super-fast processing speed of the processor gives users the illusion that they are almost real at the same time, but in a multi-processor, the real same time can be achieved ). It can also be determined that the thread must belong to a process and cannot exist independently of the process, while the process has at least one thread.

Since a thread is only an execution sequence in a process, multiple execution sequences can exist in a multi-threaded process to complete multiple tasks at the same time, so why not split multiple threads into multiple processes to complete multiple tasks, or there are only heavyweight processes in a system but no lightweight processes, why not merge all tasks into one process? That is, the whole system has only one process, which is composed of many threads. The answer is obviously very complex. Simply put, the reason why multiple threads are not created for multiple processes is that:

1. All threads belonging to the same process share common data. Communication between them does not require additional overhead of inter-process communication.

2. because the same resources are shared, creating a thread is usually faster than creating a process (only the thread stack used needs to be created), and context switching of a thread is also more efficient than Context switching of a process.

3. for some services, such as printers or web servers, multithreading often provides a more efficient response speed than multi-process operations, because inter-thread communication in the same process is more efficient than inter-process communication.

Since multithreading has so many advantages, why not merge all processes into one process? The threads in the process will complete the work of all previous processes. Obviously, this assumption is not true, because the operating system itself is not just a separate process, but composed of several processes that complete different tasks, or composed of different modules. Let's take a step back. Assume that the operating system is only composed of one process, and all users' tasks are composed of one process. This will inevitably lead to security problems because all users' tasks share the same memory space, each Other can access the data of the other party. To avoid these problems, the security complexity of the operating system will be increased. In addition, from the perspective of software engineering, merging irrelevant tasks into a process violates the loose coupling principle, such as placing printers and web servers or browsers in a process, this forced bonding behavior brings far greater harm than the many advantages provided by multithreading.

1.2 context switching

In general, context switching refers to transferring the CPU usage right from one process or thread to another process or thread, the details are often closely related to specific operating systems or hardware. Context switching of a process means that different processes can use the CPU in turn. For example, when a process waits for the completion of IO, the CPU usage must be handed over, another process that waits for the CPU to obtain the right to use can be executed. Context switching of a thread means that the threads in a process get the CPU usage in turn. Context switching of different processes means context switching of processes. In a single processor system, context switching between processes and threads is easy to understand, because there is only one CPU, to switch the context of a thread in a process, you only need to save the status of the previously running thread and load the status of the thread to be run. The context switch between processes is actually process context switch, whether these processes are single-threaded or multi-threaded. In a multi-processor system, context switching between threads in a process is the same as that of a single processor, but is context switching between threads equivalent to intra-process context switching? If the thread for performing context switching is a single-threaded process, it is obviously a process context switching. What if it is a multi-threaded process? To clarify this, the thread context switch in the process does not need to change the address space of the process, while the process context switch requires changing the address space of the process, because the threads of different processes have different address spaces, the thread context between processes also needs to change the address space. Therefore, even in a multi-processor system, context switching between processes is also a process context switching. According to the above discussion, it can be concluded that, without explicitly specifying inter-process thread context switching, thread context switching refers to intra-process thread context switching, therefore, thread context switching is more efficient than process context switching. Context switching between processes is equivalent to process context switching, regardless of single CPU or multiple CPU Systems.

1.3 thread type

Depending on whether a thread is managed and scheduled by the operating system, there are two types of threads: User thread and kernel thread. As the name suggests, user threads are managed by Applications created by users or users. user applications are responsible for thread creation, scheduling, context switching, information transmission between threads, and thread destruction, from the operating system perspective, the multi-threaded process of a user thread is only a single-threaded process. User applications are responsible for all aspects of user threads and do not need to execute system calls. Therefore, user Thread Scheduling and context switching are faster and more efficient, however, the resulting disadvantages are also very obvious. First of all, because the kernel is not responsible for user thread scheduling, the kernel can only schedule user applications (single-threaded processes), so it cannot schedule multithreading to multiple CPUs, therefore, the parallel advantages of multiple CPUs cannot be used. Second, when a user thread's execution system call is blocked, such a thread cannot be executed even if there is a user thread that can be executed, because the single-Thread process seen by the kernel. Finally, the time slice allocated by the kernel to the user thread process needs to be allocated to the user thread by the application, that is, all user threads share the time slice.

The kernel thread is created, scheduled, context switched, and destroyed by the operating system. Due to the participation of the operating system, the kernel thread overcomes the shortcomings of the user thread, that is, the kernel thread can be allocated time slices for running, when a kernel thread in the same process is blocked, the other kernel threads still have the opportunity to run (depending on whether the operating system schedules the operation ), multiple kernel threads can be allocated to multiple CPUs for running to take full advantage of the advantages of multiple CPUs. There is a disadvantage in everything. Compared with the user thread, the creation and management of kernel threads are more complex and inefficient.

The user thread is a thread running in the user space, while the kernel thread is a thread running in the kernel space, which leads to some connection between the user thread and the kernel thread, this connection creates the thread model to be described below.

1.4 thread model

The thread model defines how to map user threads to kernel threads, mainly including the multi-to-one model, one-to-one model, and many-to-many model.

1.4.1 multi-to-one model

The many-to-one model maps multiple user threads to one kernel thread. Thread management is performed in the user space. Because management does not involve system calls, it is more efficient. However, because multiple user threads can only be mapped to or associated with one kernel thread, the whole process is blocked when the user Thread associated with the kernel thread executes a blocking system call, because only one thread can be scheduled by the operating system, multiple user threads cannot run on multiple CPUs. In earlier versions of Java, Solaris Green Thread was implemented using multiple-to-one models.

1.4.2 one-to-one model

As the name suggests, in a one-to-one model, each user thread has a kernel thread corresponding to it. In this way, when a user thread executes a blocking system call, such as waiting for the completion of file read/write, wait for the arrival of network data, and other user threads will not lose the chance of execution because of blocking threads, and can truly run concurrently on the multi-processor. Because everything has two sides, the disadvantage of the one-to-one model is that a kernel thread is created every time a user thread is created, which is less efficient than creating a user thread, in addition, because different systems have different configurations (memory, hard disk, CPU quantity and speed), creating too many user threads will have different effects on the system and thus affect the performance of applications. Many Linux systems and Windows systems have implemented a one-to-one model.

1.4.3 multi-to-multi-model

In the multi-to-one model, although multiple user threads can be created (as long as there is enough memory), only one user thread can be scheduled to the kernel thread at a time, therefore, no application concurrency is added. The disadvantage of one-to-one model is that there is an upper limit on the number of kernel threads allowed and the number of user threads is increased at will (corresponding kernel threads will also be created) this will affect the performance of the system or application. Therefore, you must limit the number of user threads that can exist at the same time to a certain extent. In order to create any number of user threads and run programs concurrently in the form of Inner-core threads, a multi-to-many model is developed based on the multi-to-one and one-to-one models. Many-to-many models allow user threads to be reused to the same number or fewer kernel threads. Therefore, you can create any number of user threads, it also enables the corresponding kernel threads to run on the multi-processor in parallel. When a thread is blocked, it does not block other threads. Despite the advantages of many-to-many models, it is particularly difficult and error-prone to build and synchronize the user thread scheduler to the kernel scheduler. The comparison between many-to-many and one-to-one models on the Linux kernel shows that the one-to-one model is usually more advantageous in terms of performance and user usage, however, many-to-many models in a specific field may be the right choice.

In versions earlier than Solaris 9, Solaris supports many-to-many models, but later versions use one-to-one models.

1.5 Java thread

After reading the above introduction, the question that users who use Java may ask is whether the Java thread is a user thread or a kernel thread, and which thread model is used by the Java thread. Anyone with experience in Java Thread Programming knows that Java threads are created by executing the start method (instead of a new Thread object), that is, applications are created in the user space, therefore, Java threads are user threads. Since java programs run in JVM and JVM has different implementations based on the operating system, JVM on different platforms implements different multi-threaded models. For example, the one-to-one model is used in Windows and Linux, while the multi-to-one model was implemented in earlier Solaris, and then changed to the multi-to-multi-model, after Solaris 9, a one-to-one model was adopted. In addition, there is a certain relationship between the Java thread and the thread library of the host operating system. For example, in Windows, the Win32 API Thread library is used to create a thread, and in Linux, The Pthread is used to create a thread.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.