I've stumbled upon an article, which says that StampedLock from JSR166 "is a major improvement over existing lock implementations". And the API and code are pretty complex.
Can anybody explain me how it works and why it is better than other types of locks in Java?
I thought there can't be a big difference since all the locks generally acquire monitor and other threads have to wait when it available.
The StampedLock creates a queue (linked-list) of the threads that are waiting to acquire the lock.
The insertion in the queue is Lock-Free, but after the insertion, each thread will spin or yield and thus be blocked by the thread currently holding the lock. Using the Unsafe.park()/unpark() mechanism, the thread that releases the lock is able to "wakeup" the next thread waiting in the queue, thus enforcing a strict priority.
The current thread is guaranteed to eventually get the lock, and thus complete its own operation.So, Eventually all thread complete their operation.
It uses Unsafe heavily, but classes from "sun" package aren't guaranteed to exist in future versions of JDK. So it looks like this solution may have problems with maintenance in future. Is that correct?
surlac surlacovich wrote:It uses Unsafe heavily, but classes from "sun" package aren't guaranteed to exist in future versions of JDK. So it looks like this solution may have problems with maintenance in future. Is that correct?
If the code is intended to be part of the standard API, then it can use internal code like that without any problem. I'm not sure if that applies to the code you linked to or not, I didn't look at it for very long.
surlac surlacovich wrote:Can anybody explain me how it works and why it is better than other types of locks in Java?
How it works? Dunno. But its advantage would appear to be that you can upgrade a lock without a lot of overhead.
The fact of the matter is that I haven't yet found anything much that can't be done with volatile and synchronized and, according to the article, many of the reasons for choosing locks over synchronized in the first place have disappeared. A lot of it sounds like "transactional" memory stuff, and sounds like it's only needed for very specialised situations. I don't know "where you are" at the moment, but I suspect there are other things that might be a better use of your time - interesting though this may be.
Bats fly at night, 'cause they aren't we. And if we tried, we'd hit a tree -- Ogden Nash (or should've been).
Articles by Winston can be found here