Thursday, April 14, 2016

Write async methods in Java

In the below example code you can find out how to write your own async methods and invoke it.


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 MyAsyncUtil {

public static void main(String[] args) throws InterruptedException, ExecutionException {

System.out.println("Starting...");
ExecutorService pool = Executors.newFixedThreadPool(3);
Future<Result> future = pool.submit(new AsyncCallable("My async method"));

for(int i=0;i<10;i++){
System.out.println("cc");
}
//Compute the result
Result result = future.get();
System.out.println(result.isResult());
System.out.println(result.getResponse());
pool.shutdownNow();
System.out.println("cool");
System.out.println(pool.isShutdown());
}
}


class AsyncCallable implements Callable<Result>{

private String str;

public AsyncCallable(String str1){
this.str = str1;
}

@Override
public Result call() throws Exception {
try{

Thread.sleep(5*1000);
System.out.println(str);
System.out.println("*** End of Thread ***");
}catch(Exception ex){
//System.exit(0);
return new Result(Thread.currentThread().getName(),
false,ex);
}
return new Result(Thread.currentThread().getName(),
true, null, "PASS");
}

public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}

}


The result class is to get the result of the execution of async method.

class Result implements Cloneable{
private String threadName;
private boolean result;
private Exception thrownEx;
private Object response;

public String getThreadName() {
return threadName;
}

public void setThreadName(String threadName) {
this.threadName = threadName;
}

public boolean isResult() {
return result;
}

public void setResult(boolean result) {
this.result = result;
}

public Exception getThrownEx() {
return thrownEx;
}

public void setThrownEx(Exception thrownEx) {
this.thrownEx = thrownEx;
}

public Result(String threadName, boolean result, Exception thrownEx){
this.threadName=threadName;
this.result=result;
this.thrownEx=thrownEx;
}

public Result(String threadName, boolean result, Exception thrownEx,
Object o){
this(threadName,result,thrownEx);
this.response = o;
}

@Override
protected Result clone() throws CloneNotSupportedException {
return (Result) super.clone();
}

public Object getResponse() {
return response;
}

public void setResponse(Object response) {
this.response = response;
}
}

No comments:

Post a Comment