Skip to content
Advertisement

Caching java instance for peformance

Please assist, What is meant by caching this line/new instance in java for example:

XPath xpath = XPathFactory.newInstance().newXPath();

I know I have to store insome sort of memory… may someone show me an example.

Thanks.

Advertisement

Answer

Caching means don’t let the garbage collector trashing your variable after you use it, if you already know that you will need to use the same variable a bit later (but the GC does not understand that).

It really depends on how long does the Xpath states last (may be function-scope, instance-scope or class-scope – or even a more reduced scope like a for loop or an if block, but that’s only you knowing it).

The below should help to understand:

Case 1 – inside a function

If you do this:

public Object doSomething() {
    //code...
    XPath xpath = XPathFactory.newInstance().newXPath();
    //code...
}

..then the garbage collector will think that once you’re out of the function you don’t need it anymore and so, it will trash it short after. Next time you call the function again, you will have to rebuild it from scratch.

Case 2 – as a class field

If you instead do this:

public class YourClass {
    
    private final XPath xpath = XPathFactory.newInstance().newXPath();

    public Object doSomething() {
        //code...
        this.xpath.use(...);
        //code...
    }

.. then you’re doing the job only once per instance created. If you create 10 instances of your class, you’ll do it 10 times. If you create just one, you’ll do it just once. And the garbage collector will preserve the value of each instance as long as that instance exists.

Case 3 – static field

But if this really never depends on anything, then it should be static:

public class YourClass {
    private static final XPath XPATH = XPathFactory.newInstance().newXPath();
    
    public Object doSomething() {
        //code...
        XPATH.use(...);
        //code...
    }        
}

… in this last case, no matter how many instances of the class you build, you’ll always have one and only one instance of Xpath, and the garbage collector will let the variable live in peace as long as your class is used / lies inside a class loader which contains used classes

(Small note: the static fields are initialized as soon as the Class is loaded by the ClassLoader, which loads that class and many others. The only case when the class becomes eligible to GC is when both that class and all the other classes of that class loader become unreachable. It is a very hard-to-reach state, meaning that usually, once a static field is initialized, you can be pretty safe it won’t be collected until you shut down your application).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement