How to prevent dead code being optimized by JVM?

162 views Asked by At
public class A
{
    public String getText()
    {
        Marker.start();
        ...
        ...
        Marker.end();
    }
}

public class Marker
{
    public static void start()
    {
        long now = System.currentTimeMillis;
    }

    public static void end()
    {
        long now = System.currentTimeMillis;
    }
}

I want to use JPDA (Java Platform Debugger Architecture) to detect the occurrence of Marker.start() and Marker.end() from external application. However I think the code may be optimized / eliminated away by JVM. How to prevent dead code being optimized by JVM?

1

There are 1 answers

1
Michał Kosmulski On

You could for example create a fake int variable somewhere in the class Marker and increment/decrement its value in the start() and end() methods. I don't think any optimizer could remove an instance field from a class even if the value is not used anywhere. After all, someone could always inject new agent code into the JVM and ask for the value. This means calls to start() and stop() shouldn't get optimized out, either.