Next page | Contents page |

Synchronisation

There is a construction which can be used to protect any critical sections of code:

	synchronized (expression)
	{
		statements
	}

expression must evaluate to an object (or array) reference that every thread using this code has access to. A lock is obtained on that object before entering the section and released at the end of it. No other thread can run this section of code until the lock is released: they must wait at the start of the critical section.

The bank in the previous exercise had a really typical example of a critical section: test a value and then update it. If another thread can get in between the test and the update you are in trouble.

Modifier synchronized can also be applied to a method, to ensure that two threads cannot execute it simultaneously. A thread obtains a lock on the object (or the entire class for a static method).

NB: It is vitally important to be sure that competing threads access the same lockable object. Putting synchronized on a method is a less sure way of guaranteeing that.

Testing is not easy: how would you arrange that 2 threads do try to access the critical section at the same time, when you have no control over the scheduler?

Java 5

Java 5 has introduced significant enhancements to multi-threading. Eg, run() could end with an unchecked exception. Java 5 enables catching that by using setUncaughtExceptionHandler () to provide a handler that implements Thread.UncaughtExceptionHandler.

There are now 2 ways of protecting a block of code from concurrent access: the old synchronized keyword and, with more facilities, a new java.util.concurrent.locks.ReentrantLock class, used like this:

	theReentrantLock.lock();
	
	try 
	{
		/* ... critical section */ 
	}
	finally 
	{
		theReentrantLock.unlock();  // Essential!
	}

That enables you to find out what objects are waiting, and other new things.

New java.util.concurrent.locks.Condition interface for managing threads that have the lock but cannot do anything until another thread has changed some variable.

Next page | Contents page |