Java Multithreading: Callable and Future (Video Tutorial Part 13)

How to use Callable and Future in Java to get results from your threads and to allow your threads to throw exceptions. Plus, Future allows you to control your threads, checking to see if they’re running or not, waiting for results and even interrupting them or descheduling them.

After starting the video, click the maximise button to make it fullscreen so you can see the code!

Code For This Tutorial

Starting ...
Finished.
Result is: 792
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class App {

	public static void main(String[] args) {
		ExecutorService executor = Executors.newCachedThreadPool();
		
		Future future = executor.submit(new Callable() {

			@Override
			public Integer call() throws Exception {
				Random random = new Random();
				int duration = random.nextInt(4000);
				
				if(duration > 2000) {
					throw new IOException("Sleeping for too long.");
				}
				
				System.out.println("Starting ...");
				
				try {
					Thread.sleep(duration);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				System.out.println("Finished.");
				
				return duration;
			}
			
		});
		
		executor.shutdown();
		
		try {
			System.out.println("Result is: " + future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			IOException ex = (IOException) e.getCause();
			
			System.out.println(ex.getMessage());
		}
	}

}

Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.

All pages on this site are copyright © 2013 John W. Purcell

4 Responses to Java Multithreading: Callable and Future (Video Tutorial Part 13)

  1. sandy says:

    Your multithreading videos are the best. They beautifully illustrated the concepts that I was unable to fully grasp for some time.

    Thanks a lot for sharing your knowledge!!

  2. Mithun says:

    went through the advanced threading tutorials.
    the are very good.
    would love to see if you have anything covering spring ?

    • Squiffy says:

      Cheers. I don’t have anything on Spring, but I’ll definitely keep it in mind for a future possible topic.

  3. zkh says:

    i think it is best if you include java networking as a separate tutorial

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>

Posted in Java, Java Multithreading, Java Video Tutorials (Advanced) | Tagged , , , , , , |