Java Thread Pool – ExecutorService

Java Thread Pool is a performance solution for scaling system, so JavaSampleApproach will guide you how to work with Java Thread Pool by ExecutorService and Executors.

I. Concepts
1. ExecutorService & Executors

java.util.concurrent.ExecutorService provides methods to manage termination and methods to produce a Future for tracking progress of tasks.

java.util.concurrent.Executors class provides factory methods for the executor services.

2. Methods

public static ExecutorService newFixedThreadPool(int nThreads): creates a thread pool for reusing a fixed number of threads . At any point if having any tasked are submitted when all threads are active, they will wait until a thread is available.

public static ExecutorService newSingleThreadExecutor(): creates an Executor that uses a single worker thread. Tasks are guaranteed to execute sequentially, and no more than one task will be active at a specific time.

Note:
– Difference between newFixedThreadPool(1) & newSingleThreadExecutor(): Executor of newSingleThreadExecutor() factory method guaranteed not to be reconfigurable at runtime.

– If a thread terminates(both: newFixedThreadPool() & newSingleThreadExecutor()) due to a failure during execution prior to shutdown, a new one will created for executing subsequent tasks.

void java.util.concurrent.Executor.execute(Runnable command): executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

void java.util.concurrent.ExecutorService.shutdown(): setup a shutdown right after all submitted tasks are executed, and not accepted any new task.

boolean java.util.concurrent.ExecutorService.isTerminated(): returns true if all tasks have completed after shut down.
Note: isTerminated is always false unless either shutdown or shutdownNow was called first.

II. Practice
1. Create WorkerThread
package com.javasampleapproach.javathreadpool;

public class Worker  implements Runnable{
	
	private String message;
	
	public Worker(String message){
		this.message = message;
	}
	
	

	@Override
	public void run() {
		doJob();
	}

	private void doJob(){
		try{
			long id = Thread.currentThread().getId();
			System.out.println("Thread with " + id + " START PROCESS. Message = " + message);
			Thread.sleep(2000);		
			System.out.println("Thread with " + id + " END");
			System.out.println();
		}catch(Exception e){
		}
	}

	public String getMessage() {
		return message;
	}

}
2. Sample with newFixedThreadPool

Sourcecode:

package com.javasampleapproach.javathreadpool;

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

public class ThreadpoolExecutorServiceSample {
	public static void main(String[] args) {
		
		// create ExecutorService
		ExecutorService executor = Executors.newFixedThreadPool(3);
		
		for (int i = 0; i < 10; i++) {
			Runnable worker = new Worker(Integer.toString(i));
			executor.execute(worker);
		}
		
		executor.shutdown();
		while (!executor.isTerminated()) {
		}

		System.out.println("Finished all threads");
	}
}

Outuput:

Thread with 11 START PROCESS. Message = 1
Thread with 12 START PROCESS. Message = 2
Thread with 10 START PROCESS. Message = 0
Thread with 11 END

Thread with 10 END

Thread with 12 END

Thread with 10 START PROCESS. Message = 4
Thread with 11 START PROCESS. Message = 3
Thread with 12 START PROCESS. Message = 5
Thread with 10 END

Thread with 12 END

Thread with 12 START PROCESS. Message = 7
Thread with 10 START PROCESS. Message = 6
Thread with 11 END

Thread with 11 START PROCESS. Message = 8
Thread with 12 END
Thread with 10 END

Thread with 11 END

Thread with 10 START PROCESS. Message = 9

Thread with 10 END
3. Sample with newSingleThreadExecutor

Sourcecode:

package com.javasampleapproach.javathreadpool;

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

public class THreadPoolSingleThreadExecutorSample {
	public static void main(String[] args) {
		// create ExecutorService
		ExecutorService executor = Executors.newSingleThreadExecutor();

		for (int i = 0; i < 10; i++) {
			Runnable worker = new Worker(Integer.toString(i));
			executor.execute(worker);
		}

		executor.shutdown();
		while (!executor.isTerminated()) {
		}

		System.out.println("Finished all threads");
	}
}

Output:

Thread with 10 START PROCESS. Message = 0
Thread with 10 END

Thread with 10 START PROCESS. Message = 1
Thread with 10 END

Thread with 10 START PROCESS. Message = 2
Thread with 10 END

Thread with 10 START PROCESS. Message = 3
Thread with 10 END

Thread with 10 START PROCESS. Message = 4
Thread with 10 END

Thread with 10 START PROCESS. Message = 5
Thread with 10 END

Thread with 10 START PROCESS. Message = 6
Thread with 10 END

Thread with 10 START PROCESS. Message = 7
Thread with 10 END

Thread with 10 START PROCESS. Message = 8
Thread with 10 END

Thread with 10 START PROCESS. Message = 9
Thread with 10 END

Finished all threads
[0x7FFD0DFA70E3] ANOMALY: use of REX.w is meaningless (default operand size is 64)

4. Source code

Java ThreadPool



By grokonez | December 21, 2016.

Last updated on June 4, 2017.



Related Posts


7 thoughts on “Java Thread Pool – ExecutorService”

  1. I am from Slovenia. I can help with build this forum. Thanks for approved.

    Jaz sem Slovenka. Lahko pomagam pri razvoju foruma.

    1. Dear Terwixonse,

      Thank you! You can send us your article and we will publish it after review

      Best Regards,
      Grokonez

  2. hiiiiiii i am spider from Arg. I would to ask you what kind of games do you like playing?? My favourite games is diablo rpg

Got Something To Say:

Your email address will not be published. Required fields are marked *

*