Saturday, 20 March 2010

Java.util.Concurrent, Part 1 - Locks

You might have missed this glem in API, Released back in 2006 with Java 5.0, util.Concurrent is a Java API extention, giving all sorts of tricks and methodology for hightly multithreaded code. With chips becoming ever more multithreaded, perphaps
even 512 way by 2020. Your find yourself ever push to make more use of multiple threads. And the Concurrent API certainly make it easier. Lets have a look at some of the tricks in the new API.

Locks, in old fashioned java, when you had a critical set of code, a piece you want to be sure, only one thread was going to run at a time. You use to have to synchronize it on a object invented for the task. But in Java 5 and onwards have also proper locks in a variatly of types.

import java.util.concurrent.lock;

Lock myLock = new ReentractLock();

try {
   // Thread safe code
finally {

The API provide to general interfaces, Lock and ReadWriteLock, and three classes, RentrantLock, RentrantReadWriteLock.ReadLock, RentrantReadWriteLock.WriteLock. Rentrant means the calling class can try and gain the lock as many times as it like without problems, only once it was unlock as many lock as it has acquired will another thread beable to acquire the lock. The RentractReadWriteLock is usually for double end object such as queues, seperate class may be able to gain different locks. Allowing different threads to be reading and writing the queue at the same time.

No comments:

Post a Comment