Tuesday, December 15, 2009

java.util.concurrent.CyclicBarrier JSR166

java.util.concurrent.CyclicBarrier

Assume the scenario, I have to transfer money from my bank account to my friend account. In the first phase, my account details and balance is verified and validate. Now, amount has to be debited in my account and creadited in my friend account. While commiting the changes in these two transaction, if any exception comes then these two activity has to be get informed. credit/debit operations are happening in multithreaded environment, How to achive this scenario. In older ages, we have to reiniate two more threads to rollback these operation.



CyclicBarrier helps us to achive this and intimate back to the threads who are all waiting for the commit operation, to take necessary action using the exception BrokenBarrierException. The CyclicBarrier uses an all-or-none breakage model for failed synchronization attempts. Common operation which needs to run at the end of multiple threads operation, will go in Runnable implementation.



We do not wants to do any special operation as common for all the threads, however we wants to end all the thread in same time. For example, first thread may take 5minutes to complete the operation, whereas second thread may take 1Hour to complete. Assume T2 has to complete prior to T1 thread completion, then CyclicBarrier has to instantiate without Runnable object.



import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) {
final CyclicBarrier cb = new CyclicBarrier(2, new Runnable() 
{
public void run() {
System.out.println("Commit Operation - Completed");
}
});

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T1 pre-commit");
try
{
cb.await();
}catch (Exception e)
{
//do something commit operation failed
}
System.out.println("T1 post-commit");
}
}.start();

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T2 pre-commit");
try
{
cb.await();
}catch (Exception e)
{
//do something commit operation failed
}
System.out.println("T2 post-commit");
}
}.start();
}
}

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com