8172204: Better Thread Pool execution
authorchegar
Mon, 13 Feb 2017 16:32:23 +0000
changeset 45978 882d720b3edf
parent 45977 20cce6a1312d
child 45979 51b7312baba3
8172204: Better Thread Pool execution Reviewed-by: alanb, skoivu, rriggs
jdk/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java
--- a/jdk/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Sun Feb 12 08:10:34 2017 -0800
+++ b/jdk/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Mon Feb 13 16:32:23 2017 +0000
@@ -35,6 +35,9 @@
 
 package java.util.concurrent;
 
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.ConcurrentModificationException;
 import java.util.HashSet;
@@ -584,6 +587,9 @@
     private static final RuntimePermission shutdownPerm =
         new RuntimePermission("modifyThread");
 
+    /* The context to be used when executing the finalizer, or null. */
+    private final AccessControlContext acc;
+
     /**
      * Class Worker mainly maintains interrupt control state for
      * threads running tasks, along with other minor bookkeeping.
@@ -1326,6 +1332,9 @@
             throw new IllegalArgumentException();
         if (workQueue == null || threadFactory == null || handler == null)
             throw new NullPointerException();
+        this.acc = System.getSecurityManager() == null ?
+                null :
+                AccessController.getContext();
         this.corePoolSize = corePoolSize;
         this.maximumPoolSize = maximumPoolSize;
         this.workQueue = workQueue;
@@ -1491,6 +1500,9 @@
      * Invokes {@code shutdown} when this executor is no longer
      * referenced and it has no threads.
      *
+     * <p>This method is invoked with privileges that are restricted by
+     * the security context of the caller that invokes the constructor.
+     *
      * @deprecated The {@code finalize} method has been deprecated.
      *     Subclasses that override {@code finalize} in order to perform cleanup
      *     should be modified to use alternative cleanup mechanisms and
@@ -1502,7 +1514,13 @@
      */
     @Deprecated(since="9")
     protected void finalize() {
-        shutdown();
+        SecurityManager sm = System.getSecurityManager();
+        if (sm == null || acc == null) {
+            shutdown();
+        } else {
+            PrivilegedAction<Void> pa = () -> { shutdown(); return null; };
+            AccessController.doPrivileged(pa, acc);
+        }
     }
 
     /**