Shermans's Notes
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

January 21st, 2020

Java Executor pools

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private static final int NUM_THREADS = 4;private final Logger log = Logger.getLogger(getClass());
	 

private LinkedBlockingQueue< Runnable> taskQueue = new LinkedBlockingQueue< Runnable>();private List< Runnable> running = Collections.synchronizedList(new ArrayList());

public void doSomeStuffConcurrently() {
    Executor executor = 
        new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS,
            0L, TimeUnit.MILLISECONDS,
            taskQueue,
          	Executors.defaultThreadFactory()) 
    {

        @Override
        protected < T> RunnableFuture< T> newTaskFor(final Runnable runnable, T value) {
            return new FutureTask< T>(runnable, value) {
                @Override
                public String toString() {
                    return runnable.toString();
                }
            };
        }

        @Override
        protected void beforeExecute(Thread t, Runnable r) {
            super.beforeExecute(t, r);
            running.add(r);
        }

        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            running.remove(r);
            log.info("RUNNING: " + running);
        }
    };

    executor.execute(new Runnable() {

        @Override
        public void run() {
            // so some stuff
        }

        @Override
        public String toString() {
            return "describe the task here!";
        }                        
    });}
  • Only real way to know what is going on is to have a custom interface that allow naming of tasks. Source
  • Doing a controlled shutdown can look like this
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
		int retries = 5;
		_implementation.shutdown();

		try
		{
			while (!_implementation.awaitTermination(1000, TimeUnit.MILLISECONDS))
			{
				int activeCount = _implementation.getQueue().size();
				if (--retries > 0)
				{
						log.warn("Waiting for {} queued tasks", activeCount);
				}
				else
				{
					log.warn("Aborting {} queued tasks", activeCount);
					break;
				}	
			}
			log.warn("Finished");
		}
		catch (InterruptedException e)
		{
			log.error("Interrupted while awaiting termination");
		}