Search code examples
javajvmjit

Will JVM optimization break down my code?


I have the following method which is being called by multiple threads:

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();
}

Is it possible that the JVM optimizer will comment out the code marked as (1) in above given menthod? I am suspecting that because, the existence of directory is checked twice in immediate succession. Considering it as a unnecessary redundant checking JVM optimizer might comment out the line --> (1).


Solution

  • As pointed out by @yshavit

    Because the File methods are going to eventually end up as OS calls, and the JVM can't assume those don't have side effects (and aren't affected by state other than their arguments) so, the JVM will not optimize the code involving if(!file.exists() || !file.isDirectory()) by commenting out that section .