I have a long-running method which I want to run asynchronously. I transform the method into asynchronous method by running it on separate thread.
Original Code:
public void mainMethod() throws InterruptedException{
System.out.println("Main Method start");
longRunningMethod("testing", new Object());
otherMethod();
}
public Integer longRunningMethod(String param1,Object parm2) throws InterruptedException{
System.out.println("Long running method");
Thread.sleep(5000);
//long process
return 1;
}
public void otherMethod(){
System.out.println("Other Method");
}
New Code:
public void mainMethod() throws InterruptedException{
System.out.println("Main Method start");
//longRunningMethod("testing", new Object());
asyncServiceMethod("testing",new Object());
otherMethod();
}
public Integer longRunningMethod(String param1,Object parm2) throws InterruptedException{
System.out.println("Long running method");
Thread.sleep(5000);
//long process
return 1;
}
public void otherMethod(){
System.out.println("Other Method");
}
public void asyncServiceMethod(final String parm1,final Object obj){
Runnable task = new Runnable() {@Override
public void run() {
try {
longRunningMethod(parm1,obj);
} catch (Exception ex) {
//handle error which cannot be thrown back
}
}
};
new Thread(task, "ServiceThread").start();
}
There are few things to consider wrapping a method into asynchronous call.
- Passing Parameters must be final
- Exception from the long-running process cannot be thrown back to mainMethod (main thread). It has to be handled at separate thread (ServiceThread in the sample)
- Returning value cannot be retrieved (Integer value in this sample) from the main Method. (If one wants to retrieve, FutureTask should be used.)
Other to read

0 comments:
Post a Comment