1

I need to make a web request to a RESTful server from Java. I would like for my Java code to handle the response asynchronously. I am looking for a framework which handles the threading and callbacks of the request.

By the way, I took a look at FutureTask and it does not appear to be what I need because it requires the client to wait for it to complete at some point. I'm looking for a callback upon completion.

David V
  • 11,531
  • 5
  • 42
  • 66

3 Answers3

3

By the way, I took a look at FutureTask and it does not appear to be what I need because it requires the client to wait for it to complete at some point.

You don't have to call FutureTask.get() from the initiating thread in order to get the results of the task. You could just have the Callable passed to the FutureTask also handle communicating it's output to some other component. The get() methods are there so that you can get the results of the async computation, which may involve waiting for the computation to finish if it has not yet.

If you would prefer the callback style, you can simply have the Callable invoke a callback of your own construction or handle the result on it's own.

matt b
  • 138,234
  • 66
  • 282
  • 345
  • That is a good suggestion and makes sense. I have come across the ThreadPoolExecutor class, which appears to provide similar functionality. Does FutureTask have one thread, or use a thread pool? – David V Apr 04 '11 at 19:25
  • FutureTask basically just wraps around a Callable and is intended to be used by an ExecutorService (or similar service). – matt b Apr 05 '11 at 00:15
1

This is easily solved in java with the Observer Pattern

  • Create class that extends Observable and implements Runnable
  • Instantiate, pass URL to it.
  • Main object implements Observer, registers with new class as observer
  • Run your Runnable, it does a blocking HttpUrlConneciton, notifies observer with results when done
  • repeat as necessary.
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
0

Check out the ning async http client project on GitHub. It gives you the option to use a Future or to define a callback for when the request completes:

https://github.com/sonatype/async-http-client

Mike Deck
  • 18,045
  • 16
  • 68
  • 92