Concurrency in Singleton Designing Pattern

      Please refer previous post for Singleton Designing Pattern. Concurrency is the one of the major issues with singleton designing pattern.

      There will be multiple client accessing same singleton resource instance. If this resource is mutable then concurrency need to be taken care . Example from previous post is being used here.

  1: package demo.singleton;
  2: import java.util.concurrent.locks.ReadWriteLock;
  3: import java.util.concurrent.locks.ReentrantReadWriteLock;
  4: /**
  5:  * Singleton Resource Class
  6:  * @author Yogesh
  7:  */
  8: public class SingletonResource {
  9:     private static SingletonResource resorce =null;
 10:     int count;
 11:     private ReadWriteLock writeLock = new ReentrantReadWriteLock();
 12: 
 13:     public static  SingletonResource getInstance(){
 14:         if(resorce ==null){
 15:             synchronized(SingletonResource.class){
 16:                 if(resorce==null){
 17:                     resorce = new SingletonResource();
 18:                 }
 19:             }
 20:         }
 21:         return resorce;
 22:     }
 23: 
 24:     private SingletonResource(){
 25:         // your initializing code here
 26:     }
 27:     
 28:     public void increament(){
 29:         writeLock.writeLock().lock();
 30:         count++;
 31:         writeLock.writeLock().unlock();            
 32:     }
 33:         
 34:      public void decreament(){
 35:         writeLock.writeLock().lock();
 36:         count--;
 37:         writeLock.writeLock().unlock();            
 38:     }
 39: }

Comments

  1. getInstance() method is implemented incorrectly. Multiple instances of SingletonResource may be created in two ways: two threads may pass the null test and then both create an instance, or since the resorce attribute is not marked as volatile, some threads may not see it being created...

    ReplyDelete

Post a Comment

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester