Given the following code fragment:
00: ExecutorService es = ...
01: // es.submit(() -〉 {;} );
02: // es.submit(() -〉 null );
03: // es.submit(() -〉 { throw new NullPointerException(); });
04: // es.submit(() -〉 { throw new IOException(); });
05: // es.submit(() -〉 new SQLException());
Which line or lines, when uncommented individually, will compile successfully? Choose one.
- * Only line 01
- * Only lines 01 and 02
- * Only lines 01, 02, and 03
- * Only lines 01, 02, 03, and 04
- * All lines will compile successfully
#java #certificationquestion #ocp
Answer. The java.util.concurrent.ExecutorService has three overloaded submit(...) methods.
* 〈T〉 Future〈T〉 submit(Callable〈T〉 task);
* Future〈?〉 submit(Runnable task);
* 〈T〉 Future〈T〉 submit(Runnable task, T result);
In each case, the task is defined by a particular method on the argument object, and that task-defining method is declared in the interface Callable or Runnable.
Those interfaces have the following forms:
public interface Runnable {
public abstract void run();
}
public interface Callable〈V〉 {
V call() throws Exception;
}
Notice that there are two significant differences between them.
* A Callable returns a value, whereas the Runnable declares a void method.
* A Callable may throw a checked exception, but a Runnable can throw only an unchecked exception.
Now, let's check the suggestions one by one:
Line 01: () -〉 {;}
This lambda body does not return any value, so it can implement only Runnable.
Line 01 is valid and will compile.
Line 02: () -〉 null
This form creates a Callable because it returns a value.
Line 02 is also valid.
In lines 03 and 04, the lambda has a body that consistently throws an exception.
Runnable can throw only unchecked exceptions, but a Callable may throw any exception.
This means that line 03 could be either a Runnable or a Callable, but line 04 must be a Callable.
Both lines are valid and will compile.
Line 05: () -〉 new SQLException()
It returns an exception, rather than throwing an exception.
However, exceptions are objects, so the code forms a Callable because it returns a value.
Line 05 is valid and will compile.
All five lambdas are valid.