Java ExecutorService

Today we are going to describe briefly Java ExecutorService mechanism. Some time ago we have shown you how you can easily speed up your programs execution using threads in Java – How to speed up applications using threads in java. Back then we have discussed the barrier concept – a place in your code where main thread waits for other threads that are running. Back then we had to use our custom Lock object to synchronize program execution.
Java 6 introduced the ExecutorService mechanism using which synchronizing your program execution is much more easier. Take a look at the example code.

package com.itcuties.java.threads;

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

/**
 * ExecutorService example. 
 * Waiting for threads to finish their work.
 * 
 * @author itcuties
 *
 */
public class ExecutorServiceExample {

	// Run threads
	public static void main(String[] args)  {
		System.out.println("["+System.currentTimeMillis()+"]["+Thread.currentThread().getName()+"]:: starting");
		
		// Executor service that can execute up to 5 threads
		ExecutorService executor = Executors.newFixedThreadPool(5);
		
		for (int i=0; i < 10; i++) {
			Runnable thread = new Runnable() {
				// Sample thread - prints out random numbers
				public void run() {
					Random random = new Random();
					for (int i=0; i < 10; i++) {
						System.out.println("["+System.currentTimeMillis()+"]["+Thread.currentThread().getName()+"]:: lucky numer is " + random.nextInt(10000));
					}
				}};
				
			
			executor.execute(thread);
			
		}
		
		// Accept no more new threads
		executor.shutdown();
		
		// Waiting for all the threads to finish
		while(!executor.isTerminated()) {
			try {
				Thread.sleep(100);
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("["+System.currentTimeMillis()+"]["+Thread.currentThread().getName()+"]:: done");
		
	}
	
}

Then you run this code you will get the following output:

[1356644101826][main]:: starting
[1356644101856][pool-1-thread-3]:: lucky numer is 1382
[1356644101856][pool-1-thread-2]:: lucky numer is 2354
[1356644101856][pool-1-thread-1]:: lucky numer is 3254
[1356644101856][pool-1-thread-4]:: lucky numer is 8874
[1356644101856][pool-1-thread-1]:: lucky numer is 5498
...
[1356644101856][pool-1-thread-5]:: lucky numer is 423
[1356644101856][pool-1-thread-5]:: lucky numer is 5269
[1356644101856][pool-1-thread-5]:: lucky numer is 6121
[1356644101856][pool-1-thread-5]:: lucky numer is 3681
[1356644101856][pool-1-thread-5]:: lucky numer is 7692
[1356644101856][pool-1-thread-5]:: lucky numer is 8842
[1356644101956][main]:: done

As you can see it takes only like 4 lines of code implement barrier concept in your code.

// 1. Executor service that can execute up to 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
...
// 2. Execute a thread in the Executor
executor.execute(thread);
…
// 3. Shutdown the executor - it will take no new threads for execution
executor.shutdown();

// 4. Wait for the Executor to process all the threads
while(!executor.isTerminated()) {...}

Download this sample code here.

This code is available on our GitHub repository as well.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW