In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what are the mistakes easy to make in java multithreading". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
When should multithreading be used?
I wonder if you have ever thought about this question, that is, when should I use multithreading? Does the use of multithreading necessarily improve system performance?
1. Whether you should use multithreading or not depends largely on the type of application.
For computationally intensive (such as pure mathematical operations) and restricted by CPU functions, only multi-CPU (or multiple cores) machines can benefit from more threads. Under a single CPU, multithreading will not bring any performance improvement, but may lead to performance degradation due to additional overhead such as thread switching.
IO-intensive, when my application has to wait for slow resources (such as returning data on a network connection or database connection), then many threads will make full use of the system's CPU, and when one thread blocks and hangs, the other thread can continue to use CPU resources.
In fact, multithreading will not increase the processing power of CPU, but can make more full use of CPU resources.
Because multiple threads in the same process share the same memory resources, it will not only bring convenience, but also increase its complexity, how to ensure the consistency of multi-thread access data and so on. And multithreading is a place where programming is easy to roll over. And the test location of multithreaded programming problems is also difficult. Generally speaking, good multithreading is written, and it is undoubtedly extremely unreliable to expect multithreading problems to be found in the test. SO, study hard.
Several keywords closely related to multithreading in Java API: volatile, synchronized, wait, notify. With the understanding of these keywords, you can write multithreaded code.
When does it need to be locked?
In the case of multithreading, the most important thing is to ensure the consistency of data, and to ensure the consistency of data, we need to rely on locks.
In fact, in a multithreaded scenario, we should figure out the question, that is, what needs to be protected? Not all data needs to be locked, only those that involve shared data accessed by multiple threads need to be locked.
The essence of locking is to ensure that only one thread is accessing the shared data at the same time, so that the shared data can be effectively protected.
For example, for example, we want to construct an one-way linked list that is safe under multiple threads:
If there are now two threads operating on the linked list, one writer thread inserts a new element 7, and the other reader thread traverses the linked list data, if no locks are used, the following execution order may occur:
Step writer thread reader thread 0 modifies the next pointer of linked list element 2 to the element 7. 1. ... Traversing the linked list, it is found that next is null at 7, and the next pointer to element 7 at the end of traversal 2 points to 3. ...
From the above example, we can clearly see that manipulating the linked list in multithreading may result in incomplete data read by the reading thread, only from the head of the linked list to the position of element 7. Thus it can be seen that multithreaded protection without any protection measures will inevitably lead to data confusion. To avoid data consistency problems, we need to put the code that operates on the queue into the synchronization block (the object of the lock is the linked list instance) to ensure that only one thread can access the linked list at a time.
How to add a lock?
To put it simply, we usually use synchronized (if there is no special need to suggest using this keyword directly, the new version of jdk is really fast), keep in mind that the synchronized lock is the object header.
In a nutshell, there are the following main uses:
Synchronized is placed on the method, and the object instance of the current synchronized method is locked
Synchronized locks the class class object of the synchronized method on the static method. Note that class is actually an object here.
Synchronized (this) in the code block, the lock is the object in parentheses in the code block, where this refers to the class instance object that calls this method.
Mistakes easy to make in multithreading 1. The lock range is too large
After the shared resource access is complete, the subsequent code is not placed outside the synchronized synchronization code block. It will cause the current thread to occupy the lock invalid for a long time, while other threads contending for the lock can only wait, resulting in a great impact on performance.
Public void test () {synchronized (lock) {. / is accessing shared resources. / / doing other time-consuming operations, but these time-consuming operations have nothing to do with shared resources}}.
In the face of the above writing, it will cause this thread to occupy the lock for a long time, thus causing other threads to wait. Let's discuss the solution below:
1) in a single CPU scenario, taking time-consuming operations that do not require synchronization to the outside of the synchronization block can improve performance in some cases, but not in others.
CPU-intensive code, there is no disk IO/ network IO and other low CPU consumption code. In this case, 99% of CPU is executing code. Therefore, shrinking the synchronization block will not bring any performance improvement, and shrinking the synchronization block will not bring about any performance degradation.
IO-intensive code, in fact, CPU is idle when executing code that does not consume CPU. If you let CPU work at this time, you can bring an overall performance improvement. So in this case, time-consuming operations that do not require synchronization can be moved outside the synchronization block.
2) in multi-CPU scenarios, taking time-consuming CPU operations outside the synchronization block can always improve performance.
CPU-intensive code, there are no IO operations and other code fragments that do not consume CPU. Because it is currently multi-CPU, other CPU may also be idle. So when shrinking the synchronization block, it will also allow other threads to execute this code as soon as possible, resulting in a performance improvement.
IO-intensive code, because the current PCU is idle, so putting time-consuming operations outside the synchronization block will certainly lead to an overall performance improvement.
Of course, in any case, narrowing the synchronization range of the lock is beneficial to the system, so the above code should be changed to:
Public void test () {synchronized (lock) {. / / accessing shared resources}. / / do other time-consuming operations, but these time-consuming operations have nothing to do with shared resources}.
To sum up, a key point is to put only the code that accesses the shared resources in the synchronization block to ensure fast-in and fast-out.
2. Deadlock problem
What deadlocks need to know:
Deadlock, in short, is caused by two or more threads waiting for the lock held by each other at the same time. The deadlock will cause the thread to be unable to continue execution and be permanently suspended.
If the thread has a deadlock, then we can clearly see the "Found one Java-level deadlock" in the thread stack, and the thread stack will also give the analysis result of the deadlock.
If deadlock occurs on a critical system, it may paralyze the system. If you want to restore the system quickly, the only temporary way is to leave the thread stack to restart first, and then restore it as soon as possible.
Deadlock problems are sometimes difficult to detect immediately during testing. In many cases, whether you can find such problems in time depends on your luck and the test cases you have prepared.
The only way to avoid problems such as deadlocks is to change the code. But a reliable system is designed, not by changing the BUG. When this problem occurs, it needs to be analyzed from the perspective of system design.
Some people may think that deadlocks will lead to 100% CPU, but it is both true and wrong. Depending on what type of lock is used, such as a deadlock caused by synchronized, it does not cause CPU100%, to only suspend threads. But if it is a spin lock, this may consume CPU.
3. The problem of sharing a lock
It is that multiple shared variables share a lock, especially the use of synchronized at the method level, resulting in artificial lock competition.
For the above example, here are some mistakes that beginners can easily make:
1 public class MyTest2 {3 Object shared;4 synchronized void fun1 () {...} / / access the shared variable shared5 synchronized void fun2 () {} / / access the shared variable shared6 synchronized void fun3 () {} / / do not access the shared variable shared7 synchronized void fun4 () {.} / / do not access the shared variable shared8 synchronized void fun5 () {.} / / do not access the shared variable shared9}
Each method in the above code is added with a synchronized, which clearly violates the principle of protecting locks and whatever.
Third, the number of threads we generally set is more reasonable?
In fact, we all know that in most cases, multithreading can improve the performance and throughput of the system, but how many threads are reasonable in a system?
Generally speaking, it is not good to have too many and too few threads. Too many threads will increase the overhead due to frequent thread switching, and sometimes reduce system performance. The lack of CPU resources can not be fully utilized, and the performance does not reach the bottleneck.
Therefore, the appropriate number of threads used by the system depends on whether the threads of the system can make full use of CPU. In fact, the actual situation is that most of the time do not consume CPU, such as: disk IO, network IO and so on.
Disk IO, network IO compared to the speed of CPU, that is quite slow, in the execution of IO during this time CPU is actually idle. If other threads can make use of this idle CPU at this time, they can achieve the purpose of indicating system performance and throughput.
In fact, we have also mentioned above, that is, two computing features:
CPU-intensive: because every CPU is a case of high computing load, setting too many threads can lead to unnecessary context switching. So, the general thread we will set the number of CPU cores + 1, why add 1, even when CPU-intensive threads are occasionally paused due to page missing failures or other reasons, this "extra" thread can ensure that the clock cycle of CPU will not be wasted, in fact, it is just a backup.
IO-intensive: because a large number of IO operations will cause CPU to be idle, we can set up more threads at this time. So, the number of threads = the number of CPU cores * (1 + IO time / CPU time) is fine. I hope it will give you some inspiration.
This is the end of the content of "what are the mistakes easy to make in java multithreading". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.