Skip to content

Instantly share code, notes, and snippets.

Created Apr 16, 2016
Embed
What would you like to do?
import static com.google.common.base.Throwables.getRootCause;
import static com.google.common.base.Throwables.propagate;
import java.util.concurrent.ExecutionException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Singleton;
@Singleton
public class JAXBContextHolder {
private final LoadingCache<Class, JAXBContext> cache =
CacheBuilder.newBuilder()
.build(new CacheLoader<Class, JAXBContext>() {
@Override
public JAXBContext load(Class clazz) throws Exception {
return getNewJAXBContext(clazz);
}
});
public JAXBContext getContext(Class clazz) {
try {
return cache.get(clazz);
} catch (ExecutionException e) {
throw propagate(getRootCause(e));
}
}
@VisibleForTesting
JAXBContext getNewJAXBContext(Class clazz) throws JAXBException {
return JAXBContext.newInstance(clazz);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment