Q:

How does "delegation" aid with thread-safe classes?

I don't really quite get the concept of "delegation" when we talk about constructing a thread-safe class. What does it mean? And how does the strategy effectively make a thread-safe class? And when can it fail ? Can someone give an example please?

A:

"Delegation" with respect to making a class thread-safe means that the class contains a reference of some other class object to which this class offloads the thread-safe operation. Consider , 
class Delegator {  
    private final AtomicInteger counter = new AtomicInteger(0);

  public int getNextCounter(){
      return counter.incrementAndGet();
   }
 }

Here the Delegator class has delegated the thread-safety to its component counter. Obviously the class could have taken the pain of doing the counter operation itself , but that would be reinventing wheel.
Delegation needs to be carefully used. If there is a state operation involving multiple variables ,then it is not sufficient that each of these variables operations be individually thread-safe , but there state transition together should also be thread-safe.

