Improving Lock Performance in Java–reference

After we introduced to couple of months ago,we have started to receive queries similar to “hey,great,Now I understand what is causing my performance issues,but what I am supposed to do Now?”

We are working hard to build the solution instructions into our own product,but in this post I am going to share several common techniques you can apply independent of the tool used for detecting the lock. The methods include lock splitting,concurrent data structures,protecting the data instead of the code and lock scope reduction.

Locking is not evil,lock contention is

Whenever you face a performance problem with the threaded code there is a chance that you will start blaming locks. After all,common “kNowledge” is that locks are slow and limit scalability. So if you are equipped with this “kNowledge” and start to optimize the code and getting rid of locks there is a chance that you end up introducing nasty concurrency bugs that will surface later on.

So it is important to understand the difference between contended and uncontended locks. Lock contention occurs when a thread is trying to enter the synchronized block/method currently executed by another thread. This second thread is Now forced to wait until the first thread has completed executing the synchronized block and releases the monitor. When only one thread at a time is trying to execute the synchronized code,the lock stays uncontended.

As a matter of fact,synchronization in JVM is optimized for the uncontended case and for the vast majority of the applications,uncontended locks pose next to no overhead during execution. So,it is not locks you should blame for performance,but contended locks. Equipped with this kNowledge,lets see what we can do to reduce either the likelihood of contention or the length of the contention.

Protect the data not the code

A quick way to achieve thread-safety is to lock access to the whole method. For example,take look at the following example,illustrating a naive attempt to build an online poker server:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>