Double Checked Locking With Thread

While implementing a circular non-blocking queue, we observed a pattern which could boost a performance.

When you have condition based thread safe block, it is always advisable to check same condition before and after lock.

Before lock will avoid threads to get locked unnecessarily and after lock will ensure that any state change within synchronized block does not violate protocol.

In detail, for example, there are ‘n’ threads entering into this piece of code and say queue(ConcurrentLinkedQueue) is full, If queue is not full we should not lock threads, hence check at Line 1, All thread will wait at line 2. First thread (whichever will get CPU based on OS priority/roundrobin mechanism for processes) will enter and modify queue at line 4. Because of this, queue may not satisfy condition for other waiting threads, so thread entering second should not run code if condition is not satisfied, hence check at line 3. We could omit line 1 actually but adding it will have performance boost especially when condition is important to pass before entering to synchronized block.

   if (this. linkedThreadSafeQueue.size() == this.maxLimit) {
      synchronized(this.linkedThreadSafeQueue) {
          if (this. linkedThreadSafeQueue.size() == this. maxLimit) {
                        //Modify queue

This helps when developer is dealing with singleton (condition based) and multithread implementation where he does not want to initialize same object again and also not to lock thread unnecessarily.