Skip to content

Instantly share code, notes, and snippets.

Created April 16, 2016 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/a52e2a3e25376e482c87e0e0fcf6fe35 to your computer and use it in GitHub Desktop.
Save anonymous/a52e2a3e25376e482c87e0e0fcf6fe35 to your computer and use it in GitHub Desktop.
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