I was going through some random java code and came across this peice of code, I am trying to understand the flow and having hard time understanding how the actual implementation of the class, actual operation done by the class so my basic questions is WhatDoIDo class actually do ? Any guidance would be apprecaited.
Q:
What would be the unit test case which explains the improved performance because of implementing in the concurrent environment.
Code
public class WhatDoIDo{
private X x;
private boolean b;
private Object o;
public WhatDoIDo(X x) {
this.x = x;
}
synchronized Object z() {
if (!b) {
o = x.y();
b = true;
}
return o;
}
public interface X {
Object y();
}
}
WhatDoIDois a wrapper class that wraps an objecto.It defines an inner
interface Xwhich has a methody()to create anObject. This interface can be thought of as a strategy for creating the object. When an object ofWhatDoIDois created usingnew, it’s constructor is supplied with an object ofXthat will be used to create the object.It creates the wrapped object and makes it available to client code through
z()method. It creates the object lazily. It uses abooleanflagbto keep track of whether the object has been created or not. Whenz()is called by client to get hold of the wrapped object, if the flag is set, the objectois returned. If flag is not set, an object is created using the strategyXsupplied when creating thisWhatDoIDoobject. A reference to the created object is stored and returned to the client. Also,z()issynchronizedsince it creates the object if it has not been created already. If it was not synchronized, two threads could end up creating an object each and only one of them will get stored.