class MyClass
{
private static volatile Resource resource;
public static Resource getInstance()
{
if(resource == null)
resource = new Resource();
return resource;
}
}
Here if the Resource is a immutable class, is it safe to write the above code? As in java concurrency in practice it's mentioned that "initialization safety allow properly constructed immutable objects to be safely shared across thread.So the above code is safe to be written." (in page no 349 16.3). But with this it may possible if two threads checks for the null and they can proceed for object creation which is against the invariant of the class (singleton). please explain. A continuation of the question in link