Posts Tagged ‘ ExecutorService

Executors.newFixedThreadPool(n) – Suspended Threads

Only Exception is Real

Image by valentin.d via Flickr

Yesterday while I am trying to organize threads in Java I noticed something strange !!

Simply the default ExecutorService  could not manage to recover suspended threads.

After a small investigation, it looks like if any of the running thread throws any RuntimeException, ExecutorService may not recover and could not start any waiting runnable.

You can check the java code below.

SmartFix: Don’t throw any exception :P

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorsTest {

	private static ExecutorService executorService;

	public static void main(String[] args) {
	    executorService = Executors.newFixedThreadPool(10);
	    for (int i = 0; i < 10000; i++) {
	        executorService.execute(new MyRunnable());
        }
    }

	public static class MyRunnable implements Runnable{

		@Override
        public void run() {
			while(true){
				long t=(long) (Math.random()*1000*10);
				try {
	                Thread.sleep(t);
                } catch (InterruptedException e) {}
                if(t<3000){
                	System.out.println(Thread.activeCount());
                	// COMMENT AND UNCOMMENT THE LINE BELOW TO SEE THE DIFFERENCE
                	throw new RuntimeException("s");

                }
			}
        }
	}
}
Enhanced by Zemanta