Reputation: 6805
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.
Upvotes: 1
Views: 110
Reputation: 9353
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 (e.g. countLines(String...paths)
) using the following idioms:
Upvotes: 1
Reputation: 45756
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.
Upvotes: 1
Reputation: 77177
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.
Upvotes: 1