简体   繁体   中英

Seeking example of asynchronous methods in Java standard library

I'd like to find an example in the Java standard libraries of a method that takes a callback as an argument, returns immediately, and invokes the callback when it has completed its task. For example, you could imagine a method to get user input from the keyboard that returns immediately but invokes the callback once the input has been entered.

Next best would be a method that calls a listener when it has completed its task. An example from the Android SDK would be SoundPool.load() and SoundPool.setOnLoadCompleteListener() .

I don't consider Swing methods like addActionListener() to be examples, since the purpose of the method is to add the listener. The triggering event is entirely separate.

My motivation is preparing a lecture on Java I/O and wanting to contrast methods that (1) block, (2) return immediately with or without data, or (3) use callbacks.

The Java standard library generally uses the Future abstraction instead of a callback as the core building block. If you want to build a "callback-based" structure, you then use the then* methods on CompletionStage (typically CompletableFuture ).

This structure allows for flexibility in how the caller wants asynchronous results handled; for example, I've used it for scatter-gather on multiple downstream API calls used to build a compound result.

One group of examples you're looking for is the Java NIO AynchronousChannel implementations. For instance:

As you can see, all those methods (and others not listed) use the provided CompletionHandler to notify callers of completion, whether the operation succeeded or failed. Most, if not all, of those methods have an overload which does not accept a CompletionHandler but instead returns a Future .

There's also java.util.concurrent.CompletionStage , which has many methods which invoke some functional interface implementation once the stage is complete.

Check https://github.com/javasync/idioms . You may find here different approaches of using asynchronicity with non-blocking IO with an example of counting the total number of lines of given files (eg countLines(String...paths) ) using the following idioms:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM