Thursday, July 30, 2009

The Callable Interface

Recall that there are two ways of creating threads. We can either extend the Thread class or implement the Runnable interface. In whichever technique used, we customize its functionality by overriding the run method. The method has the following signature:


Java Tutorial Source Code: The Callable Interface

public void run()

The drawbacks in creating threads this way are:
  1. The run method cannot return a result since it has void as its return type.
  2. Second, the run method requires you to handle checked exceptions within this method since the overriden method does not use any throws clause.
The Callable interface is basically the same as the Runnable interface without its drawbacks. To get the result from a Runnable task, we have to use some external means of getting the result. A common technique of which is to use an instance variable for storing the result. The next code shows how this can be done.

public MyRunnable implements Runnable {
private int result = 0;

public void run() {
...
result = someValue;
}

/* The result attribute is protected from changes from other
codes accessing this class */
public int getResult() {
return result;
}
}

Java Tutorial Source Code: The Callable Interface

With the Callable interface, getting the result is simple as shown in the next example.

import java.util.concurrent.*;

public class MyCallable implements Callable {
public Integer call() throws java.io.IOException {
...
return someValue;
}
}

The call method has the following signature:

V call throws Exception

V here is a generic type, which means that the return type of call can be of any reference type. You will learn more about generic types in a latter chapter.

There are still more concurrency features in J2SE5.0. Please refer to the API documentation for a detailed discussion of these other features.

No comments:

Post a Comment