In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how the new feature StampedLock of java 8 solves the synchronization problem. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
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.
?
one
two
three
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
one
two
three
four
five
six
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 little chance of writing and reading at the same time, so you are not pessimistic about using a complete read lock. 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
?
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty
thirty-one
thirty-two
thirty-three
thirty-four
thirty-five
thirty-six
thirty-seven
thirty-eight
thirty-nine
forty
forty-one
forty-two
forty-three
forty-four
forty-five
forty-six
forty-seven
forty-eight
forty-nine
fifty
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 local local variables
If (! sl.validate (stamp)) {/ / check whether other write locks occur at the same time after issuing optimistic read locks?
Stamp = sl.readLock (); / / if not, we get a read pessimistic lock again
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 case of pessimistic reading lock
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 ticket is replaced successfully
X = newX; / / make a state change
Y = newY; / / make a state change
Break
}
Else {/ / if it cannot be successfully converted to a write lock
Sl.unlockRead (stamp); / / We explicitly release the read lock
Stamp = sl.writeLock (); / / write the lock explicitly and then try again through the loop
}
}
} finally {
Sl.unlock (stamp); / / release the read 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:
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
So much for sharing about how StampedLock, the new feature of java 8, solves the synchronization problem. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.
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.