<howto>
h1.  Readlock Recipe

h2.  Summary

Terracotta supports read locks in addition to standard synchronized (mutually exclusive, or write) locks.  Even if you still use Java 1.4, or haven't changed your code to use ReentrantReadWrite locks from the java.util.concurrent package, you can add read locking to your code.

The use of read locks for concurrent access to data in a threaded environment is highly useful.  With Java 1.5, you can add read and write to your code using [java.util.concurrent.ReentrantReadWriteLock|http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html].  If you want to add read and write lock semantics to code that uses synchronized, with Terracotta, you can.  

A common use case for read locking, especially in a clustered envionrment, is the use of a distributed cache.  Read access to cached data items allows highly concurrent access - within a single JVM and across JVMs - without compromising data integrity when updates are made.

If your code already utilizes ReentrantReadWrite locks, then you are done already.  Just examine the [ReentrantReadWrite Recipe|http://www.terracotta.org/confluence/display/howto/Recipe?recipe=rrwl] to integrate Terracotta with your ReentrantReadWrite locks. 

If, however, you have existing code that utilizes synchronized, but can benefit from read locking, as opposed to mutually exlusive write locking, read this example to see how a standard java synchronized block is converted to a concurrent read lock with no changes to your code.

Even with a single JVM in the cluster, your application will benefit from the improved concurrency afforded by read locks.

h2.  How to run
(Note: A Terracotta Server instance is always required to run Terracotta.  dso-java(.sh|.bat) is a wrapper script that adds Terracotta to standard java)

*Node 1:*
{code}
$ javac *.java
$ start-tc-server &amp;
$ dso-java Main
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
I'm in the synchronized block
{code}
</howto>
