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?

Similar Messages

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

  • How to correctly use a fixed size thread pool?

    I am quite new to using concurrency in Java, so please forgive if this is a trivial question.
    I would like to make use of something like pool=Executors.newFixedThreadPool(n) to automatically use a fixed number of threads to process pieces of work. I understand that I can asynchronously run some Runnable by one of the threads in the threadpool using pool.execute(someRunnable).
    My problem is this: I have some fixed amount of N datastructures myDS (which are not reentrant or sharable) that get initialized at program start and which are needed by the runnables to do the work. So, what I really would like to do is that I not only reuse N threads but also N of these datastructures to do the work.
    So, lets say I want to have 10 threads, then I would want to create 10 myDS objects once and for all. Each time some work comes in, I want that work to get processed by the next free thread, using the next free datastructure. What I was wondering is if there is something in the library that lets me do the resusing of threads AND datastructures as simply as just reusing a pool of threads. Ideally, each thread would get associated with one datastructure somehow.
    Currently I use an approach where I create 10 Runnable worker objects, each with its own copy of myDS. Those worker objects get stored in an ArrayBlockingQueue of size 10. Each time some work comes in, I get the next Runner from the queue, pass it the piece of work and submit it to the thread pool.
    The tricky part is how to get the worker object back into the Queue: currently I essentially do queue.put(this) at the very end of each Runnable's run method but I am not sure if that is safe or how to do it safely.
    What are the standard patterns and library classes to use for solving this problem correctly?

    Thank you for that feedback!
    There is one issue that worries me though and I obviously do not understand it enough: as I said I hand back the Runnable to the blocking queue at the end of the Runnable.run method using queue.put(this). This is done via a static method from the main class that creates the threads and runnable objects in a main method. Originally I tried to make that method for putting back the Runnable objects serialized but that inevitably always led to a deadlock or hang condition: the method for putting back the runnable was never actually run. So I ended up doing this without serializing the put action in any way and so far it seems to work ... but is this safe?
    To reiterate: I have a static class that creates a thread pool object and a ArrayBlockingQueue queue object of runnable objects. In a loop I use queue.take() to get the next free runnable object, and pass this runnable to pool.execute. Inside the runnable, in method run, i use staticclass.putBack(this) which in turn does queue.put(therunnableigot). Can I trust that this queue.put operation, which can happen from several threads at the same time works without problem without serializing it explicitly? And why would making the staticclass.putBack method serialized cause a hang? I also tried to serialize using the queue object itself instead of the static class, by doing serialize(queue) { queue.put(therunnable) } but that also caused a hang. I have to admit that I do not understand at all why that hang occurred and if I need the serialization here or not.

  • ITunes taking more space then it should!

    Hey Apple Discussions,
    I have come to you guys for a solution for the same problem for the second time...(http://discussions.apple.com/thread.jspa?threadID=1351866&tstart=0)
    the first time i thought it would really work(look in the other thread about the script) but then i noticed something.
    itunes isnt just music...it stores all the movies. so that resolved about 15GBs of my problem...but now i have new amount of problem
    iTunes shows that I have 19.69GB of music(that shows at the bottom of the application) and 9.98Gb of movies, which totals to 29.67GB. But when i right click on the itunes folder to "get info" it shows i have 35.39GB
    can anyone help me out on this problem? i have a wierd thing about freeing space on my computer

    Try this -> List Music Folder Files Not Added v2.0
    "This script recursively searches user-selected folders for files not added to iTunes and creates a text file listing their file"

  • ScheduledThreadPoolExecutor core thread pool / keepalive/timing out threads

    Hi,
    I am using a ScheduledThreadPoolExecutor - java1.6 on Windows(currently).
    I would like to minimise the number of threads in the pool running at any one time to around the number of threads required to run the number of tasks that are concurrently executing.
    However, I don't seem to be able to get the thread pool to minimise the number of threads below the max threads in the constructor.
    I want to do this mainly because I have a large delay queue and the performance of the pool seems to be better when the number of threads in the pool is minimised to roughly the number of threads required to service the concurrently executing tasks.
    Any ideas?
    Thanks,
    Alex
                    ThreadFactory tf = new MyThreadFactory();
              ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(50,tf);
              scheduler.setCorePoolSize(10);
              //scheduler.setMaximumPoolSize(50);
              scheduler.setKeepAliveTime(1, TimeUnit.NANOSECONDS);
              scheduler.allowCoreThreadTimeOut(true);
              scheduler.schedule(aTask, 10, TimeUnit.SECONDS);
    ...

    because of how a scheduledthreadpoolexecutor works, it doesn't really make sense to have a variable number of threads. since threads are only added when tasks are added to the pool (aka, when submit is called), once the core threads timed out they would never get replaced (e.g. you would eventually get down to 1 thread and never get anymore added). one way to achieve what you want would be to have a single threaded ScheduledThreadPoolExecutor, where the scheduled jobs do the real work in a separate, variable size thread pool (e.g. the scheduled tasks do not do anything but submit a task to the real work thread pool). this solution would work fine for "schedule at fixed rate" but not for "schedule with fixed delay". you would actually have to simulate the latter by scheduling a one-off task which resubmits itself to the scheduler each time it completes.

  • 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

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

  • Using threads in a process of two or more tasks concurrently?

    Dear,
    I need to develop through a Java application in a process that allows the same process using Threads on two or more tasks can be executed concurrently. The goal is to optimize the runtime of a program.
    Then, through a program, display the behavior of a producer and two consumers at runtime!
    Below is the code and problem description.
    Could anyone help me on this issue?
    Sincerely,
    Sérgio Pitta
    The producer-consumer problem
    Known as the problem of limited buffer. The two processes share a common buffer of fixed size. One, the producer puts information into the buffer and the other the consumer to pull off.
    The problem arises when the producer wants to put a new item in the buffer, but it is already full. The solution is to put the producer to sleep and wake it up only when the consumer to remove one or more items. Likewise, if the consumer wants to remove an item from the buffer and realize that it is empty, he will sleep until the producer put something in the buffer and awake.
    To keep track of the number of items in the buffer, we need a variable, "count". If the maximum number of items that may contain the buffer is N, the producer code first checks whether the value of the variable "count" is N. If the producer sleep, otherwise, the producer adds an item and increment the variable "count".
    The consumer code is similar: first checks if the value of the variable "count" is 0. If so, go to sleep if not zero, removes an item and decreases the counter by one. Each case also tests whether the other should be agreed and, if so, awakens. The code for both producer and consumer, is shown in the code below:
    #define N 100                     / * number of posts in the buffer * /
    int count = 0,                     / * number of items in buffer * /
    void producer(void)
    int item;
    while (TRUE) {                    / * number of items in buffer * /
    produce_item item = ()           / * generates the next item * /
    if (count == N) sleep ()           / * if the buffer is full, go to sleep * /
    insert_item (item)                / * put an item in the buffer * /
    count = count + 1                / * increment the count of items in buffer * /
    if (count == 1) wakeup (consumer);      / * buffer empty? * /
    void consumer(void)
    int item;
    while (TRUE) {                    / * repeat forever * /
    if (count == 0) sleep ()           / * if the buffer is full, go to sleep * /
    remove_item item = ()           / * generates the next item * /
    count = count - 1                / * decrement a counter of items in buffer * /
    if (count == N - 1) wakeup (producer)      / * buffer empty? * /
    consume_item (item)      / * print the item * /
    To express system calls such as sleep and wakeup in C, they are shown how to call library routines. They are not part of standard C library, but presumably would be available on any system that actually have those system calls. Procedures "insert_item and remove_item" which are not shown, they register themselves on the insertion and removal of the item buffer.
    Now back to the race condition. It can occur because the variable "count" unfettered access. Could the following scenario occurs: the buffer is empty and the consumer just read the variable "count" to check if its value is 0. In that instant, the scheduler decides to stop running temporarily and the consumer starting to run the producer. The producer inserts an item in the buffer, increment the variable "count" and realizes that its value is now 1. Inferring the value of "count" was 0 and that the consumer should go to bed, the producer calls "wakeup" to wake up the consumer.
    Unfortunately, the consumer is not logically asleep, so the signal is lost to agree. The next time the consumer to run, test the value of "count" previously read by him, shall verify that the value is 0, and sleep. Sooner or later the producer fills the whole buffer and also sleep. Both sleep forever.
    The essence of the problem is that you lose sending a signal to wake up a process that (still) not sleeping. If he were not lost, everything would work. A quick solution is to modify the rules, adding context to a "bit of waiting for the signal to wake up (wakeup waiting bit)." When a signal is sent to wake up a process that is still awake, this bit is turned on. Then, when the process trying to sleep, if the bit waiting for the signal to wake up is on, it will shut down, but the process will remain awake. The bit waiting for the signal to wake up is actually a piggy bank that holds signs of waking.
    Even the bit waiting for the signal to wake the nation have saved in this simple example, it is easy to think of cases with three or more cases in which a bit of waiting for the signal to wake up is insufficient. We could do another improvisation and add a second bit of waiting for the signal to wake up or maybe eight or 32 of them, but in principle, the problem still exists.

    user12284350 wrote:
    Hi!
    Thanks for the feedback!
    I need a program to provide through an interface with the user behavior of a producer and two consumers at runtime, using Threads!So hire somebody to write one.
    Or, if what you really mean is that you need to write such a program, as part of your course work, then write one.
    You can't just dump your requirements here and expect someone to do your work for you though. If this is your assignment, then you need to do it. If you get stuck, ask a specific question about the part that's giving you trouble. "How do I write a producer/consumer program?" is not a valid question.

  • 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

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Waiting all threads in a fixed thread pool

    Hello, may I know how can I wait for all the threads in a fixed thread pool to be completed, without calling shutdownNow?
    Executor pool = Executors.newFixedThreadPool(nThreads);
    for(int i = 0; i < 10000;  i++)
        pool.execute(new StockHistoryRunnable(code));
    // blah blah blah
    // I would like to wait for all the 10000 task to be completed. There is a method named
    // awaitTermination. However, in order to use the method, I have to first call shutdownNow.
    // I do not want to do so, because I need to re-use the pool later.
    //

    You could retrieve all the "Future" instances returned by calling "submit" on your Executor and then have a Thread sequentially wait for the completion of all these individual tasks by using "get". Of course, this will require some synchronization if it is possible that new tasks get queued while you are already waiting for the original ones to be completed. But this way you can easily find out when all tasks have completed.

  • 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);
        }

  • Setting Thread pool size

              Hi,
              I want to know if I set a system property "-Dweblogic.ThreadPoolSize", how will the
              WLS get to know that the pool size has been changed, at run time?
              E.g. I pass -Dweblogic.ThreadPoolSize=30 from the command-line. Then if I change
              the pool size to 40 at runtime, is there any event that I can fire for the change
              in property through APIs?
              Thnx in advance.
              Best Regards
              Ali
              

    Disregarding what it is for, in my experience, tuning this setting rarely has much effect. For 6.1, the main thread pool related tunables to look at are the EJB thread pools and EJB max-beans... settings, the "default" thread pool, and the internal thread-pool for stand-alone clients -- all of which are mentioned in the performance guide.

  • Will more number of waiting threads in thread pool degrade performance?

    Hi,
    I use thread pool and set the maximum number of threads to execute. My problem is, the thread pool initiates the number of threads and these threads wait until they get a work. Will this degrade the performance (The threads do I/O operations) ??

    Threads waiting for work will not degrade performance. If your work involves those threads waiting for I/O then that in itself will not degrade performance either (as long as they block and don't poll of course).
    All live threads consume resources however so if you are short on threads or memory then don't create too many of them.
    Pre-starting a large number of threads in a pool can cause a startup delay of course. Generally you should let the pool create threads as needed until it gets to the core pool size.

Maybe you are looking for