Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Whether StampedLock in Java 8 will be the key to solving the synchronization problem

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

It is believed that many inexperienced people are at a loss about whether StampedLock in Java 8 will be the key to solve the synchronization problem. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Java8 is like a treasure, a small API improvement, but also enough to write an article, such as synchronization, has always been an old topic of multithreaded concurrent programming, I believe that no one likes synchronized code, which will reduce application throughput and other performance indicators, the worst will hang, but even then you have no choice, because to ensure the correctness of the information. So the editor decided to make a comparative analysis of the new StampedLock from synchronized, Lock to Java8. I believe StampedLock will not let you down.

Synchronized

Before java5, synchronization was mainly achieved using synchronized. It is a keyword of the Java language, and when it is used to modify a method or a block of code, it ensures that at most one thread executes the code at a time.

There are four different synchronization blocks:

Example method

Static method

Synchronization block in instance method

Synchronization blocks in static methods

You should be familiar with this, so I won't talk about it any more. here are some code examples.

Synchronized (this) / / do operation}

Summary: Synchronized has always been a veteran in multithreaded concurrent programming, and many people will call it a heavyweight lock, but performance has improved as Java SE1.6 has made various optimizations to Synchronized.

Lock

It is a new API added to java.util.concurrent.locks by Java 5.

Lock is an interface. The core methods are lock (), unlock (), tryLock (). The implementation classes include ReentrantLock, ReentrantReadWriteLock.ReadLock, and ReentrantReadWriteLock.WriteLock.

ReentrantReadWriteLock, ReentrantLock, and synchronized locks all have the same memory semantics.

Unlike synchronized, Lock is written entirely in Java and is implemented independently of JVM at the java level. Lock provides a more flexible locking mechanism, and many features that many synchronized do not provide, such as lock voting, scheduled lock waiting and interrupt lock waiting, but because lock is implemented through code, to ensure that the lock must be released, unLock () must be placed in finally {}

Here is a code example for Lock

Rwlock.writeLock () .lock (); try {/ / do operation} finally {rwlock.writeLock () .unlock ();}

Summary: a more flexible and scalable locking mechanism than synchronized, but synchronized code is easier to write anyway

StampedLock

It is a new API added by java8 to java.util.concurrent.locks.

ReentrantReadWriteLock can only acquire write locks when there are no read-write locks, which can be used to implement pessimistic reads (Pessimistic Reading), that is, if reading is in progress, there is often another need to execute writes, and read locks on ReentrantReadWriteLock can come in handy in order to maintain synchronization.

However, if there is a lot of read execution and very few writes, using ReentrantReadWriteLock may cause the writer thread to experience Starvation problems, that is, the writer thread can't compete until it is locked and is waiting.

There are three modes of StampedLock control lock (write, read, optimistic read). A StampedLock state is composed of version and mode. The lock acquisition method returns a number as a ticket stamp, which represents and controls access with the corresponding lock state, and the number 0 indicates that no write lock is authorized to access. The read lock is divided into pessimistic lock and optimistic lock.

The so-called optimistic read mode, that is, if there are a lot of read operations and few write operations, you can be optimistic that there is very little chance of writing and reading at the same time, so you are not pessimistic about using full read locking. The program can check whether changes are written after reading the data, and then take follow-up measures (re-read the change information, or throw an exception). This is a small improvement. Can greatly improve the throughput of the program!

Here is an example of StampedLock provided by java doc

Class Point {private double x, y; private final StampedLock sl = new StampedLock (); void move (double deltaX, double deltaY) {/ / an exclusively locked method long stamp = sl.writeLock (); try {x + = deltaX; y + = deltaY;} finally {sl.unlockWrite (stamp) }} / / Let's take a look at the optimistic read lock case double distanceFromOrigin () {/ A read-only method long stamp = sl.tryOptimisticRead (); / / get an optimistic read lock double currentX = x, currentY = y; / / read two fields into the local local variable if (! sl.validate (stamp)) {/ / check whether other write locks occur at the same time after issuing the optimistic read lock? Stamp = sl.readLock (); / / if not, we again get a pessimistic lock try {currentX = x; / / read two fields into the local local variable currentY = y; / / read two fields into the local local variable} finally {sl.unlockRead (stamp) }} return Math.sqrt (currentX * currentX + currentY * currentY);} / / the following is a pessimistic read lock case void moveIfAtOrigin (double newX, double newY) {/ / upgrade / / Could instead start with optimistic, not read mode long stamp = sl.readLock () Try {while (x = = 0 & & y = = 0) {/ / loop to check whether the current state conforms to long ws = sl.tryConvertToWriteLock (stamp); / / convert read lock to write lock if (ws! = 0L) {/ / this is to confirm whether the conversion to write lock is successful stamp = ws; / / if the bill is successfully replaced x = newX / / perform a state change y = newY; / / perform a state change break;} else {/ / if you cannot successfully convert to a write lock sl.unlockRead (stamp); / / We explicitly release the read lock stamp = sl.writeLock () / / write lock explicitly and then try again via loop} finally {sl.unlock (stamp); / / release read lock or write lock}}

Summary:

StampedLock is cheaper than ReentrantReadWriteLock, that is, it consumes less.

Performance comparison between StampedLock and ReadWriteLock

The following picture shows that compared with ReadWritLock, in the case of one thread, it is about 4 times the read speed and 1 times the write speed.

The following figure shows that in the case of six threads, the read performance is dozens of times higher, and the write performance is about 10 times higher:

The following figure shows the improvement in throughput:

Summary

1. Synchronized is implemented at the JVM level. Not only can you monitor the lock of synchronized through some monitoring tools, but also if an exception occurs during code execution, JVM will automatically release the lock.

2. ReentrantLock, ReentrantReadWriteLock, and StampedLock are all locks at the object level. To ensure that the lock will be released, you must put unLock () in finally {}.

3. StampedLock has a great improvement in throughput, especially when there are more and more read threads.

4. StampedLock has a complex API, so it is easy to misuse other methods for locking operations.

5. Synchronized is a good general-purpose lock implementation when there are only a few competitors

6. ReentrantLock is a good general-purpose lock implementation when thread growth can be predicted

StampedLock can be said to be a good supplement to Lock. The improvement in throughput and performance is enough to move many people, but it does not mean to replace the previous Lock. After all, he still has some application scenarios. At least API is easier to get started than StampedLock. The next blog post may be updated faster, which may be the content of Nashorn.

Original link: http://my.oschina.net/benhaile/blog/264383

After reading the above, do you know whether StampedLock in Java 8 will be the key to solving the synchronization problem? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report