Tuesday, February 08, 2005

Make an Object Thread-Safe - 1

(1) Synchronize critical sections within the code

Restrict access to that resource such that only one thread can update the resource at any point of time -- make it thread safe.

To do that we must identify and synchronize its critical sections. A critical sectoin is piece of code in the program that may be accessed by multiple threads at the same time to update the state of the object. Let’s say we have a method Withdraw() and it will be accessed from many threads, we need to make WIthdraw() method thread-safe. We do that by synchronize the Withdraw() method so that only one thread can access it at any one time.

Lines of code (statements) that cannot be interrupted during its execution is said to be atomic. An atomic process are unitse of code that execute as one complete unit -- as if they were a single statement. By making Withdraw() method atomic, no other thread can call it until the calling thread has finished executing Withdraw().

(2) Make the object immutable

An immutable object is one whose state can’t be changed once the object has been created. The critical sections that change the instance variable of the object are changed so that, instead of changing the state of the current object, a new object is created that embodies the new state and a reference to that new object is returned. In this way, there is no need to lock the the critical section because no methods of an immutable object actually writes to the object’s instance variable.

(3) Use a thread-safe wrapper

In this strategy, a thread-safe wrapper class is written over the object that will be thread-safe, rather than making the object thread-safe. THe object will remain unchanged and the new wrapper class will contain synchronized sections of thread-safe code.

0 Comments:

Post a Comment

<< Home