Dmitriy Setrakyan manages daily operations of GridGain Systems and brings over 12 years of experience to GridGain Systems which spans all areas of application software development from design and architecture to team management and quality assurance. His experience includes architecture and leadership in development of distributed middleware platforms, financial trading systems, CRM applications, and more. Dmitriy is a DZone MVB and is not an employee of DZone and has posted 54 posts at DZone. You can read more from them at their website. View Full User Profile

Asynchronous Functional APIs in Java

04.21.2011
| 6020 views |
  • submit to reddit

The major limitation of java.util.concurrent.Future class is lack of a good way to listen to future completion asynchronously. Even though Java futures are asynchronous in nature and meant to eliminate synchronous waits when not needed, the only way to get a future result is to synchronously wait for future completion. In many cases this defeats the purpose and Java futures cannot be used.

To avoid this problem we at GridGain created our own future which allows for asynchronous listening for future subscription. In addition to that we have also resolved the inconveniences of error handling and added 'duration()'method to tell users how long the future took to execute. Here is how you can add a listener to get notified, say for completion of put(..) operation on distributed cache.

...
GridCache<Integer, String> cache = grid.cache();

// Asynchronously put a value into cache.
GridFuture<String> fut = cache.putAsync(1, "1");

// Pass in a closure which will be called whenever future completes.
fut.listenAsync(new GridInClosureX<GridFuture<String>>() {
public void applyx(GridFuture<String> fut) throws GridException {
V previousValue = fut.get();

long duration = fut.duration();

System.out.println("Finished cache put operation [prev=" +
previousValue + ", duration= + duration + "ms]");
}
});
...

 GridFuture is used for all asynchronous operations in GridGain, including both, compute and data grid features. Hope you find it useful.

From http://gridgain.blogspot.com/2011/04/asynchronous-functional-apis-in-java.html

Published at DZone with permission of Dmitriy Setrakyan, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Michal Xorty replied on Thu, 2011/04/21 - 3:56am

Is this something like GWT's AsyncCallback?

Shoaib Almas replied on Sat, 2012/08/25 - 5:50am

I think you should pass the listener to Cache#put() as third parameter.
Because now there is a way that #put() is too fast and returns before you register the listener

Java Forum

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.