Threads are often designed in two ways (see java tutorials): either by extending the Thread class or by implementing the Runnable class. Either way, you need to specify what wil
Use anonymous classes of type Callable
(which, in contrast to Runnable
, can return values) and execute them using an Executor
. If the logic to retrieve informationA and informationB is very similar, you may of course refactor that and use a single, parameterizes inner class of Callables.
I'm not sure if Callable and Executor are part of J2ME spec though. In standard Java, i'd go for a Proxy
approach anyway and encapsulate the external resource as interface.
public class AsyncMethodsTest {
public class OnlineResourceAdapter {
private final ExecutorService executor = Executors.newFixedThreadPool(2);
public String getInformationOfTypeA() throws InterruptedException, ExecutionException,
TimeoutException {
Callable callable = new Callable() {
@Override
public String call() throws Exception {
// Connect to external resource
Thread.sleep(500);
return "A";
}
};
Future submit = executor.submit(callable);
return submit.get(1000, TimeUnit.MILLISECONDS);
}
public String getInformationOfTypeB() throws InterruptedException, ExecutionException,
TimeoutException {
Callable callable = new Callable() {
@Override
public String call() throws Exception {
// Connect to external resource
Thread.sleep(1500);
return "B";
}
};
Future submit = executor.submit(callable);
return submit.get(1000, TimeUnit.MILLISECONDS);
}
}
@Test
public void testMethodCalls() throws Exception {
OnlineResourceAdapter adapter = new OnlineResourceAdapter();
assertNotNull(adapter.getInformationOfTypeA());
assertNotNull(adapter.getInformationOfTypeB());
}
}