Here is my problem. I want to document a piece of program and want to express something, I believed quite common among the programming community, but can't hack the idea into a word. Take a look at this class :
public class RemoteClient {
private InetSocketAddress remoteAddress;
/*+ some other fields not in the scope of this topic*/
public RemoteClient(String hostName, int port
/*+ some other arguments not in the scope of this topic*/){
this.remoteAddress=new InetSocketAddress(hostName, port);
}
public InetSocketAddress getRemoteAddress() {
return this.remoteAddress;
}
}
The obvious problem in a multithreaded environment is that the caller of the constructor has no guaranty that hostName
will be resolved, and therefore build time is not deterministic. It would be, I believe, much better if the construction of InetSocketAddress
was lazy, such as follow :
public class RemoteClient {
private volatile InetSocketAddress remoteAddress;
private final String hostName;
private final int port;
/*+ some other fields not in the scope of this topic*/
public RemoteClient(String hostName, int port
/*+ some other arguments not in the scope of this topic*/){
this.hostName=hostName;
this.port=port;
}
/** lazy instanciation **/
public InetSocketAddress getRemoteAddress() {
if(remoteAddress==null){
synchronized(hostName){
if(remoteAddress==null){
this.remoteAddress=new InetSocketAddress(hostName, port);
}
}
}
return this.remoteAddress;
}
}
So in this case, the Thread
calling the constructor operator, which might at some time build from a list of host names, has no more network-related indetermination. It is now delegated to the Thread
in charge of communication with the remote client.
- My questions are :
- can you give reasons why the second proposition is/isn't better designed?
- could you put a word on the idiom behind this practice ?
I believe this is not a opinion-based topic, as I'm asking for a design.