ExecutorService thread pool shutdown exception

Hello,
We are developing a desktop application (no applets etc) on the Netbeans plaform. I am trying to add a thread pool via the Java5 ExecutorService. I think we have a very standard implementation using static methods - we copied it from some basic examples in blogs. Please see the class below.
Everything seems OK until I try to run shutdown. During the application shutdown we catch an exception that says
access denied (java.lang.RuntimePermission modifyThread)The exception is raised when running the ExecutorService "shutdown()" method.
Please note that this is a desktop application, and we DO check the permission with the SecurityManager (see code) and we do seem to have the correct permission (no exception raised during check).
Firstly, this is the first time we've used ExecutorService, so maybe we just have just implemented it incorrectly. Secondly, all "googling" on the issue reveals very little. It only seems to happen to applets.
ANY SUGGESTIONS, ADVICE, GUIDANCE, HINTS would be MUCH appreciated.
public final class ThreadPool {
    private static ExecutorService threadPool = Executors.newFixedThreadPool(3);
    public static void execute(Runnable worker) {
        threadPool.submit(worker);
    public static void shutdown() {
        SecurityManager s = System.getSecurityManager ();
        if (s!=null) {
            try {
                s.checkPermission(new RuntimePermission("modifyThread"));
                // we apparently have permission, so proceed to shutdown ...
                threadPool.shutdown();  // EXCEPTION RAISED HERE !!!!!
                threadPool.awaitTermination(15L, TimeUnit.SECONDS);
                threadPool.shutdownNow(); // brutal mop up
            } catch (Exception e) {
                logger.warn("ThreadPool.shutdown(): ex=" + e.getMessage());
}

You don't explain the context in which this application is launched - applications can be restricted by security policies too.
shutdown requires two permissions: one from the installed SecurityManager if any, and the other directly from the AccessController. Your installed SecurityManager may be saying "yes" while the AccessController says "no". There is a change in Java 6 such that only the security manager is queried.

Similar Messages

  • ExecutorService - thread pool

    I am using a thread pool to handle requests. Is there a way to know who is doing what?
    This is the code I used to assign new tasks to my pool:
    for (;;) {
    this.pool.execute(new Handler(this.sSocket.accept(),Identifier);
    Is there a way to get the thread that will execute it?

    You don't explain the context in which this application is launched - applications can be restricted by security policies too.
    shutdown requires two permissions: one from the installed SecurityManager if any, and the other directly from the AccessController. Your installed SecurityManager may be saying "yes" while the AccessController says "no". There is a change in Java 6 such that only the security manager is queried.

  • Thread Pool "Null Pointer" exception

    Hello,
    I have an embarrassingly parallel algorithm. The parallel part is solved by 2 objects called shifters which implement the Runnable interface. However, for reasons I can't figure out, sometimes my code will randomly output this error.
    Exception in thread "pool-1-thread-1" java.lang.NullPointerException
    at cvtpmshiftlabnormalized.Shifter.run(Shifter.java:63)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    Exception in thread "pool-1-thread-2" java.lang.NullPointerException
    at cvtpmshiftlabnormalized.Shifter.run(Shifter.java:63)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    My code concerning the parallelization is as follows:
            shifter_1 = new Shifter(list_1 , clusterTree);
            shifter_2 = new Shifter(list_2 , clusterTree);
            ExecutorService executor = Executors.newFixedThreadPool(5);
            executor.execute(shifter_1);
            executor.execute(shifter_2);
            executor.shutdown();Any help would be greatly appreciated, seeing how my computer throws this error for the same data set whenever it feels like it.
    Sincerely,
    Chem E

    Here is the run() method of the shifter. It's pretty big, but I don't know what you would want to look at , and what is garbage.. Thanks for helping me.
    public void run()
            ArrayList<Cluster> neighbors = new ArrayList();
            ArrayList<Cluster> removeUs  = new ArrayList();
            double resultantVector[] = new double[3];
            double dotProduct;
            double gaussian;
            double gaussianWeight;
            while(workingClusters.size() > 0)
                workingClusters.removeAll(removeUs);
                removeUs.clear();
                System.out.println("Working Clusters: " + workingClusters.size());
                for(Cluster cluster : workingClusters)
                    neighbors.clear();
                    neighbors = clusterTree.returnNeighbors(cluster.values, returnRange);
                    clusterTree.remove(cluster);
                    resultantVector[0] = 0;
                    resultantVector[1] = 0;
                    resultantVector[2] = 0;
                    gaussianWeight = 0;
                    for(Cluster nCluster : neighbors)
                         dotProduct = dotProduct( cluster.values, nCluster.values);
                         gaussian = Math.exp(-dotProduct / Math.pow(returnRange , 2));
                         resultantVector[0] += gaussian * nCluster.values[0] * nCluster.weight;
                         resultantVector[1] += gaussian * nCluster.values[1] * nCluster.weight;
                         resultantVector[2] += gaussian * nCluster.values[2] * nCluster.weight;
                         gaussianWeight += gaussian * nCluster.weight;
                    if(neighbors.size() > 0)
                        resultantVector[0] /= gaussianWeight;
                        resultantVector[1] /= gaussianWeight;
                        resultantVector[2] /= gaussianWeight;
                        if(dotProduct(resultantVector , cluster.values) < 0.01)
                            removeUs.add(cluster);
                        cluster.values[0] = resultantVector[0];
                        cluster.values[1] = resultantVector[1];
                        cluster.values[2] = resultantVector[2];
                    clusterTree.put(cluster);
        }

  • Thread pool throws reject exceptions even though the queue is not full

    Hi. I am using org.springframework.scheduling.concurrent.ThreadPo olTaskExecutor which is based on java
    java.util.concurrent.ThreadPoolExecutor
    with a enviornment under load.
    I see on some cases, that this thread pool throws tasks with reject exception
    even though the queue size is 0.
    According to the documentation, this thread pool should increase the pool size to core size and then wait untill all queue is full to create new threads.
    this is not what happends. for some reason the queue is not filled but exceptions are thrown.
    Any ideas why this can happen?

    This is the stack trace:
    taskExecutorStats-1 2010-04-27 11:01:43,324 ERROR [com.expand.expandview.infrastructure.task_executor] TaskExecutorController: RejectedExecutionException exception in thread: 18790970, failed on thread pool: [email protected]544f07, to run logic: com.expand.expandview.infrastructure.logics.DispatchLogicsProviderLogic
    org.springframework.core.task.TaskRejectedException: Executor [java.util.concurrent.ThreadPoolExecutor@dd9007] did not accept task: com.expand.expandview.infrastructure.task_executor.TaskExecuterController$1@141f728; nested exception is java.util.concurrent.RejectedExecutionException
         at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:305)
         at com.expand.expandview.infrastructure.task_executor.TaskExecuterController.operate(TaskExecuterController.java:68)
         at com.expand.expandview.infrastructure.proxies.DataProxy.callLogic(DataProxy.java:131)
         at com.expand.expandview.infrastructure.proxies.DataProxy.operate(DataProxy.java:109)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.operate(AbstractLogic.java:455)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterSingleChunkLogic.persistSlots(StatsPersisterSingleChunkLogic.java:362)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterSingleChunkLogic.doLogic(StatsPersisterSingleChunkLogic.java:132)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.execute(AbstractLogic.java:98)
         at com.expand.expandview.server.app.logics.ApplicationLogic.execute(ApplicationLogic.java:79)
         at com.expand.expandview.infrastructure.task_executor.TaskExecuterControllerDirect.operate(TaskExecuterControllerDirect.java:33)
         at com.expand.expandview.infrastructure.proxies.LogicProxy.service(LogicProxy.java:62)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.service(AbstractLogic.java:477)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterLogic.persist(StatsPersisterLogic.java:48)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterLogic.doLogic(StatsPersisterLogic.java:19)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.execute(AbstractLogic.java:98)
         at com.expand.expandview.server.app.logics.ApplicationLogic.execute(ApplicationLogic.java:79)
         at com.expand.expandview.infrastructure.task_executor.TaskExecuterController$1.run(TaskExecuterController.java:80)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
         at java.lang.Thread.run(Thread.java:619)
    Caused by: java.util.concurrent.RejectedExecutionException
         at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1760)
         at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
         at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
         at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:302)
         ... 19 more

  • Fixed size thread pool excepting more tasks then it should

    Hello,
    I have the following code in a simple program (code below)
              BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10, false);
              ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, 10, 20, TimeUnit.SECONDS, q);
    for (int x = 0; x < 30; x++) {
    newPool.execute(new threaded());
    My understanding is that this should create a thread pool that will accept 10 tasks, once there have been 10 tasks submitted I should get RejectedExecutionException, however; I am seeing that when I execute the code the pool accepts 20 execute calls before throwing RejectedExecutionException. I am on Windows 7 using Java 1.6.0_21
    Any thoughts on what I am doing incorrectly?
    Thanks
    import java.util.concurrent.*;
    public class ThreadPoolTest {
         public static class threaded implements Runnable {
              @Override
              public void run() {
                   System.out.println("In thread: " + Thread.currentThread().getId());
                   try {
                        Thread.sleep(5000);
                   } catch (InterruptedException e) {
                        System.out.println("Thread: " + Thread.currentThread().getId()
                                  + " interuptted");
                   System.out.println("Exiting thread: " + Thread.currentThread().getId());
         private static int MAX = 10;
         private Executor pool;
         public ThreadPoolTest() {
              super();
              BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(MAX/2, false);
              ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, MAX, 20, TimeUnit.SECONDS, q);
              pool = newPool;
         * @param args
         public static void main(String[] args) {
              ThreadPoolTest object = new ThreadPoolTest();
              object.doThreads();
         private void doThreads() {
              int submitted = 0, rejected = 0;
              for (int x = 0; x < MAX * 3; x++) {
                   try {
                        System.out.println(Integer.toString(x) + " submitting");
                        pool.execute(new threaded());
                        submitted++;
                   catch (RejectedExecutionException re) {
                        System.err.println("Submission " + x + " was rejected");
                        rejected++;
              System.out.println("\n\nSubmitted: " + MAX*2);
              System.out.println("Accepted: " + submitted);
              System.out.println("Rejected: " + rejected);
    }

    I don't know what is wrong because I tried this
    public static void main(String args[])  {
        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10, false);
        ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, 10, 20, TimeUnit.SECONDS, q);
        for (int x = 0; x < 100; x++) {
            System.err.println(x + ": " + q.size());
            newPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Thread.sleep(1000);
                    return null;
    }and it printed
    0: 0
    1: 0
    2: 1
    3: 2
    4: 3
    5: 4
    6: 5
    7: 6
    8: 7
    9: 8
    10: 9
    11: 10
    12: 10
    13: 10
    14: 10
    15: 10
    16: 10
    17: 10
    18: 10
    19: 10
    20: 10
    Exception in thread "main" java.util.concurrent.RejectedExecutionException
         at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1768)
         at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
         at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
         at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:92)
         at Main.main(Main.java:36)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)Ihave Java 6 update 24 on Linux, but I don't believe this should make a difference. Can you try my code?

  • Out Of Memory Exception with Thread Pool

    Hi,
    I'm using the ThreadPooling, and I have a problem. In my usage, I submit a bunch of tasks to my application, and i have a pool of THREADS, so while executing these tasks i am getting the following errot :
    Exception in thread "pool-1-thread-271" java.lang.OutOfMemoryError: Java heap space
    I am not able to understand, what could be the reason to get this error, please help me
    any one who knows it .

    a few things to consider
    1. increasing the heap size
    2. you could have a memory leak
    3. your app could just be creating too many/large objects and need redesign

  • How can I use the same thread pool implementation for different tasks?

    Dear java programmers,
    I have written a class which submits Callable tasks to a thread pool while illustrating the progress of the overall procedure in a JFrame with a progress bar and text area. I want to use this class for several applications in which the process and consequently the Callable object varies. I simplified my code and looks like this:
            threadPoolSize = 4;
            String[] chainArray = predock.PrepareDockEnvironment();
            int chainArrayLength = chainArray.length;
            String score = "null";
            ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
            CompletionService<String> referee = new ExecutorCompletionService<String>(executor);
            for (int i = 0; i < threadPoolSize - 1; i++) {
                System.out.println("Submiting new thread for chain " + chainArray);
    referee.submit(new Parser(chainArray[i]));
    for (int chainIndex = threadPoolSize; chainIndex < chainArrayLength; chainIndex++) {
    try {
    System.out.println("Submiting new thread for chain " + chainArray[chainIndex]);
    referee.submit(new Parser(chainArray[i]));
    score = referee.poll(10, TimeUnit.MINUTES).get();
    System.out.println("The next score is " + score);
    executor.shutdown();
    int index = chainArrayLength - threadPoolSize;
    score = "null";
    while (!executor.isTerminated()) {
    score = referee.poll(10, TimeUnit.MINUTES).get();
    System.out.println("The next score is " + score);
    index++;
    My question is how can I replace Parser object with something changeable, so that I can set it accordingly whenever I call this method to conduct a different task?
    thanks,
    Tom                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    OK lets's start from the beginning with more details. I have that class called ProgressGUI which opens a small window with 2 buttons ("start" and "stop"), a progress bar and a text area. It also implements a thread pool to conducts the analysis of multiple files.
    My main GUI, which is much bigger that the latter, is in a class named GUI. There are 3 types of operations which implement the thread pool, each one encapsulated in a different class (SMAP, Dock, EP). The user can set the necessary parameters and when clicking on a button, opens the ProgressGUI window which depicts the progress of the respective operation at each time step.
    The code I posted is taken from ProgressGui.class and at the moment, in order to conduct one of the supported operations, I replace "new Parser(chainArray)" with either "new SMAP(chainArray[i])", "new Dock(chainArray[i])", "new EP(chainArray[i])". It would be redundant to have exactly the same thread pool implementation (shown in my first post) written 3 different times, when the only thing that needs to be changed is "new Parser(chainArray[i])".
    What I though at first was defining an abstract method named MainOperation and replace "new Parser(chainArray[i])" with:
    new Callable() {
      public void call() {
        MainOperation();
    });For instance when one wants to use SMAP.class, he would initialize MainOperation as:
    public abstract String MainOperation(){
        return new SMAP(chainArray));
    That's the most reasonable explanation I can give, but apparently an abstract method cannot be called anywhere else in the abstract class (ProgressGUI.class in my case).
    Firstly it should be Callable not Runnable.Can you explain why? You are just running a method and ignoring any result or exception. However, it makes little difference.ExecutorCompletionService takes Future objects as input, that's why it should be Callable and not Runnable. The returned value is a score (String).
    Secondly how can I change that runMyNewMethod() on demand, can I do it by defining it as abstract?How do you want to determine which method to run?The user will click on the appropriate button and the GUI will initialize (perhaps implicitly) the body of the abstract method MainOperation accordingly. Don't worry about that, this is not the point.
    Edited by: tevang2 on Dec 28, 2008 7:18 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Thread Pool , Executors ...

    Sorry if i make a stupid post now, but i'm looking for a implementation of a Thread Pool using the latest 1.5 java.util.concurrent classes and i can't find anything serious. Any implementation or link to a tutorial should be vary helpful.
    Thnx

    but i'm looking
    for a implementation of a Thread Pool using
    the latest 1.5 java.util.concurrent classes and i
    can't find anything serious. Any implementation or
    link to a tutorial should be vary helpful.
    Thnxhere is an Example :
    import java.util.concurrent.*;
    public class UtilConcurrentTest {
    public static void main(String[] args) throws InterruptedException {
    int numThreads = 4;
    int numTasks = 20;
    ExecutorService service = Executors.newFixedThreadPool(numThreads);
    // do some tasks:
    for (int i = 0; i < numTasks; i++) {
    service.execute(new Task(i));
    service.shutdown();
    log("called shutdown()");
    boolean isTerminated = service.awaitTermination(60, TimeUnit.SECONDS);
    log("service terminated: " + isTerminated);
    public static void log(String msg) {
    System.out.println(System.currentTimeMillis() + "\t" + msg);
    private static class Task implements Runnable {
    private final int id;
    public Task(int id) {
    this.id = id;
    public void run() {
    log("begin:\t" + this);
    try { Thread.sleep(1000); } catch (InterruptedException e) {}
    log("end\t" + this);
    public String toString() {
    return "Task " + id + " in thread " + Thread.currentThread().getName();
    }

  • Thread pool executor problem

    When using a thread pool executor (java.util.concurrent.ThreadPoolExecutor) to limit the number of threads executing at a time, the number of threads running still exceeds the limit number.
    This is the code:
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 20, TimeUnit.SECONDS, new LinkedBlockingQueue());
    The number of tasks in my program are 4, so i always have 4 threads running, although i limited it to 3.
    Can anyone help me with this problem? Or can u propose another solution to limit the number of running threads? By the way, i also tried using a newFixedThreadPool() and got the same problem.
    Thx.

    The number of tasks in my program are 4, so i always
    have 4 threads running, although i limited it to 3.How do you know that there are 4 threads running? If you're generating a JVM thread dump, you're going to see threads that are used internally by the JVM.
    Here's a simple program that creates a fixed-size threadpool and runs jobs. It limits the number of concurrent threads to 3. Compare it to what you're doing, I'm sure that you'll find something different. Also, verify that you're not creating threads somewhere else in your program; all of the ThreadPoolExecutor threads will have names of the form "pool-X-thread-Y"
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            for (int ii = 0 ; ii < 10 ; ii++) {
                pool.execute(new MyRunnable());
            pool.shutdown();
        private static class MyRunnable implements Runnable {
            public void run() {
                log("running");
                try {
                    Thread.sleep(1000L);
                catch (InterruptedException e) {
                    log("interrupted");
            private void log(String msg) {
                System.err.println(
                        msg + " on " + Thread.currentThread().getName()
                        + " at " + System.currentTimeMillis());
    }

  • Fixed Size Thread Pool which infinitely serve task submitted to it

    Hi,
    I want to create a fixed size thread pool say of size 100 and i will submit around 200 task to it.
    Now i want it to serve them infinitely i.e once all tasks are completed re-do them again and again.
    public void start(Vector<String> addresses)
          //Create a Runnable object of each address in "addresses"
           Vector<FindAgentRunnable> runnables = new Vector<FindAgentRunnable>(1,1);
            for (String address : addresses)
                runnables.addElement(new FindAgentRunnable(address));
           //Create a thread pool of size 100
            ExecutorService pool = Executors.newFixedThreadPool(100);
            //Here i added all the runnables to the thread pool
             for(FindAgentRunnable runnable : runnables)
                    pool.submit(runnable);
                pool.shutdown();
    }Now i wants that this thread pool execute the task infinitely i.e once all the tasks are done then restart all the tasks again.
    I have also tried to add then again and again but it throws a java.util.concurrent.RejectedExecutionException
    public void start(Vector<String> addresses)
          //Create a Runnable object of each address in "addresses"
           Vector<FindAgentRunnable> runnables = new Vector<FindAgentRunnable>(1,1);
            for (String address : addresses)
                runnables.addElement(new FindAgentRunnable(address));
           //Create a thread pool of size 100
            ExecutorService pool = Executors.newFixedThreadPool(100);
            for(;;)
                for(FindAgentRunnable runnable : runnables)
                    pool.submit(runnable);
                pool.shutdown();
                try
                    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
                catch (InterruptedException ex)
                    Logger.getLogger(AgentFinder.class.getName()).log(Level.SEVERE, null, ex);
    }Can anybody help me to solve this problem?
    Thnx in advance.

    Ravi_Gupta wrote:
    *@ kajbj*
    so what should i do?
    can you suggest me a solution?Consider this thread "closed". Continue to post in your other thread. I, and all others don't want to give answers that already have been given.

  • Thread Pool - EMS

    Hi,
    How can I increase the number of threads of an EMS (Enterprise Manager Source)?
    We define a JMS Queue and I only see there are only 5 consumers.. The processing of the messages from the queue are two slow..
    Thanks in advance,
    Julian

    The number of tasks in my program are 4, so i always
    have 4 threads running, although i limited it to 3.How do you know that there are 4 threads running? If you're generating a JVM thread dump, you're going to see threads that are used internally by the JVM.
    Here's a simple program that creates a fixed-size threadpool and runs jobs. It limits the number of concurrent threads to 3. Compare it to what you're doing, I'm sure that you'll find something different. Also, verify that you're not creating threads somewhere else in your program; all of the ThreadPoolExecutor threads will have names of the form "pool-X-thread-Y"
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            for (int ii = 0 ; ii < 10 ; ii++) {
                pool.execute(new MyRunnable());
            pool.shutdown();
        private static class MyRunnable implements Runnable {
            public void run() {
                log("running");
                try {
                    Thread.sleep(1000L);
                catch (InterruptedException e) {
                    log("interrupted");
            private void log(String msg) {
                System.err.println(
                        msg + " on " + Thread.currentThread().getName()
                        + " at " + System.currentTimeMillis());
    }

  • Thread Pool Is Not Terminating

    Hi All;
    I am trying to stop java program which are running continuously in a while loop and loop is looking for a stop file.
    When I am trying to stop java program through a Unix stop script, which will create a stop file .
    It is working fine with normal program where threading is not involved but multi threaded program(Via Thread pool) it is not working.
    Could you please refer below sample program which using Thread pool,
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 5, 10,
                             TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
                   threadPool.prestartAllCoreThreads();
                   File f=new File("/app/cbf/stop");
                   while(!f.isFile()){
                   new JavaTest().start(threadPool);
    Could any body please suggest me on this.
    Thanx & Regards

    Here is the complete code,
    import java.io.File;
    import java.io.IOException;
    import java.util.Properties;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    public class JavaTest {
         public void start(ThreadPoolExecutor threadPool) {
              threadPool.execute(new JavaThread());
         public void stop(ThreadPoolExecutor threadPool) {
              threadPool.shutdown();
              System.out.println("Stopping thread pool");
         * @param args
         public static void main(String[] args) throws IOException {
              // TODO Auto-generated method stub
              Properties p = new Properties();
              p.keys();
              try {
                   ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 5, 10,
                             TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
                   threadPool.prestartAllCoreThreads();
                   File f = new File("C:/stop");
                   while (!f.isFile()) {
                        new JavaTest().start(threadPool);
                   new JavaTest().stop(threadPool);
              } catch (Exception ex) {
                   ex.printStackTrace();
    }

  • Submit submit a large number of task to a thread pool (more than 10,000)

    i want to submit a large number of task to a thread pool (more than 10,000).
    Since a thread pool take runnable as input i have to create as many objects of Runnable as the number of task, but since the number of task is very large it causes the memory overflow and my application crashes.
    Can you suggest me some way to overcome this problem?

    Ravi_Gupta wrote:
    I have to serve them infinitely depending upon the choice of the user.
    Take a look at my code (code of MyCustomRunnable is already posted)
    public void start(Vector<String> addresses)
    searching = true;What is this for? Is it a kind of comment?
    >
    Vector<MyCustomRunnable> runnables = new Vector<MyCustomRunnable>(1,1);
    for (String address : addresses)
    try
    runnables.addElement(new MyCustomRunnable(address));
    catch (IOException ex)
    ex.printStackTrace();
    }Why does MyCustomRunnable throw an IOException? Why is using up resources when it hasn't started. Why build this vector at all?
    >
    //ThreadPoolExecutor pool = new ThreadPoolExecutor(100,100,50000L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue());
    ExecutorService pool = Executors.newFixedThreadPool(100);You have 100 CPUs wow! I can only assume your operations are blocking on a Socket connection most of the time.
    >
    boolean interrupted = false;
    Vector<Future<String>> futures = new Vector<Future<String>>(1,1);You don't save much by reusing your vector here.
    for(int i=1; !interrupted; i++)You are looping here until the thread is interrupted, why are you doing this? Are you trying to generate loading on a remote server?
    System.out.println("Cycle: " + i);
    for(MyCustomRunnable runnable : runnables)Change the name of you Runnable as it clearly does much more than that. Typically a Runnable is executed once and does not create resources in its constructor nor have a cleanup method.
    futures.addElement((Future<String>) pool.submit(runnable));Again, it unclear why you would use a vector rather than a list here.
    >
    for(Future<String> future : futures)
    try
    future.get();
    catch (InterruptedException ex)
    interrupted = true;If you want this to break the loop put the try/catch outside the loop.
    ex.printStackTrace();
    catch (ExecutionException ex)
    ex.printStackTrace();If you are generating a load test you may want to record this kind of failure. e.g. count them.
    futures.clear();
    try
    Thread.sleep(60000);Why do you sleep even if you have been interrupted? For better timing, you should sleep, before check if you futures have finished.
    catch(InterruptedException e)
    searching = false;again does nothing.
    System.out.println("Thread pool terminated..................");
    //return;remove this comment. its dangerous.
    break;why do you have two way of breaking the loop. why not interrupted = true here.
    searching = false;
    System.out.println("Shut downing pool");
    pool.shutdownNow();
    try
    for(MyCustomRunnable runnable : runnables)
    runnable.close(); //release resources associated with it.
    catch(IOException e)put the try/catch inside the loop. You may want to ignore the exception but if one fails, the rest of the resources won't get cleaned up.
    The above code serve the task infinitely untill it is terminated by user.
    i had created a large number of runnables and future objects and they remain in memory until
    user terminates the operation might be the cause of the memory overflow.It could be the size of the resources each runnable holds. Have you tried increasing your maximum memory? e.g. -Xmx512m

  • The problem of thread pool

    I want to make a thread pool to handle UDP package request
    so I set tow int variable :
    norsize;
    maxsize;
    the norsize is normal amount threads when Server boot they will be creat;
    the maxsize is when the quest is large and the norsize threads are not enough,The
    Thead pool can increase to the amount
    but how reduce the Thread pool amount when it reach the maxsize????

    That was funy (the Duke Dollars part) :)
    Ok. This time with some code.
    We have a class that manages work. This work is made up of Runnable objects and the threads that run it. Let's go with sample code instead of english, just remenber that I wrote this code directly to the post text area and didn't event compile it, although it should work.
    publi class WorkQueue {
        private LinkedList m_listRunnable;
        private int m_nMinThread;
        private int m_nMaxThread;
        private int m_nTimeOut;
        private int m_nNumThread;
        private int m_nNumThreadWaiting;
        public WorkQueue(int minThread, int maxThread, int timeOut) {
            m_listRunnable = new LinkedList();
            m_nMinThread = minThread;
            m_nMaxThread = maxThread;
            m_nTimeOut = timeOut;
            m_nNumThread = 0;
            m_nNumThreadWaiting = 0;
            init();
        private void init() {
            /* Start MinThread threads */
            for (i = 0; i < m_nMinThread; i++) {
                 new WorkSlaveThread();
                 m_nNumThread++;
        /* Inner class for the work thread */
        private class WorkSlaveThread extends Thread {
            public WorkSlaveThread() {
            public void run() {
                /* Work unless no work is returned, then it should stop */
                for (Runnable work = getNextWork(); work != null; work = getNextWork()) {
                    try {
                        work.run();
                    } catch (Throwable ex) {
                        /* Log the error */
                        ex.printStackTrace();
                threadStopping();
        private void threadStopping() {
            synchronized (this) {
                m_nNumThread--;
        private Runnable getNextWork() {
            Runnable work;
            long starttime = System.currentTimeMillis();
            long currenttime = starttime;
            long timeOut = m_nTimeOut * 1000; // Assume the time on in the constructor is in seconds
            synchronized (m_listRunnable) {
                /* Until there is work and the time out hasn't exceed */
                /* (time out ignored if the minimum umber of threads is reached) */
                while ((m_listRunnable.size() == 0) && ((timeOut > (currenttime - starttime)) || (m_nThreads == m_nMinThreads))) {
                    try {
                        m_nNumThreadWaiting++;
                        m_listRunnable.wait(m_nTimeOut * 1000);
                    } catch (Exception ex) {
                        /* Exception are launched if the VM is going down */
                        return null;
                    } finally {
                        m_nNumThreadWaiting--;
                    currenttime = System.currentTimeMillis();
                if (m_listRunnable.size () == 0) {
                    /* Stop threads procedure */
                    return null; // Null will stop the thread
                } else {
                    work = (Runnable)m_listRunnable.remove(0);
                    return work;
        public void addWork(Runnable work) {
            synchronized (m_listRunnable) {
                m_listRunnable.add(work);
                /* Start threads if necessary */
                if ((m_nNumThreadWaiting == 0) && (m_nNumThread < m_nMaxthread)) {
                    new WorkSlaveThread();
                    synchronized (this) {
                        m_nNumThread++;
                /* Signal a waiting thread */
                m_listRunnable.notify();
    }Well, this about does it! I didn't compile this, nor this is the code I use internally (internally I have shutdown procedures to ensure all work is down and other things), but it should do all the things a mention previously (I don't think I forgot any thing).
    Hope this helps,
    Nuno

  • A good design for a single thread pool manager using java.util.concurrent

    Hi,
    I am developing a client side project which in distinct subparts will execute some tasks in parallel.
    So, just to be logorroic, something like that:
    program\
                \--flow A\
                           \task A1
                           \task A2
                \--flow B\
                            \task B1
                            \task B2
                            \...I would like both flow A and flow B (and all their launched sub tasks) to be executed by the same thread pool, because I want to set a fixed amount of threads that my program can globally run.
    My idea would be something like:
    public class ThreadPoolManager {
        private static ExecutorService executor;
        private static final Object classLock = ThreadPoolManager.class;
         * Returns the single instance of the ExecutorService by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getExecutorService() {
            synchronized (classLock) {
                if (executor != null) {
                    return executor;
                } else {
                    // TODO: put the dimension of the FixedThreadPool in a property
                    executor = Executors.newFixedThreadPool(50);
                return executor;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
    }The tasks I have to execute will be of type Callable, since I expect some results, so you see an ExecutorService interface above.
    The flaws with this design is that I don't prevent the use (for example) of executor.shutdownNow(), which would cause problems.
    The alternative solution I have in mind would be something like having ThreadPoolManager to be a Singleton which implements ExecutorService, implementing all the methods with Delegation to an ExecutorService object created when the ThreadPoolManager object is instantiated for the first time and returned to client:
    public class ThreadPoolManager implements ExecutorService {
        private static ThreadPoolManager pool;
        private static final Object classLock = ThreadPoolManager.class;
        private ExecutorService executor;
         * Returns the single instance of the ThreadPoolManager by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getThreadPoolManager() {
            synchronized (classLock) {
                if (pool !=null) {
                    return pool;
                } else {
                    // create the real thread pool
                    // TODO: put the dimension of the FixedThreadPool in a property
                    // file
                    pool = new ThreadPoolManager();
                    pool.executor = Executors.newFixedThreadPool(50);
                    // executor = Executors.newCachedThreadPool();
                    return pool;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
        /* ======================================== */
        /* implement ExecutorService interface methods via delegation to executor
         * (forbidden method calls, like shutdownNow() , will be "ignored")
          // .....I hope to have expressed all the things, and hope to receive an answer that clarifies my doubts or gives me an hint for an alternative solution or an already made solution.
    ciao
    Alessio

    Two things. Firstly, it's better to use     private static final Object classLock = new Object();because that saves you worrying about whether any other code synchronises on it. Secondly, if you do decide to go for the delegation route then java.lang.reflect.Proxy may be a good way forward.

Maybe you are looking for

  • What is the export format for Iphone and Android (Premiere Pro CS6)?

    For Iphone, Ipad and Android, what is the export format (Premiere Pro CS6) for watching videos ?

  • Turning iPod to backup hard drive (sorry if this is in the wrong place.)

    Hello, I was wondering how I would be able to change my old iPod into just an external hard drive so I may use it for Time Machine

  • Reg FCC

    Hi Guys, can you pls tell me the content conversion for the belo w. parent.f1,f2,f3, parent.child.f4,f5,f6, parent.f7 to explain in brief the parent is the base node and has 3 fields after that has a child segment which has 3 fields and one field in

  • License requirements to host for a customer

    I would like to build and host a dashboard for a customer of mine.  I would like to let the customer update using an xml file and display the dashboard on my web site for the customer to access whenever they like.  It will likely expand to a few diff

  • Add columns to CO02-Operations Overview

    Hi Gurus I'm trying to add couple of columns to the Operations Overview display layout in CO02 Transaction. Can someone please let me know how this is done? Thanks in advance Deepak