This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is a callback function?
I have read the wikipedia definition of a callback but I still didn't get it. Can anyone explain me what a callback is, especially the following line
In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.
Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.
Paul Jakubik, Callback Implementations in C++.
Maybe an example would help.
Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.
A callback is some code that you pass to a given method, so that it can be called at a later time.
In Java one obvious example is java.util.Comparator. You do not usually use a Comparator directly; rather, you pass it to some code that calls the Comparator at a later time:
Example:
class CodedString implements Comparable<CodedString> {
private int code;
private String text;
...
#Override
public boolean equals() {
// member-wise equality
}
#Override
public int hashCode() {
// member-wise equality
}
#Override
public boolean compareTo(CodedString cs) {
// Compare using "code" first, then
// "text" if both codes are equal.
}
}
...
public void sortCodedStringsByText(List<CodedString> codedStrings) {
Comparator<CodedString> comparatorByText = new Comparator<CodedString>() {
#Override
public int compare(CodedString cs1, CodedString cs2) {
// Compare cs1 and cs2 using just the "text" field
}
}
// Here we pass the comparatorByText callback to Collections.sort(...)
// Collections.sort(...) will then call this callback whenever it
// needs to compare two items from the list being sorted.
// As a result, we will get the list sorted by just the "text" field.
// If we do not pass a callback, Collections.sort will use the default
// comparison for the class (first by "code", then by "text").
Collections.sort(codedStrings, comparatorByText);
}
Strictly speaking, the concept of a callback function does not exist in Java, because in Java there are no functions, only methods, and you cannot pass a method around, you can only pass objects and interfaces. So, whoever has a reference to that object or interface may invoke any of its methods, not just one method that you might wish them to.
However, this is all fine and well, and we often speak of callback objects and callback interfaces, and when there is only one method in that object or interface, we may even speak of a callback method or even a callback function; we humans tend to thrive in inaccurate communication.
(Actually, perhaps the best approach is to just speak of "a callback" without adding any qualifications: this way, you cannot possibly go wrong.
See next sentence.)
One of the most famous examples of using a callback in Java is when you call an ArrayList object to sort itself, and you supply a comparator which knows how to compare the objects contained within the list.
Your code is the high-level layer, which calls the lower-level layer (the standard java runtime list object) supplying it with an interface to an object which is in your (high level) layer. The list will then be "calling back" your object to do the part of the job that it does not know how to do, namely to compare elements of the list. So, in this scenario the comparator can be thought of as a callback object.
A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".
In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html
In Java, callback methods are mainly used to address the "Observer Pattern", which is closely related to "Asynchronous Programming".
Although callbacks are also used to simulate passing methods as a parameter, like what is done in functional programming languages.
Related
In Java, assume you have a data object object with an attribute bar that you need to set with a value that is returned from a complex operation done in an external source. Assume you have a method sendRequestToExternalSource that send a request based on 'object' to the external source and gets an object back holding (among other things) the needed value.
Which one of these ways to set the value is the better practice?
void main(MyObject object) {
bar = sendRequestToExternalSource(object);
object.setBar(bar);
}
String sendRequestToExternalSource(MyObject object) {
// Send request to external source
Object response = postToExternalSource(object);
//Do some validation and logic based on response
...
//Return only the attribute we are interested in
return response.getBar();
}
or
void main(MyObject object) {
sendRequestToExternalSourceAndUpdateObject(object);
}
void sendRequestToExternalSourceAndUpdateObject(MyObject object) {
// Send request to external source
Object response = postToExternalSource(object);
//Do some validation and logic based on response
...
//Set the attribute on the input object
object.setBar(response.getBar());
}
I know they both work, but what is the best practice?
It depends on a specific scenario. Side-effects are not bad practice but there are also scenarios where a user simply won't expect them.
In any case your documentation of such a method should clearly state if you manipulate arguments. The user must be informed about that since it's his object that he passes to your method.
Note that there are various examples where side-effects intuitively are to be expected and that's also totally fine. For example Collections#sort (documentation):
List<Integer> list = ...
Collections.sort(list);
However if you write a method like intersection(Set, Set) then you would expect the result being a new Set, not for example the first one. But you can rephrase the name to intersect and use a structure like Set#intersect(Set). Then the user would expect a method with void as return type where the resulting Set is the Set the method was invoked on.
Another example would be Set#add. You would expect that the method inserts your element and not a copy of it. And that is also what it does. It would be confusing for people if it instead creates copies. They would need to call it differently then, like CloneSet or something like that.
In general I would tend to giving the advice to avoid manipulating arguments. Except if side-effects are to be expected by the user, as seen in the example. Otherwise the risk is too high that you confuse the user and thus create nasty bugs.
I would choose the first one if I have only these two choices. And the reason of that is "S" in SOLID principles, single responsibility. I think the job of doComplicatedStuff method is not setting new or enriched value of bar to MyObject instance.
Of course I don't know use case that you are trying to implement, but I suggest looking at decorator pattern to modify MyObject instance
I personally prefer the variant barService.doComplicatedStuff(object); because I avoid making copies
In Cocos2d-x (3.6) I am trying to add increased functionality to SimpleAudioEngine. Specifically, with regard to Android's SoundPool (which SimpleAudioEngine is based upon, at least for Android), I am trying to add some of the methods that have not yet been implemented but are documented in the Android Developer web site.
For example, SoundPool's play method includes a loop variable that is of type int, whereas in SimpleAudioEngine it is of type bool (boolean on the Java side). If I can implement a new method with the loop variable as type int, I will be able to control the number of repetitions directly when I call the playEffect method.
I have figured out most of the changes required, including various C++ header and .cpp files (cocos/audio/include/SimpleAudioEngine.h, cocos/audio/android/cddSimpleAudioEngine.cpp, cocos/audio/android/jni/cddandroidAndroidJavaEngine.h, and cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp) and also the Cocos2dxSound.java file, but I am still getting error messages saying that my new method (which I am calling playEffectN) cannot be found.
The only other place I can see where something might need to be added is in the cocos/audio/openal/SimpleAudioEngineOpenAL.cpp file, but I'm not quite sure how to modify that in order to add my new method.
Can anyone point me in the right direction as to what else I need to do in order to add this additional functionality to SimpleAudioEngine? If I am successful, I will gladly share the results. (If successful, I will also be able to add some of the other unimplemented methods in SoundPool, such as setLoop, setPriority, setRate, and setVolume, for sounds that have already been assigned a soundID.)
first, add c++ apis, in :
cocos/audio/include/AudioEngine.h
though there is no implement in cddSimpleAudioEngine.cpp, you still need to declare functions in AudioEngine.h
then, the bridge btween c++ and java:
cocos/audio/android/jni/cddandroidAndroidJavaEngine.h
cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp
here, declare in cddandroidAndroidJavaEngine.h and implement in cddandroidAndroidJavaEngine.cpp, like
void AndroidJavaEngine::playEffectN(int times) {
cocos2d::JniMethodInfo methodInfo;
if (! getJNIStaticMethodInfo(methodInfo, "playEffectN", "(I)V")) {
return ;
}
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, times);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
then in java
cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java
add function like:
public static void playEffectN(int times) {
}
finally is your java implement, in
cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java
Please note: I am a Java developer with no working knowledge of Scala (sadly). I would ask that any code examples provided in the answer would be using Akka's Java API.
I am trying to use the Akka FSM API to model the following super-simple state machine. In reality, my machine is much more complicated, but the answer to this question will allow me to extrapolate to my actual FSM.
And so I have 2 states: Off and On. You can go fro Off -> On by powering the machine on by calling SomeObject#powerOn(<someArguments>). You can go from On -> Off by powering the machine off by calling SomeObject#powerOff(<someArguments>).
I'm wondering what actors and supporting classes I'll need in order to implement this FSM. I believe the actor representing the FSM has to extend AbstractFSM. But what classes represent the 2 states? What code exposes and implements the powerOn(...) and powerOff(...) state transitions? A working Java example, or even just Java pseudo-code, would go a long way for me here.
I think we can do a bit better than copypasta from the FSM docs (http://doc.akka.io/docs/akka/snapshot/java/lambda-fsm.html). First, let's explore your use case a bit.
You have two triggers (or events, or signals) -- powerOn and powerOff. You would like send these signals to an Actor and have it change state, of which the two meaningful states are On and Off.
Now, strictly speaking an FSM needs one additional component: an action you wish to take on transition.
FSM:
State (S) x Event (E) -> Action (A), State (S')
Read: "When in state S, if signal E is received, produce action A and advance to state S'"
You don't NEED an action, but an Actor cannot be directly inspected, nor directly modified. All mutation and acknowledgement occurs through asynchronous message passing.
In your example, which provides no action to perform on transition, you basically have a state machine that's a no-op. Actions occur, state transitions without side effect and that state is invisible, so a working machine is identical to a broken one. And since this all occurs asynchronously, you don't even know when the broken thing has finished.
So allow me to expand your contract a little bit, and include the following actions in your FSM definitions:
When in Off, if powerOn is received, advance state to On and respond to the caller with the new state
When in On, if powerOff is received, advance state to Off and respond to the caller with the new state
Now we might be able to build an FSM that is actually testable.
Let's define a pair of classes for your two signals. (the AbstractFSM DSL expects to match on class):
public static class PowerOn {}
public static class PowerOff {}
Let's define a pair of enums for your two states:
enum LightswitchState { on, off }
Let's define an AbstractFSM Actor (http://doc.akka.io/japi/akka/2.3.8/akka/actor/AbstractFSM.html). Extending AbstractFSM allows us to define an actor using a chain of FSM definitions similar to those above rather than defining message behavior directly in an onReceive() method. It provides a nice little DSL for these definitions, and (somewhat bizarrely) expects that the definitions be set up in a static initializer.
A quick detour, though: AbstractFSM has two generics defined which are used to provide compile time type checking.
S is the base of State types we wish to use, and D is the base of Data types. If you're building an FSM that will hold and modify data (maybe a power meter for your light switch?), you would build a separate class to hold this data rather than trying to add new members to your subclass of AbstractFSM. Since we have no data, let's define a dummy class just so you can see how it gets passed around:
public static class NoDataItsJustALightswitch {}
And so, with this out of the way, we can build our actor class.
public class Lightswitch extends AbstractFSM<LightswitchState, NoDataItsJustALightswitch> {
{ //static initializer
startWith(off, new NoDataItsJustALightswitch()); //okay, we're saying that when a new Lightswitch is born, it'll be in the off state and have a new NoDataItsJustALightswitch() object as data
//our first FSM definition
when(off, //when in off,
matchEvent(PowerOn.class, //if we receive a PowerOn message,
NoDataItsJustALightswitch.class, //and have data of this type,
(powerOn, noData) -> //we'll handle it using this function:
goTo(on) //go to the on state,
.replying(on); //and reply to the sender that we went to the on state
)
);
//our second FSM definition
when(on,
matchEvent(PowerOff.class,
NoDataItsJustALightswitch.class,
(powerOn, noData) -> {
goTo(off)
.replying(off);
//here you could use multiline functions,
//and use the contents of the event (powerOn) or data (noData) to make decisions, alter content of the state, etc.
}
)
);
initialize(); //boilerplate
}
}
I'm sure you're wondering: how do I use this?! So let's make you a test harness using straight JUnit and the Akka Testkit for java:
public class LightswitchTest {
#Test public void testLightswitch() {
ActorSystem system = ActorSystem.create("lightswitchtest");//should make this static if you're going to test a lot of things, actor systems are a bit expensive
new JavaTestKit(system) {{ //there's that static initializer again
ActorRef lightswitch = system.actorOf(Props.create(Lightswitch.class)); //here is our lightswitch. It's an actor ref, a reference to an actor that will be created on
//our behalf of type Lightswitch. We can't, as mentioned earlier, actually touch the instance
//of Lightswitch, but we can send messages to it via this reference.
lightswitch.tell( //using the reference to our actor, tell it
new PowerOn(), //to "Power On," using our message type
getRef()); //and giving it an actor to call back (in this case, the JavaTestKit itself)
//because it is asynchronous, the tell will return immediately. Somewhere off in the distance, on another thread, our lightbulb is receiving its message
expectMsgEquals(LightswitchState.on); //we block until the lightbulb sends us back a message with its current state ("on.")
//If our actor is broken, this call will timeout and fail.
lightswitch.tell(new PowerOff(), getRef());
expectMsgEquals(LightswitchState.off);
system.stop(lightswitch); //switch works, kill the instance, leave the system up for further use
}};
}
}
And there you are: an FSM lightswitch. Honestly though, an example this trivial doesn't really show the power of FSMs, as a data-free example can be performed as a set of "become/unbecome" behaviors in like half as many LoC with no generics or lambdas. Much more readable IMO.
PS consider learning Scala, if only to be able to read other peoples' code! The first half of the book Atomic Scala is available free online.
PPS if all you really want is a composable state machine, I maintain Pulleys, a state machine engine based on statecharts in pure java. It's getting on in years (lot of XML and old patterns, no DI integration) but if you really want to decouple the implementation of a state machine from inputs and outputs there may be some inspiration there.
I know about Actors in Scala.
This Java Start Code may help you, to go ahead:
Yes, extend your SimpleFSM from AbstractFSM.
The State is an enum in the AbstractFSM.
Your <someArguments> can be the Data Part in your AbstractFSM
Your powerOn and powerOff are Actor Messages/Events.
And the State switching is in the transitions Part
// states
enum State {
Off, On
}
enum Uninitialized implements Data {
Uninitialized
}
public class SimpleFSM extends AbstractFSM<State, Data> {
{
// fsm body
startWith(Off, Uninitialized);
// transitions
when(Off,
matchEvent(... .class ...,
(... Variable Names ...) ->
goTo(On).using(...) ); // powerOn(<someArguments>)
when(On,
matchEvent(... .class ...,
(... Variable Names ...) ->
goTo(Off).using(...) ); // powerOff(<someArguments>)
initialize();
}
}
Real working Project see
Scala and Java 8 with Lambda Template for a Akka AbstractFSM
Well this is a really old question but if you get as a hit from Google, but if you are still interested implementing FSM with Akka, I suggest to look this part of the documentation.
If you want to see how a practical model driven state machine implementation, you can check my blog1, blog2.
I've got some crazy task, that sounds like mission impossible. I need to pass some data through stack of methods, which I can't modify (can modify only the last one). Example:
SomeData someData; //not passed in method1
obj1.method1(...);
here is obj1 class code
obj1 {
someReturnClass method1(...) {
...
obj2.method2(...);
...
}
}
obj2 and method2 call some more methods, before they get to objN.methodM(). It can even be run in separate thread (so, ThreadLocal won't help). I need to access someData inside methodM, which is not passed through this stack as parameter.
I've got some concepts to get it through exception and double running methodM, but it looks ugly.
Do you have any ideas, how to pass someData to methodM()?
If you can't smuggle access any other way -- e.g. by adding a reference to SomeData into some other object that is passed through the call stack -- then you will eventually have to use a global variable. This is of course a poor design, but nothing else is possible given your constraints.
You mentioned in a comment that you may have several calls to your method "active" (is it recursive, or do you have multiple threads?) In that case, you will need to have a global collection instead, and have some way of inferring which element of the collection to select from the data that is passed through the call stack.
I understand that you need to access a local variable inside a method activation, of a method which you can't change, but which you know exists lower on the stack.
The obvious thing here is to work with the Java Debugging Architecture: http://docs.oracle.com/javase/7/docs/technotes/guides/jpda/index.html
This will allow you to examine the stacks of all threads.
Finally, I found solution:
Create JAAS Subject
Subject subject = new Subject();
Put data somewhere in subject's principals or credentials:
subject.getPublicCredentials().add(new String("Trololo"));
Get this subject and it's data anywhere you need (works even in another thread):
Subject subject = Subject.getSubject(AccessController.getContext());
System.out.println(subject.getPublicCredentials());
It won't work only in one case: thread started before subject was created.
I'm looking for a Java pattern for making a nested sequence of non-blocking method calls. In my case, some client code needs to asynchronously invoke a service to perform some use case, and each step of that use case must itself be performed asynchronously (for reasons outside the scope of this question). Imagine I have existing interfaces as follows:
public interface Request {}
public interface Response {}
public interface Callback<R extends Response> {
void onSuccess(R response);
void onError(Exception e);
}
There are various paired implementations of the Request and Response interfaces, namely RequestA + ResponseA (given by the client), RequestB + ResponseB (used internally by the service), etc.
The processing flow looks like this:
In between the receipt of each response and the sending of the next request, some additional processing needs to happen (e.g. based on values in any of the previous requests or responses).
So far I've tried two approaches to coding this in Java:
anonymous classes: gets ugly quickly because of the required nesting
inner classes: neater than the above, but still hard for another developer to comprehend the flow of execution
Is there some pattern to make this code more readable? For example, could I express the service method as a list of self-contained operations that are executed in sequence by some framework class that takes care of the nesting?
Since the implementation (not only the interface) must not block, I like your list idea.
Set up a list of "operations" (perhaps Futures?), for which the setup should be pretty clear and readable. Then upon receiving each response, the next operation should be invoked.
With a little imagination, this sounds like the chain of responsibility. Here's some pseudocode for what I'm imagining:
public void setup() {
this.operations.add(new Operation(new RequestA(), new CallbackA()));
this.operations.add(new Operation(new RequestB(), new CallbackB()));
this.operations.add(new Operation(new RequestC(), new CallbackC()));
this.operations.add(new Operation(new RequestD(), new CallbackD()));
startNextOperation();
}
private void startNextOperation() {
if ( this.operations.isEmpty() ) { reportAllOperationsComplete(); }
Operation op = this.operations.remove(0);
op.request.go( op.callback );
}
private class CallbackA implements Callback<Boolean> {
public void onSuccess(Boolean response) {
// store response? etc?
startNextOperation();
}
}
...
In my opinion, the most natural way to model this kind of problem is with Future<V>.
So instead of using a callback, just return a "thunk": a Future<Response> that represents the response that will be available at some point in the future.
Then you can either model subsequent steps as things like Future<ResponseB> step2(Future<ResponseA>), or use ListenableFuture<V> from Guava. Then you can use Futures.transform() or one of its overloads to chain your functions in a natural way, but while still preserving the asynchronous nature.
If used in this way, Future<V> behaves like a monad (in fact, I think it may qualify as one, although I'm not sure off the top of my head), and so the whole process feels a bit like IO in Haskell as performed via the IO monad.
You can use actor computing model. In your case, the client, services, and callbacks [B-D] all can be represented as actors.
There are many actor libraries for java. Most of them, however, are heavyweight, so I wrote a compact and extendable one: df4j. It considers actor model as a specific case of more general dataflow computing model and, as a result, allows user to create new types of actors, to optimally fit user's requirements.
I am not sure if I get you question correctly. If you want to invoke a service and on its completion result need to be passed to other object which can continue processing using result. You can look at using Composite and Observer to achive this.