Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * z2env.org - (c) ZFabrik Software KG
 * 
 * Licensed under Apache 2.
 * 
 * www.z2-environment.net
 */

import java.security.AccessController;

import java.security.PrivilegedExceptionAction;
import java.util.concurrent.Callable;

public class Main {
    /**
     * Stupid... but there is places all over that hold on to
     * AccessControlContexts and Context Class Loaders. This easily consitutes a
     * leak. So, for stuff that doesn't need anything from the context class
     * loader this is a way of keeping context to a minimum;
     * 
     * 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 propagated.
     * 
     * @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
     * @throws Exception
     */
    public static <T> T cleanContextExceptionExecute(ClassLoader contextLoader, final Callable<T> callable)
            throws Exception {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(contextLoader);
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {
                public T run() throws Exception {
                    return callable.call();
                }
            });
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }

    /**
     * Short version of {@link #cleanContextExceptionExecute(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
     * @throws Exception
     */
    public static <T> T cleanContextExceptionExecute(final Callable<T> callable) throws Exception {
        return cleanContextExceptionExecute(null, callable);
    }
}