Mac
Mac

Reputation: 1495

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).

Upvotes: 0

Views: 243

Answers (3)

Mac
Mac

Reputation: 1495

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 .

Upvotes: 1

Isaac
Isaac

Reputation: 16736

No. Compiler optimizations don't alter a program's flow. Specifically, method invocations will never be skipped.

Upvotes: 1

JonathanS
JonathanS

Reputation: 321

No. It will not be optimized out.

It would be a bit rubbish if the JVM optimized out a standard double check lock pattern.

Upvotes: 1

Related Questions