Posts

Showing posts from March, 2017

Java Concurrency - Multi Threading with ExecutorService

In this post I'll look how the ExeutorService can be used to perform multi threaded asynchronous tasks. I'll begin by looking at the traditional approach of creating threads directly and then move on to examine the ExecutorService and how it can be used to simplify things.

Instantiating Threads Directly Prior to the Executor API developers were responsible for instantiating and managing threads directly. Lets look at a simple example below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /** * Call 2 expensive methods on separate threads * * @throws InterruptedException */publicvoid doMultiThreadedWork() throws InterruptedException { /* create Runnable using anonymous inner class */ Thread t1 = new Thread(new Runnable() { publicvoid run() { System.out.println("starting expensive task thread t1"); doSomethingExpensive(); System.out.println("fi…