Java tutorial
//package com.java2s; /* * z2env.org - (c) ZFabrik Software KG * * Licensed under Apache 2. * * www.z2-environment.net */ import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.Callable; public class Main { /** * Execute a callable with a clean thread context and security context as * to avoid any passing on of thread context and security context to another * thread that may be spawned from here and may end up holding copies in the end. * Any exception thrown will be forwarded via a generic runtime exception. * * @param contextLoader A class loader to set as context class loader * @param callable A {@link Callable} to invoke * @return Return value from the {@link Callable} invocation */ public static <T> T cleanContextExecute(ClassLoader contextLoader, final Callable<T> callable) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(contextLoader); try { return AccessController.doPrivileged(new PrivilegedAction<T>() { public T run() { try { return callable.call(); } catch (Exception e) { throw new RuntimeException(e); } } }); } finally { Thread.currentThread().setContextClassLoader(cl); } } /** * Short version of {@link #cleanContextExecute(ClassLoader, Callable)} passing in <code>null</code> * as context class loader. * * @param callable A {@link Callable} to invoke * @return Return value from the {@link Callable} invocation */ public static <T> T cleanContextExecute(final Callable<T> callable) { return cleanContextExecute(null, callable); } }