0

I have service method which return DefferedResult<Foo> in few seconds, but I need my code will wait until that method finish and return deferred result with set result.

Here is sample code:

@Service
public class FooService {
   // ...
   public DeferredResult<Foo> fetchFoo(long id) throws InterruptedException {
       DeferredResult<Foo> fooDeferredResult = new DeferredResult<>();
       concurrentMap.put(id, fooDeferredResult);
       return fooDeferredResult;
   }

   // this you can figure out as some handler or scheduler which receive messages and is called
   public void anotherMethod(Foo foo) {
       DeferredResult<Foo> remove = concurrentMap.remove(foo.getId());
       remove.setResult(foo);
   }
   // ...
}

and I want call it in another service:

@Service
public class AnotherService {

    @Autowired
    FooService fooService;

    public Foo bar(long id) {
        // some logic
        Foo foo = fooService.fetchFoo(id).getResult();
        // another logic which depends on received foo
        // there I need wait for result of fetchFoo method

        return foo;
    }

}

Can you tell me please how to ensure this behaviour? Thank you in advice.

Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174

1 Answers1

0

You can use CountDownLatch for synchronize. Example:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(1);

        CountDownLatch latch = new CountDownLatch(1);
        getResult()
                .setResultHandler(result -> {
                    System.out.println(2 + " " + result);
                    latch.countDown();
                });

        latch.await();
        System.out.println(3);
    }

    public static DeferredResult<String> getResult() {
        DeferredResult<String> result = new DeferredResult<>();
        
        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result.setResult("Hello");
        })
                .start();
        return result;
    }
}
Nick
  • 3,691
  • 18
  • 36