In the openJDK source code, the System.console() was implemented as such:
private static volatile Console cons = null;
/**
* Returns the unique {@link java.io.Console Console} object associated
* with the current Java virtual machine, if any.
*
* @return The system console, if any, otherwise <tt>null</tt>.
*
* @since 1.6
*/
public static Console console() {
if (cons == null) {
synchronized (System.class) {
cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
}
}
return cons;
}
IMO, this implementation is lack of the double-checked locking, say the null test inside the synchronized block is absent. In this case assuming 2 threads, thread I gets into the synchronized monitor and, in the same time thread II coincidentally gets blocked on the same synchronized monitor, as a result, thread II would also get chance to call the cons = sun.misc.SharedSecrets.getJavaIOAccess().console(); to initialized the Console object again
Question: Why isn't the double-checked locking used properly in this case? Is this really a flaw of the openJDK?
It's likely because the
Consoleobject returned bysun.misc.SharedSecrets.getJavaIOAccess().console()is already initialised as a static-block singleton anyway. The worst that could happen is thatconsgets set to the same thing again.Is it ideal? Probably not. Is it intentional? Maybe. Will it cause side effects? I don't think so.