Execute Java callback on new thread
In this project, the manager performs event queuing and returns the result of the event using a callback (the callback does not extend runnable) The manager runs on a separate thread and schedules events Once the event terminates, the same thread invokes the callback This means that the next event will not be scheduled until the callback of the previous event terminates To avoid this, I want the manager to create a new thread for each callback and execute the callback there How good is this solution in design practice, and is there a better way to achieve this goal?
Solution
A 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); //System.out.println("future status:"+future.get()+":"+future.isDone()); } }catch(Exception err){ err.printStackTrace(); } service.shutdown(); } public static void main(String args[]){ CallBackDemo demo = new CallBackDemo(); } } class MyCallable implements Callable<Long>{ Long id = 0L; Callback callback; public MyCallable(Long val,Callback obj){ this.id = val; this.callback = obj; } public Long call(){ //Add your business logic System.out.println("Callable:"+id+":"+Thread.currentThread().getName()); callback.callbackMethod(); return id; } } class Callback { private int i; public Callback(int i){ this.i = i; } public void callbackMethod(){ System.out.println("Call back:"+i); // Add your business logic } }
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 the manager with your preferred executorservice. > You can pass a callaback object to a callable / runnable object, or you can create a callback object in callable / runnable In my example, I have explicitly passed the callback object to callable. > The callable object calls the callback method before returning the result If you want to prevent it from continuing unless you receive a response to the current event, please uncomment below
System.out.println("future status:"+future.get()+":"+future.isDone());
I think you'll avoid it, so stay above the comments You do not have to create a new thread for the callback method call If you want to process the callback event asynchronously, you can create another executorservice and submit the event