Consider the following class:
class Ideone
{
private Map<String, String> m;
public Ideone(){
synchronized(this){
m = new ConcurrentHashMap<>();
}
}
public synchronized Map<String, String> getM(){
return Collections.unmodifiableMap(m); //effectively immutable
}
}
In order to allow other classes to observe Ideone
's internal state, we should publish its internal state safely (with correct synchronization). If we don't do this, it's not guaranteed that another thread read the correct value (not the default one). For example:
public volatile Ideone ideone;
public void init(){
ideone = new Ideone();
}
I think if we didn't synchronize the construction and getter, like
class Ideone
{
private Map<String, String> m;
public Ideone(){
m = new ConcurrentHashMap<>();
}
public Map<String, String> getM(){
return Collections.unmodifiableMap(m); //effectively immutable
}
}
there would be no guarantees to observe the correct state value (default value, for instance).
But as said in this answer, such synchronization is not desirable as long as it allows this
to escape.
QUESTION: Why does the synchronization in a constructor allow this
to escape?
Ideone
asvolatile
is not sufficient to oberver a consistent state of the object, correct? – Judithjuditha