Search code examples
javaasynccallback

Wait for the async callback function to return in java


final Function<Boolean, ? extends Class<Void>> functionCallback = (Boolean t) -> {
   if(t) {
     plugin.setIsInstalled(Boolean.TRUE);             
   }
   return Void.TYPE;
};

foo.install(plugin,functionCallback);

if(plugin.getIsInstalled().getValue())
  return "done";
else 
  return "not done";

I want to check if(plugin.getIsInstalled().getValue()) once the callback has finished executing. How can I prevent execution of this if condition until callback has completed execution?


Solution

  • You can use a FutureTask that gets called in your callback function:

    final FutureTask<Object> ft = new FutureTask<Object>(() -> {}, new Object());
    final Function<Boolean, ? extends Class<Void>> functionCallback = (Boolean t) -> {
        if(t) {
            plugin.setIsInstalled(Boolean.TRUE);
            ft.run();
        }
        return Void.TYPE;
    };
    
    foo.install(plugin,functionCallback); 
    ft.get();
    if(plugin.getIsInstalled().getValue())
        return "done";
    else 
        return "not done";
    

    Future.get waits till the run method was called, you can also use the get-method that accepts a timeout so you can react on that if it takes too long.