Thread pool rejecting threads when I don't think it should, ideas?

Hi,
I have a server application in which I only want a specific number of simultaneous requests. If the server gets more then this number it is suppose to close the connection (sends an HTTP 503 error to the client). To do this I used a fix thread pool. When I start the server and submit the max number of requests I get the expected behavior. However if I resubmit the request (within a small period of time, e.g. 1-15 seconds after the first one) I get very odd behavior in that some of the requests are rejected. For example if I set the max to 100 the first set of requests will work fine (100 requests, 100 responses). I then submit again and a small number will be rejected (I've seen it range from 1 to 15 rejected)....
I made a small app which kind of duplicates this behavior (see below). Basically when I see is that the first time submitting requests works fine but the second time I get a rejected one. As best as I can tell none should be rejected....
Here is the code, I welcome your thoughts or if you see something I am doing wrong here...
<pre>
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolTest {
     static AtomicInteger count = new AtomicInteger();
     public static class threaded implements Runnable {
          @Override
          public void run() {
               System.out.println("In thread: " + Thread.currentThread().getId());
               try {
                    Thread.sleep(500);
               } catch (InterruptedException e) {
                    System.out.println("Thread: " + Thread.currentThread().getId()
                              + " interuptted");
               System.out.println("Exiting run: " + Thread.currentThread().getId());
     private static int maxThreads = 3;
     private ThreadPoolExecutor pool;
     public ThreadPoolTest() {
          super();
          pool = new java.util.concurrent.ThreadPoolExecutor(
                    1, maxThreads - 1, 60L, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(1));
     public static void main(String[] args) throws InterruptedException {
          ThreadPoolTest object = new ThreadPoolTest();
          object.doThreads();
          Thread.sleep(3000);
          object.doThreads();
          object.pool.shutdown();
          try {
               object.pool.awaitTermination(60, TimeUnit.SECONDS);
          } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
     private void doThreads() {
          int submitted = 0, rejected = 0;
          int counter = count.getAndIncrement();
          for (int x = 0; x < maxThreads ; x++) {
               try {
                    System.out.println("Run #: " + counter + " submitting " + x);
                    pool.execute(new threaded());
                    submitted++;
               catch (RejectedExecutionException re) {
                    System.err.println("\tRun #: " + counter + ", submission " + x
                              + " was rejected");
                    System.err.println("\tQueue active: " + pool.getActiveCount());
                    System.err.println("\tQueue size: " + pool.getPoolSize());
                    rejected++;
          System.out.println("\n\n\tRun #: " + counter);
          System.out.println("\tSubmitted: " + (submitted + rejected));
          System.out.println("\tAccepted: " + submitted);
          System.out.println("\tRejected: " + rejected + "\n\n");
</pre>

First thank you for taking the time to reply, I do appreciate it.
jtahlborn - The code provided here is a contrived example trying to emulate the bigger app as best as I could. The actual program doesn't have any sleeps, the sleep in the secondary thread is to simulate the program doing some work & replying to a request. The sleep in the primary thread is to simulate a small delay between 'requests' to the pool. I can make this 1 second and up to (at least) 5 seconds with the same results. Additionally I can take out the sleep in the secondary thread and still see the a rejection.
EJP - Yes I am aware of the TCP/IP queue, however; I don't see that as relevant to my question. The idea is not to prevent the connection but to respond to the client saying we can't process the request (send an "HTTP 503" error). So basically if we have, say, 100 threads running then the 101st, connection will get a 503 error and the connection will be closed.
Also my test platform - Windows 7 64bit running Java 1.6.0_24-b07 (32bit) on an Intel core i7.
It occurred to me that I did not show the output of the test program. As the output shows below, the first set of requests are all processed properly. The second set of requests is not. The pool should have 2 threads and 1 slot in the queue, so by the time the second "request" is made at least 2 of the requests from the first call should be done processing, so I could possibly understand run 1, submit #2 failing but not submit 1.
<pre>
Run #: 0 submitting 0
Run #: 0 submitting 1
Run #: 0 submitting 2
In thread: 8
In thread: 9
Exiting run: 8
Exiting run: 9
     Run #: 0
     Submitted: 3
     Accepted: 3
     Rejected: 0
In thread: 8
Exiting run: 8
Run #: 1 submitting 0
In thread: 9
Run #: 1 submitting 1
     Run #: 1, submission 1 was rejected
     Queue active: 1
     Queue size: 2
Run #: 1 submitting 2
     Run #: 1
     Submitted: 3
     Accepted: 2
     Rejected: 1
In thread: 8
Exiting run: 9
Exiting run: 8
</pre>

Similar Messages

  • TS4424 I still can't get my mail to work.I have reinstalled Security update and combo 3 times. About ready to call Apple but mI don't think I should pay for it!!!!

    I can't my Apple mail to work.  It started when I did an up date.  When I went to use mail  (the little stamp at bottom)  it said, "you can't use this version of mail with this version of OS X.  I looked on support and was told to solve the problem  by downloading combo package and security update. Did it 3 times.  I did everything.  Still doesn't work.  I even took everything mail out of applications and the library and did those two updates and still can't get it.  Could I reinstall OS X Snow Leopard and would that affect any of my documents like i photo or i tunes?  I don't want to loose anything!  I have spent way too long on this problem.  I feel like I own  PC with windows again.  Please help!!!!!!    Frustated

    No need to reinstall Snow. Try trashing all the Mail.apps you have. (But don't empty the trash yet!) Do a search for those. Reinstall Mail from the DVD in Optional Installs. This will put Mail 4.2 in Applications, then run the Combo Update, which will update Mail to 4.5, and then the Security Update again, in that order.

  • My laptop continues to close down Safari unexpectedly. It is relatively new {MacBook Air purchased June 2014} and I don't think this should be happening. Is there something wrong? How do I fix this?

    How can this be fixed if it can be fixed? No bugs or viruses are on the computer as far as I know. All other applications work perfectly on the laptop, so it is strange that the Safari continues to closedown. I can use Safari and it does work for the majority of time, but there are times when the Safari closes out.

    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad and start typing the name.
    Step 1
    For this step, the title of the Console window should be All Messages. If it isn't, select
              SYSTEM LOG QUERIES ▹ All Messages
    from the log list on the left. If you don't see that list, select
              View ▹ Show Log List
    from the menu bar at the top of the screen.
    In the top right corner of the Console window, there's a search box labeled Filter. Initially the words "String Matching" are shown in that box. Enter the name of the crashed application or process. For example, if Safari crashed, you would enter "Safari" (without the quotes.)
    Each message in the log begins with the date and time when it was entered. Select the messages from the time of the last crash, if any. Copy them to the Clipboard by pressing the key combination command-C. Paste into a reply to this message by pressing command-V.
    ☞ The log contains a vast amount of information, almost all of which is irrelevant to solving any particular problem. When posting a log extract, be selective. A few dozen lines are almost always more than enough.
    Please don't indiscriminately dump thousands of lines from the log into this discussion.
    Please don't post screenshots of log messages—post the text.
    ☞ Some private information, such as your name, may appear in the log. Anonymize before posting.
    Step 2
    In the Console window, select
              DIAGNOSTIC AND USAGE INFORMATION ▹ User Diagnostic Reports
    (not Diagnostic and Usage Messages) from the log list on the left. There is a disclosure triangle to the left of the list item. If the triangle is pointing to the right, click it so that it points down. You'll see a list of crash reports. The name of each report starts with the name of the process, and ends with ".crash". Select the most recent report related to the process in question. The contents of the report will appear on the right. Use copy and paste to post the entire contents—the text, not a screenshot.
    I know the report is long, maybe several hundred lines. Please post all of it anyway.
    If you don't see any reports listed, but you know there was a crash, you may have chosen Diagnostic and Usage Messages from the log list. Choose DIAGNOSTIC AND USAGE INFORMATION instead.
    In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.)
    Please don’t post other kinds of diagnostic report—they're very long and rarely helpful.

  • Since I downloaded the upgraded software, my charger that came with my phone says "this cable or accessory is not certified and may not work reliably with this iphone"  It worked before but now it doesn't...I don't think I should have to buy a new one...

    since I upgraded to the new operating system my charger no longer works...
    It says"this cable or accessory is not certified and may not work reliably with this iPhone"

    Try checking your cable socket/lightning cable for dirt, grime, pocket lint, etc. I could not find the solution to this issue myself and after much searching I found someone stating that cleaning this out helped them immensely.
    After taking a wooden toothpick (making sure the phone was OFF first) and gently clearing out the edges and inside of the lightning socket this went away.) It is worth noting that I had a significant amount of dust or lint buildup along the edge rails which I think was causing the iphone to believe it was plugged into something when it was not.
    Try it and see, ensure you are very careful and do not use any conductive tools to clean the area in question. Compressed air also does wonders here.

  • Thread pool small example needed

    Hi friends,
    Can you please give a small example program for thread pool to understand?

    >
    Can you please give a small example program for thread pool to understand?>I don't know (whether you would understand an example - simple or otherwise).
    But why don't you help dispel the impression that you are just another lazy student, by making a start on some code, then asking a specific question, when you get stuck?

  • 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.

  • Coherence thread pools

    Hi, i'm trying to understand how coherence uses various threads/thread-pools; in particular when interacting with a data store (which threads read, which threads write). In a stack trace dump, i see the following:
    WriteBehindThread:CacheStoreWrapper($Proxy12): 30 of these threads.
    DistributedWriteThroughWorker: 16 of these
    DistributedCacheWorker: 16 of these
    DistributedWriteBehindWorker: 16 of these
    DistributedNonPersistentWorker: 16 of these
    I'm guessing writes happen on the DistributedWriteThroughWorker and DistributedWriteBehindWorker threads, but what about reads? And what are the other thread pools for?
    Thanks.

    Hi,
    WriteBehindThread:CacheStoreWrapper($Proxy12):
    These are the write behind threads for your write behind caches - in this case caches mapped to the DistributedWriteBehind service. There are 30 of them as there is one per cache. These will fire up periodically (depending on the write-delay) and write any pending inserts/updates to the DB. Deletes are done on the worker thread or service thread if you have no worker threads (i.e. a thread count of zero).
    DistributedWriteThroughWorker:
    These are the worker threads for the DistributedWriteThrough service. They process most of the operations that are requested on caches mapped to the DistributedWriteThrough service. There are 16 as you have probably set the thread-count in the cache configuration file to 16.
    DistributedCacheWorker:
    These are the worker threads for the DistributedCache service. They process most of the operations that are requested on caches mapped to the DistributedCache service. There are 16 as you have probably set the thread-count in the cache configuration file to 16.
    DistributedWriteBehindWorker:
    These are the worker threads for the DistributedWriteBehind service. They process most of the operations that are requested on caches mapped to the DistributedWriteBehind service. There are 16 as you have probably set the thread-count in the cache configuration file to 16.
    DistributedNonPersistentWorker:
    These are the worker threads for the DistributedNonPersistent service. They process most of the operations that are requested on caches mapped to the DistributedNonPersistent service. There are 16 as you have probably set the thread-count in the cache configuration file to 16.
    You will also see you have these threads
    DistributedCache:DistributedWriteThrough
    DistributedCache:DistributedCache
    DistributedCache:DistributedWriteBehind
    DistributedCache:DistributedNonPersistent
    These are the service threads for the respective services - there is only ever one of these per service. These allocate tasks to the worker threads and are also responsible for processing certain tasks themselves. If you set a thread count of zero for a service then all you will have no worker threads and requests will be processed by the service thread.
    If you manage to ever deadlock your cluster it is usually because you have deadlocked a service thread or worker threads so if the cluster is grinding to a halt this is typically where I would look first in a thread dump.
    JK

  • 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 callbacks across thread pools

    Correct me if I'm wrong, but apparently calls such as PostDeferredCallToThread() don't work between thread pools. If I create a thread pool in a main program (operating in the default thread pool) and make threads, I can't make calls to callbacks in the new thread pool. Thread-safe queues and variables, on the other hand, still seem to work.

    See the example in my answer to your other thread.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • 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

  • 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

  • Cold Fusion in a generic thread pool and enabling JAVA don't mix

    I've got Cold Fusion MX installed on a server running Sun One 6.1. I ran into a problem trying to enable JAVA (for servlet support) which I had previous disabled because I didn't use it.
    Well, when I went to enable JAVA on the server last week, the service wouldn't restart and the error logs gave me no indication of the problem.
    Through a tedious trial-and-error process I've found that having Cold Fusion running under a generic thread pool while trying to have JAVA (the j2ee plugin) running under Sun One simply doesn't work (for whatever reason).
    Once I killed the pool, everything runs fine.
    Does anyone happen to know why this is? I keep CFMX under its own thread pool because there are certain elements to CFMX that aren't wholly stable and can result in CFMX crashing. If it crashes, the process keeps accepting requests, but never processes them. I'd like to keep the native thread pool free to keep accepting non-CFMX requests even when CFMX crashes.
    Thus the separate thread pool for CFMX.
    But now I can't run CFMX in a separate thread pool with JAVA enabled.
    Anyone have any insights into why this is?
    Thanks

    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.

  • 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?

  • Combining the fixed and cached thread pools

    Is there a way to 'combine' the behavior of cached and fixed thread pools ? I have a requirement where
    - at startup, I need to execute a fixed number of short-lived tasks at the background
    - after startup, on demand, I need to run one short-lived task at a time
    If I use a fixed thread pool for my startup processing, it creates the fixed number of threads to process the tasks. But subsequently, those many threads are not required since my task submission is going to be one at a time. The remaining (n-1) threads therefore are really sitting idle & useless.
    If I use a cached thread pool, then I cannot constrain the number of threads to run at startup (since it creates one for each task). Though it ends up taking those threads out after they are idle for a fixed period. But I'm worried that it might create many threads and possibly slowing down the startup ?
    Is there a way to create a pool with a fixed number of threads but 'remove' a set of threads when they are idle ?
    TIA

    v_bala wrote:
    Thanks. The SynchronousQueue worked as expected. But I tried a LinkedBlockingQueue with size 1 hoping that would cause the second task submission to cause a new thread creation. It didn't. Instead it queues up the request (maybe the doc in ThreadPoolExecutor says that when it mentions "If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread"). I suppose if I were to try another it would create another thread ? (I was testing with only two tasks - the first one ended up creating a thread for the task and the next got queued since the queue capacity is 1)yes, the TPE will not start adding threads until the queue starts rejecting them. kind of odd in my opinion, but that's how it works.
    Btw, that was an interesting idea to add a task that scale the core pool number down ! Currently it comes back down to just the one thread (my core pool size is one) after the idle timeout but your idea may give me a slightly better response since it will scale down the core pool size quicker....I suppose if there was a task submission before that idle time there maybe a performance hit (but I don't anticipate that in my case )?actually, that won't scale things down any faster. changing the core pool size will not ditch the other threads immediately, they will still stick around until they idle timeout. changing the core pool size allows you to not worry about the queue implementation (the first solution). you can set the initial core pool size to your "max" size on startup, then drop it down for the normal processing, all the while using a linkedblockingqueue of unlimited size.

  • 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

  • PO approval workflow customization

    we want to send email notification to supplier upon approval of PO approval. Is there any default functionality available or we have to customize a PO approval workflow.

  • No Scaling Options for my Dell WQHD Display

    Why this online community actually for? this is run by apple??? Most of the questions not answered. My problem. My Dell WQHD monitor connected using MDP to DP cable and works fine  but Two problems. 1) I cannot scale things up just like my macbook pr

  • Polling in CVI

    I am trying to understand how to poll in LabWindows? My application does not require user interface, it will be separate application. If the application had user interface I was creating a new thread and use timer control. Timer control callback woul

  • OS X will not install on recently zero'd out HD...HELP!

    I recently did a 7-pass erase to my HD as I plan on selling my computer. After the erase was done I shut down my comp and rebooted from the Leopard install disk. About 60-70% of the way through the install fails with errors about 'HewlettPackardPrint

  • PO Release strategy, error: class POCLASS class type 032

    All SAP Gurus, We are configuring new PO release strategy. When we go to Release strategy - classification (Release procedure for PO - Define release procedure for PO - Release Strategies - classification) It gives following error: Error in classific