我有以下方法被多个线程调用:
private final static Object lock = new Object();
public String createDirectory()
{
File file = new File("D:"+File.separator+"test");
if(!file.exists() || !file.isDirectory())//if file doesn't exist then create a new directory.
{
synchronized(lock)
{
if(!file.exists() || !file.isDirectory())//----> (1)
{
boolean isCreated = file.mkdir();
}
}
}
return file.getAbsolutePath();
}
JVM优化器是否有可能注释掉上面给定方法中标记为(1)的代码?我怀疑这是因为,目录的存在被立即连续检查两次。将其视为不必要的冗余检查 JVM 优化器可能会注释掉 --> (1) 行。
最佳答案
没有。它不会被优化掉。
如果 JVM 优化了标准的双重检查锁定模式,那就有点垃圾了。
关于java - JVM 优化会破坏我的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24273146/