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
Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Wists
  • LinkedIn
  • Slashdot
  • Google Bookmarks
  • Reddit
  • StumbleUpon
  • email
  • Twitter
  • FriendFeed

Related posts:

  1. light-weight distributed messaging via JGroups
  2. JGroups Basics
  3. DistributableEventPublisher for Spring via JGroups
  4. Spring is totally losing its invisibility
  5. How to get Generic Metadata from a Class at Runtime

    • trung
    • July 20th, 2010

    Hello

    Use submit instead of execute or try/catch execute method. Because with execute, your runnable can be invoked in calling thread.

    Cheers

    • Hi trung,
      Thanks for the tip, it has fixed my problem.

      Cheers,

  1. No trackbacks yet.