executors.java

来自「SRI international 发布的OAA框架软件」· Java 代码 · 共 661 行 · 第 1/2 页

JAVA
661
字号
    }

    /**
     * Returns a {@link Callable} object that, when
     * called, runs the given privileged action and returns its result.
     * @param action the privileged action to run
     * @return a callable object
     * @throws NullPointerException if action null
     */
    public static Callable callable(PrivilegedAction action) {
        if (action == null)
            throw new NullPointerException();
        return new PrivilegedActionAdapter(action);
    }

    /**
     * Returns a {@link Callable} object that, when
     * called, runs the given privileged exception action and returns
     * its result.
     * @param action the privileged exception action to run
     * @return a callable object
     * @throws NullPointerException if action null
     */
    public static Callable callable(PrivilegedExceptionAction action) {
        if (action == null)
            throw new NullPointerException();
        return new PrivilegedExceptionActionAdapter(action);
    }

    /**
     * Returns a {@link Callable} object that will, when
     * called, execute the given <tt>callable</tt> under the current
     * access control context. This method should normally be
     * invoked within an {@link AccessController#doPrivileged} action
     * to create callables that will, if possible, execute under the
     * selected permission settings holding within that action; or if
     * not possible, throw an associated {@link
     * java.security.AccessControlException}.
     * @param callable the underlying task
     * @return a callable object
     * @throws NullPointerException if callable null
     *
     */
    public static Callable privilegedCallable(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        return new PrivilegedCallable(callable);
    }

    /**
     * Returns a {@link Callable} object that will, when
     * called, execute the given <tt>callable</tt> under the current
     * access control context, with the current context class loader
     * as the context class loader. This method should normally be
     * invoked within an {@link AccessController#doPrivileged} action
     * to create callables that will, if possible, execute under the
     * selected permission settings holding within that action; or if
     * not possible, throw an associated {@link
     * java.security.AccessControlException}.
     * @param callable the underlying task
     *
     * @return a callable object
     * @throws NullPointerException if callable null
     * @throws java.security.AccessControlException if the current access control
     * context does not have permission to both set and get context
     * class loader.
     */
    public static Callable privilegedCallableUsingCurrentClassLoader(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        return new PrivilegedCallableUsingCurrentClassLoader(callable);
    }

    // Non-public classes supporting the public methods

    /**
     * A callable that runs given task and returns given result
     */
    static final class RunnableAdapter implements Callable {
        final Runnable task;
        final Object result;
        RunnableAdapter(Runnable  task, Object result) {
            this.task = task;
            this.result = result;
        }
        public Object call() {
            task.run();
            return result;
        }
    }

    /**
     * A callable that runs given privileged action and returns its result
     */
    static final class PrivilegedActionAdapter implements Callable {
        PrivilegedActionAdapter(PrivilegedAction action) {
            this.action = action;
        }
        public Object call () {
            return action.run();
        }
        private final PrivilegedAction action;
    }

    /**
     * A callable that runs given privileged exception action and returns its result
     */
    static final class PrivilegedExceptionActionAdapter implements Callable {
        PrivilegedExceptionActionAdapter(PrivilegedExceptionAction action) {
            this.action = action;
        }
        public Object call () throws Exception {
            return action.run();
        }
        private final PrivilegedExceptionAction action;
    }


    /**
     * A callable that runs under established access control settings
     */
    static final class PrivilegedCallable implements Callable {
        private final AccessControlContext acc;
        private final Callable task;
        private Object result;
        private Exception exception;
        PrivilegedCallable(Callable task) {
            this.task = task;
            this.acc = AccessController.getContext();
        }

        public Object call() throws Exception {
            AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        try {
                            result = task.call();
                        } catch(Exception ex) {
                            exception = ex;
                        }
                        return null;
                    }
                }, acc);
            if (exception != null)
                throw exception;
            else
                return result;
        }
    }

    /**
     * A callable that runs under established access control settings and
     * current ClassLoader
     */
    static final class PrivilegedCallableUsingCurrentClassLoader implements Callable {
        private final ClassLoader ccl;
        private final AccessControlContext acc;
        private final Callable task;
        private Object result;
        private Exception exception;
        PrivilegedCallableUsingCurrentClassLoader(Callable task) {
            this.task = task;
            this.ccl = Thread.currentThread().getContextClassLoader();
            this.acc = AccessController.getContext();
            acc.checkPermission(new RuntimePermission("getContextClassLoader"));
            acc.checkPermission(new RuntimePermission("setContextClassLoader"));
        }

        public Object call() throws Exception {
            AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        ClassLoader savedcl = null;
                        Thread t = Thread.currentThread();
                        try {
                            ClassLoader cl = t.getContextClassLoader();
                            if (ccl != cl) {
                                t.setContextClassLoader(ccl);
                                savedcl = cl;
                            }
                            result = task.call();
                        } catch(Exception ex) {
                            exception = ex;
                        } finally {
                            if (savedcl != null)
                                t.setContextClassLoader(savedcl);
                        }
                        return null;
                    }
                }, acc);
            if (exception != null)
                throw exception;
            else
                return result;
        }
    }

    /**
     * The default thread factory
     */
    static class DefaultThreadFactory implements ThreadFactory {
        static final AtomicInteger poolNumber = new AtomicInteger(1);
        final ThreadGroup group;
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null)? s.getThreadGroup() :
                                 Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    /**
     *  Thread factory capturing access control and class loader
     */
    static class PrivilegedThreadFactory extends DefaultThreadFactory {
        private final ClassLoader ccl;
        private final AccessControlContext acc;

        PrivilegedThreadFactory() {
            super();
            this.ccl = Thread.currentThread().getContextClassLoader();
            this.acc = AccessController.getContext();
            acc.checkPermission(new RuntimePermission("setContextClassLoader"));
        }

        public Thread newThread(final Runnable r) {
            return super.newThread(new Runnable() {
                public void run() {
                    AccessController.doPrivileged(new PrivilegedAction() {
                        public Object run() {
                            Thread.currentThread().setContextClassLoader(ccl);
                            r.run();
                            return null;
                        }
                    }, acc);
                }
            });
        }

    }

   /**
     * A wrapper class that exposes only the ExecutorService methods
     * of an implementation.
     */
    static class DelegatedExecutorService extends AbstractExecutorService {
        private final ExecutorService e;
        DelegatedExecutorService(ExecutorService executor) { e = executor; }
        public void execute(Runnable command) { e.execute(command); }
        public void shutdown() { e.shutdown(); }
        public List shutdownNow() { return e.shutdownNow(); }
        public boolean isShutdown() { return e.isShutdown(); }
        public boolean isTerminated() { return e.isTerminated(); }
        public boolean awaitTermination(long timeout, TimeUnit unit)
            throws InterruptedException {
            return e.awaitTermination(timeout, unit);
        }
        public Future submit(Runnable task) {
            return e.submit(task);
        }
        public Future submit(Callable task) {
            return e.submit(task);
        }
        public Future submit(Runnable task, Object result) {
            return e.submit(task, result);
        }
        public List invokeAll(Collection tasks) throws InterruptedException {
            return e.invokeAll(tasks);
        }
        public List invokeAll(Collection tasks,
                              long timeout, TimeUnit unit)
            throws InterruptedException {
            return e.invokeAll(tasks, timeout, unit);
        }
        public Object invokeAny(Collection tasks)
            throws InterruptedException, ExecutionException {
            return e.invokeAny(tasks);
        }
        public Object invokeAny(Collection tasks,
                                long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
            return e.invokeAny(tasks, timeout, unit);
        }
    }

    /**
     * A wrapper class that exposes only the ExecutorService and
     * ScheduleExecutor methods of a ScheduledExecutorService implementation.
     */
    static class DelegatedScheduledExecutorService
            extends DelegatedExecutorService
            implements ScheduledExecutorService {
        private final ScheduledExecutorService e;
        DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
            super(executor);
            e = executor;
        }
        public ScheduledFuture schedule(Runnable command, long delay,  TimeUnit unit) {
            return e.schedule(command, delay, unit);
        }
        public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) {
            return e.schedule(callable, delay, unit);
        }
        public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay,  long period, TimeUnit unit) {
            return e.scheduleAtFixedRate(command, initialDelay, period, unit);
        }
        public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay,  long delay, TimeUnit unit) {
            return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
        }
    }


    /** Cannot instantiate. */
    private Executors() {}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?