8 great Java features no one’s talking about — reprint

Original address: http://www.infoq.com/articles/Java-8-Quiet-Features

If you haven’t seen some of the videos or tutorials around Java 8,you’ve probably been super-busy or have a more interesting social life than I do (which isn’t saying much). With new features like lambda expressions and Project Nashorn taking so much of the spotlight,I wanted to focus on some new APIs that have been a bit under the radar,but make Java 8 better in so many ways.

1. Stamped Locks

Multi-threaded code has long been the bane of server developers (just ask Oracle Java Language Architect and concurrency guru). Over time complex idioms were added to the core Java libraries to help minimize thread waits when accessing shared resources. One of these is the classic ReadWriteLock that lets you divide code into sections that need to be mutually exclusive (writers),and sections that don’t (readers).

On paper this sounds great. The problem is that the ReadWriteLock can be (up to 10x),which kind of defeats its purpose. Java 8 introduces a new ReadWrite lock – called. The good news here is that this guy is seriously fast. The bad news is that it’s more complicated to use and lugs around more state. It’s also not reentrant,which means a thread can have the dubious pleasure of deadlocking against itself.

StampedLock has an "optimistic" mode that issues a stamp that is returned by each locking operation to serve as a sort of admission ticket; each unlock operation needs to be passed its correlating stamp. Any thread that happens to acquire a write lock while a reader was holding an optimistic lock,will cause the optimistic unlock to be invalidated (the stamp is no longer valid). At that point the application can start all over,perhaps with a pessimistic lock (also implemented in StampedLock.) Managing that is up to you,and one stamp cannot be used to unlock another – so be super careful.

Let’s see this lock in action-

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
分享
二维码
< <上一篇
下一篇>>