Simple Callback Code:
import java.util.concurrent.*; import java.util.*; public class CallBackDemo{ public CallBackDemo(){ System.out.println("creating service"); ExecutorService service = Executors.newFixedThreadPool(10); try{ for ( int i=0; i<10; i++){ Callback callback = new Callback(i+1); MyCallable myCallable = new MyCallable((long)i+1,callback); Future<Long> future = service.submit(myCallable);
output:
creating service Callable:1:pool-1-thread-1 Call back:1 Callable:2:pool-1-thread-2 Call back:2 Callable:8:pool-1-thread-8 Call back:8 Callable:3:pool-1-thread-3 Call back:3 Callable:10:pool-1-thread-10 Callable:4:pool-1-thread-4 Call back:10 Callable:7:pool-1-thread-7 Call back:7 Callable:6:pool-1-thread-6 Call back:6 Callable:9:pool-1-thread-9 Callable:5:pool-1-thread-5 Call back:9 Call back:4 Call back:5
Summary:
- Replace
Manager with ExecutorService your preferred choice. - Or you can pass the
Callaback object to the Callable/Runnable object. Or you can create a Callback object inside a Callable/Runnable . In my example, I explicitly passed the Callback object to the Callable . Before returning the result, the Callable object calls the Callback method. If you want to block further actions, if you do not receive a response from the current event, just uncomment the lines below.
System.out.println("future status:"+future.get()+":"+future.isDone());
I think you are avoiding this, and therefore keep reading above the line. You do not need to create a new thread to call the Callback method. If you want to handle the Callback event asynchronously, you can create another ExecutorService and dispatch the event.
source share