Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Fixed size thread pool excepting more tasks then it should

852668Apr 4 2011 — edited Apr 12 2011
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);
}

}
This post has been answered by Kayaman on Apr 4 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 10 2011
Added on Apr 4 2011
5 comments
852 views