wtorek, 8 stycznia 2013

Using guava cache to avoid expensive JAXBContext recreation

Creating JAXBContext is very expensive, especially when many classes are "known" to this context (just as a side note, a class is known to JAXBContext when it is in the package which name was passed to newInstance method or in the same package as class passed to newInstance method). Using guava's cache can be a very nice way of acheiving JAXBContext caching

private static final LoadingCache<String, JAXBContext> jaxbContextsCache = CacheBuilder.newBuilder()
            .build(
                    new CacheLoader<String, JAXBContext>() {
                        @Override
                        public JAXBContext load(String packageName) throws Exception {
                            return JAXBContext.newInstance(packageName);
                        }
                    }
            );

    public static JAXBContext getJAXBContext(Class clazz) {
        String packageName = clazz.getPackage().getName();
        try {
            return jaxbContextsCache.get(packageName);
        } catch (ExecutionException e) {
            throw new JaxbUtilsException("Error when getting JAXBContext from cache", e);
        }
    }

It is worth noting, that JAXBContext is thread safe, but Marshaller and Unmarshaller objects are not (at least by JAXB specification contract) and therefore should not be shared. You can implement some pooling if you need critical performance. This article explains marshaller/unmarshaller pooling and shows example code

Source code related to this post can be found on my git repository

Brak komentarzy:

Prześlij komentarz