This post originated from an RSS feed registered with Java Buzz
by Talip Ozturk.
Original Post: Distributed Locks for Java
Feed Title: Shared Memory
Feed URL: http://www.jroller.com/talipozturk/feed/entries/rss
Feed Description: about java, jcache, jini, javaspaces, distributed data structures and a little bit of me and life.
While Hazelcast is cooking to be 1.0, distributed implementation of java.util.concurrent.locks.Lock is being developed to catch the 1.1 release in July. Hazelcast-1.0 will hopefully be generally available in June. Here is sample code for cluster-wide object locking.
java.util.concurrent.locks.Lock myLock = Hazelcast.getLock (new MyObject()); myLock.lock (); try { // do some stuff here.. } finally { myLock.unlock(); }
Since this is cluster-wide lock, object identity of your mutex within JVM cannot be used. Hazelcast uses binary representation of your mutex as identifier. So if binary representations of your objects are the same then Lock objects you will get for these objects will be same cluster-wide.
Everything else works just like the way Lock javadoc says. Even lock.tryLock() with timeouts is supported.
java.util.concurrent.locks.Lock myLock = Hazelcast.getLock (obj); if (myLock.tryLock (5000, TimeUnit.MILLISECONDS)) { try { // do some stuff here.. } finally { myLock.unlock(); } }
Implementation is also re-entrant; it behaves just like java.util.concurrent.lock.ReentrantLock. More importantly, you won't lose your locks after crashes. So If a member holds a lock and some of the members go down, cluster will keep your locks safe and available. Moreover, when a member leaves the cluster, all the locks acquired by this dead member will be removed so that these locks can be available for live members immediately. Currently implementation is in alpha but if you want to try it out, just drop me an email (oztalip at gmail dot com).