title: Java / Scala Future driven by a callback
body: <p><strong>Short Version:</strong></p>
  
  <p>How can I create a <code>Promise&lt;Result&gt;</code> which is completed on a trigger of a callback?</p>
  
  <p><strong>Long Version:</strong></p>
  
  <p>I am working on an application which deals with third-party SOAP services. A request from user delegates to multiple SOAP services simultaneously, aggregates the results and sends back to the user.</p>
  
  <p>The system needs to be scalable and should allow multiple concurrent users. As each user requests ends up triggering about 10 web service calls and each call blocking for about 1 second, the system needs to be designed with non-blocking I/O.</p>
  
  <p>I am using Apache CXF within Play Framework (Java) for this system. I have managed to generate the Asynchronous WS Client proxies and enable the async transport. What I am unable to figure out is how to return a Future to Play's Thread when I have delegated to multiple Web Service proxies and the results will be obtained as callbacks.</p>
  
  <p><strong>Option 1:</strong> Using async method calls returning Java Future.</p>
  
  <p>As described in this <a href="https://stackoverflow.com/questions/17215421/scala-concurrent-future-wrapper-for-java-util-concurrent-future">scala.concurrent.Future wrapper for java.util.concurrent.Future</a> thread, there is no way we can convert a Java Future to a Scala Future. Only way to get a result from the Future is to do <code>Future.get()</code> which blocks the caller. Since CXF's generated proxies return Java Future, this option is ruled out.</p>
  
  <p><strong>Option 2:</strong> Use Scala Future.</p>
  
  <p>Since CXF generates the proxy interfaces, I am not sure if there is any way I can intervene and return a Scala Future (AFAIK Akka uses Scala Futures) instead of Java Future?</p>
  
  <p><strong>Option 3:</strong> Use the callback approach.</p>
  
  <p>The async methods generated by CXF which return Java Future also takes a callback object which I suppose will provide a callback when result is ready. To use this approach, I will need to return a Future which will wait until I receive a callback.</p>
  
  <p>I think <strong>Option 3</strong> is most promising, although I have no ideas about how I can return a Promise which will be completed on receiving a callback. I could possibly have a thread waiting in a <code>while(true)</code> and waiting in between until result is available. Again, I don't know how I can go into <code>wait</code> without blocking the thread?</p>
  
  <p>In a nutshell, I am trying to build a system which is making a lot of SOAP web service calls, where each call blocks for significant time. The system may easily run out of threads in case of lot of concurrent web service calls. I am working on finding a solution which is non-blocking I/O based which can allow many ongoing web service calls at the same time.</p>