Java – put expensive resource creation in static blocks?

I am using JAXB version 2.0 To do this, I create a jaxbcontext object as follows:

package com;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

public class JAXBContextFactory {

    public static JAXBContext createJAXBContext() throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        return jaxbContext;
    }

}

Basically, because creating jaxbcontext is very expensive, I want to create jaxbcontext once and only once for the whole application So I put the jaxbcontext code under the static method, as shown above

The request will now call jaxbcontextfactory createJAXBContext(); Whenever it needs to reference jaxbcontext Now my question is, in this case, is jaxbcontext created only once, or does the application have multiple jaxbcontext instances?

Solution

Every time this method is called, your application will have a jaxbcontext instance

If you do not want this to happen, you need to do the following

package com;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

public class JAXBContextFactory {

    private static JAXBContext context = null;
    public static synchronized JAXBContext createJAXBContext() throws JAXBException {
        if(context == null){
            context = JAXBContext.newInstance(Customer.class);
        }
        return context;
    }

}

The difference between this and your implementation is that in this one, we save the jaxbcontext instance created in the static variable (guaranteed to exist only once) In your implementation, you will not save the instance just created anywhere, and a new instance will be created every time the method is called Important: don't forget to add the synchronized keyword to the method declaration, because it ensures that calling this method in a multithreading environment will still work as expected.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>