I have been trying to wrap my head around callbacks and have been struggling to grasp the concept. The following code is an example that I found here
starting from first to last I understand the flow to be such:
CallMe is instantiated, thus calling the constructor of said class
The variable en is set, subsequently instantiating the EventNotifier class and calling it's constructor which is passed a reference to the object CallMe
The variable ie is set to the object CallMe which was passed into the constructor
The variable somethinghappened is set to false (I would assume some conditional statement would be used to determine whether or not to set the value otherwise)
Ummm... done?
I do not understand this code. How does doWork get called? How does this signify an event? Why would one not simply call interestingevent from the constructor of callme .... For that matter why not just call dowork in place of whatever would change the value of somethinghappened?
Try as I might I cannot seem to grasp the idea. I understand that callbacks are used primarily to signify an event has occurred such as a mouse or button click but how does it make the connection between the event occurring and the methods being called? Should there not be a loop that checks for changes, and thus triggers the event?
Can someone please provide a (not over-simplified) explanation of callbacks in java and help clarify how something like this could be useful?
public interface InterestingEvent
{
public void interestingEvent ();
}
public class EventNotifier
{
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event)
{
ie = event;
somethingHappened = false;
}
public void doWork ()
{
if (somethingHappened)
{
ie.interestingEvent ();
}
}
}
public class CallMe implements InterestingEvent
{
private EventNotifier en;
public CallMe ()
{
en = new EventNotifier (this);
}
public void interestingEvent ()
{
// Wow! Something really interesting must have occurred!
// Do something...
}
}
EDIT: please see the comments in the approved answer... ---this--- link was very helpful for me =)
There is no main method or static blocks. Nothing is actually run from the code you posted; hence, doWork() is never called. I read the article and looked at the code, and it appears to be incomplete, or perhaps some code is left out because the author felt that it didn't need to be explained.
Here's the gist:
We have an interface InterestingEvent, a class EventNotifier, and another class CallMe, which implements InterestingEvent.
EventNotifier takes an InterestingEvent in its constructor, and sets somethingHappened to false.
The constructor for CallMe initializes its EventNotifier instance member by passing the EventNotifier constructor a reference to the CallMe object, itself.
The following is not in the code, but if we detect that some particular action takes place, we set somethingHappened = true. So after that, if doWork() is called for an EventNotifier, interestingEvent() will be called on that EventNotifier's InterestingEvent ie. We can do this, since CallMe implements InterestingEvent.
NB: This article was from 1996 and much has changed since then. You mentioned how to detect mouse click events, but this is different. The point of the article, I assume, was to show how you can use objects in conjunction with interfaces and booleans to see if something occurred.
To actually detect a mouse click, take a look at this tutorial. Here's another tutorial on Writing Event Listeners. Finally, since you asked about threading in a comment, here's a great book: Java Concurrency in Practice.
The way that I typically use callbacks is with PropertyChangeListeners/PropertyChangeSupport classes. There is probably of lot of different explanations about those classes that you might find helpful.
Anyway, to the point of your question.
First, you need to understand that the two classes you have are normally running on different threads. What the callback does is allow you to get an asynchronous notification that something has happened on the other thread. This allows the notified thread to do its part when it regains control. For example, you have a serial line that is receiving data. The InterestingEvent would be something like 10 characters have arrived on this line. Now, instead of having just one EventNotifier, you'd have one for each serial line coming in. The CallMe instance would be running doing something, periodically checking to see if interestingEvent had been called. interestingEvent would set some sort of flag so that CallMe would know that it had new data to process. When CallMe sees that, it takes care of whatever the interestingEvent was and then goes back to its normal activity.
The whole point of the interface is to have a well-defined way to access an instance of CallMe. If you develop this more, you are probably going to want to manage the other instances that are accessing your instance of CallMe. That's where reading up on the PropertyChange stuff that I mentioned earlier would be really helpful.
Related
I need to monitor for an error that is occurring in a particular method in a Java class that cannot be changed because it is owned by a third party.
This method gets invoked by a particular feature within the system that will end up causing several hoops to be jumped in order to fix it (because only
a generic error is written to the UI and logs - we will pursue getting the owner of the class (an external vendor) to fix it, but it will likely take while).
As a workaround, I have de-compiled the class and added logger statements that print the data elements that are causing the issue. This can be run
externally and only when granted permission to do so, and cannot be put in the Production environment (because of contract and other issues).
Is it possible to "listen" for this method being called without actually editing the original class? Or is there some other suitable workaround I am not thinking of?
EDIT
I agree with Paul Boddington that this might be an XY problem. You can use one of the solutions below, but perhaps you have a different problem than you describe. You might want to reconsider the thing you actually want to achieve.
You have several options:
You can subclass class 'A', and then when the event occurs, notify registered listeners, like this:
public class SubA extends A {
private AListener listener;
public void method1() {
if (this.listener != null) {
this.listener.notifyMethodCall();
}
super.method1();
}
public void setAListener(AListener listener) {
this.listener = listener;
}
}
And the AListener interface:
public interface AListener {
void notifyMethodCall();
}
Class B:
public class B implements AListener {
public B(A a) {
a.setAListener(this);
}
public void notifyMethodCall() {
// Do whatever you want.
}
}
If the method call A.method1() changes an attribute of itself, you could check its value interval-based, for example, each second check its value, but that's generally bad in this context.
It can be that class A cannot be overridden because it is a final class, but that's generally considered as a bad design. The String class is, however, an exception.
Yes, I believe you can also do it with an AOP listener. You can define advice before an event happens, during, or after.
Does the this reference escape during construction problem (as called by Brian Goetz and others in Java Concurrency in Practice) affect single-threaded programs or just multi-threaded programs? I mean, is it OK to let the this reference escape during construction if my classes aren't supposed to be thread-safe anyway?
EDIT: For example, here:
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
EDIT2: The motivation for my question is that the plugin WindowBuilder for Eclipse creates (or seems to create...) the action listeners in a JFrame's constructor and by default passing anonymous classes to those, thereby allowing the this reference to escape...
Generally speaking you shouldn't try to use your object until it is fully constructed. If you pass the object to some other code before it has been fully initialised this can lead to confusing results, unless you are very careful. Even in single threaded programs.
That said, sometimes it is not a problem esp if you know the object will not be used until later.
Allowing the "this" reference to escape isn't necessarily going to cause problems. It can work out okay, but it's completely dependent on what the other code does with it.
So why is it a best practice to not leak this in the constructor? What if EventSource were to send a "now connected" event immediately from within the register function. What happens? doSomething() gets called (and mind you, you're still mid-constructor and may not be done initializing the object). It entirely depends on what the method does, but one of the following is true:
everything you need in doSomething is initialized before the listener is registered, and things work out.
something is null, and you ignore it, leading to unexpected results
something blows up as a result of something being null when it shouldn't be (NPE or similar).
But, you say, it doesn't send that event. So you're okay, right? Well, until someone else changes it, and it starts sending something like that, and then you spontaneously break without a direct change to your code.
Short form: avoid doing that if you can; it can cause headaches. If you absolutely must for some reason, take care that you initialize everything that you can before leaking it, and take great care to understand what's going to happen, and realize that there's potential for future trouble.
Don't do it. Letting a reference escape before construction can cause unspecified behavior. Use the static factory pattern and let your worries rest, multiple threads or not
In your example it would look like this:
public class ThisEscape{
private final EventListener listener;
private ThisEscape(){
listener = new EventListener();
}
public static public ThisEscape makeEscape(EventSource source){
ThisEscape e = new ThisEscape();
source.registerListener(e.listener);
return e;
}
private class EventListener{
public void onEvent(Event e){
doSomething(e);
}
}
}
Obviously the static factory doesn't allow for seamless class extension, but in my experience this is not generally a problem, even if a few factory methods need to be made.
This code would be thread safe in regards to construction; be sure to mind that the rest of your class is thread safe.
public class A
{
public void doSomething()
{ /*code*/}
}
The doSomething method is in no way referencing the state of object A so by that logic it could be static.
What is the difference between option 1 and 2:
new A().doSomething()
Assuming doSomething is static; A.doSomething()
I want to say that option 2 is better because the first would be creating a new object everytime it is used.
Option 1 creates a new instance of A in order to call the method doSomething() which according to your question it sounds like it doesn't need to (there is nothing in doSomething() that requires an instance of A). Option 2 skips the unneeded instance creation while producing the same effect, so it would be better (assuming that this is the only design requirement). Now there might be other reasons to not use static, for instance, if A implemented in interface, or if the nature of doSomething could conceivably change at some point in the future where it might need information established outside of it.
You're entering into the "expression" part of programming. What do you want to express?
Three cases are under discussion:
your method is an action any A can take, or a message any given A can respond to,
your method is an action the class of A's should respond to, and
A is a singleton, and your method receives messages for that singleton.
Now ask yourself: what do you intend to express? Is "doSomething" appropriate for the class A? Or is it, rather, just something that every instance of A should be able to do, regardless of its internals? Does "A" represent something which, in the world of your program, should only have 1 instance?
As a practical point, you can't overload static methods, so aside from "expression of intent", you need to be aware of that.
A lot of basic utilities fall in the "static" category, and there's a (small) time penalty for creating a new instance of A, but overall--you're most likely to get it right, and more importantly, the later life of that method will have the least impact on other code, if you can answer the questions above correctly, and thus pick the implementation that matches the intent of the object most closely.
There is a third option.
Create one instance of A, then reuse it for each call.
e.g., in the class or Application that is using A,
A myA = new A(); // you can consider making this static if that makes sense...
...
then, as needed later on
...
myA.soSomething();
The advantage is that, in the future, if you do need to change the behavior of doSomething, you could change the first line to
A myA = new SubclassOfAThatDoesSomethingDifferent();
Or, if doSomething() eventually does need to reference the state of A, it can.
You'd have to declare the method as static:
public class A {
public static void doSomething() {
// code
}
}
This allows you to do A.doSomething() and also prevents doSomething() from looking at any instance methods or fields (because how would you know which A instance to use?), which shouldn't be a problem if it doesn't reference them anyway.
See The Java Tutorial's Article on Instance and Class Methods for details.
I've been attempting to resolve my problem for about a day now, but can't seem to get anywhere. The problem:
I have a java class, ExternalClass which has 30 methods in it.
I also have an interface ExternalClassFacade.
public class ExternalClass {
public method1() {...}
public method2() {...}
...
...
public metod30(...) {...}
}
This class is an external library and I cannot modify it's code.
The class works well but I have a situation where I need to group up multiple calls on an undefined timespan to all 30 methods, delay the execution, and execute all at once (serial or parallel I don't care) at some moment.
For example, over 10 minutes, methods 1 to 30 will be called randomly 500 times, I want them to do nothing at the moment of being invoked, but after 10 minutes I want to invoke all 500 calls as they were originally called.
most of the methods require parameters which I need to remember for the moment in which i will call the methods.
I'm looking for a way to extend/wrap/composite this class, so that when someone calls any of these methods, or, a special method that will bridge the calls to the original methods so that they will be delayed till the right moment comes.
I was thinking about extending the class and overriding all methods, and managing 30 Struct-Like classes to hold the info about the calls, but that would require :
30 overrides
30 lists
30 classes
Lots of code, not very smart.
I'm looking for a better way to do this, I was thinking about catching the calls and keeping the pointer to the original method call, but this is java, so it's not possible.
Very interesting problem indeed. First question: does ExternalClass implement some interface? If it does, it simplifies stuff a lot, however if it doesn't, you can create one:
interface ExternalClassFacade {
method1();
method2();
//...
method30();
}
Don't worry, you don't have to implement it! Just copy all the method signatures from the ExternalClass. Do you know java.lang.Proxy? Wonderful tool in such problems like yours:
ExternalClass ext = //obtain target ExternalClass somehow
ExternalClassFacade extFacade = (ExternalClassFacade) Proxy.newProxyInstance(
ExternalClass.class.getClassLoader(),
new Class<?>[]{ExternalClassFacade.class},
new BatchInvocationHandler(ext));
extFacade.method1();
As you can see this magic and obscure code created something that implements ExternalClassFacade and allows you to run the same methods as ExternalClass. Here is the missing puzzle:
public class BatchInvocationHandler implements InvocationHandler {
private final ExternalClass ext;
public BatchInvocationHandler(ExternalClass ext) {
this.ext = ext;
}
#Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
return MethodUtils.invokeMethod(ext, method.getName(), args);
}
}
This code itself is not doing anything useful - when you call a method on the ExternalClassFacade it forwards the call to the same named method on ExternalClass with the same arguments. So we haven't achieved anything yet. BTW I am using MethodUtils from Apache Commons Lang to simplify the reflection code a bit. Chances are you already have this library on the CLASSPATH, if not, it is just few lines of extra code.
Now look at this improved version:
private static class BatchInvocationHandler implements InvocationHandler {
private final ExternalClass ext;
private Queue<Callable<Object>> delayedInvocations = new ConcurrentLinkedQueue<Callable<Object>>();
public BatchInvocationHandler(ExternalClass ext) {
this.ext = ext;
}
#Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
delayedInvocations.add(new Callable<Object>() {
#Override
public Object call() throws Exception {
return MethodUtils.invokeMethod(ext, method.getName(), args);
}
});
return null;
}
}
Now we are getting somewhere: instead of calling the method we are wrapping the call inside Callable and adding it to a delayedInvocations queue. Of course since we are no longer calling the actual method, the return value is just a placeholder. If ExternalClass methods have return types different than void, you must be very careful.
I think you see the light now. Everything you need is to create a thread that will take all the Callables collected in the queue and run them in batch. You can do it in various ways, but the basic building blocks are there. Also you might choose data structure like map or set rather than a queue. I can for instance imagine grouping methods by name for some reason.
Of course if you can use AspectJ/Spring AOP you will avoid the whole proxy infrastructure code. But the basic idea will be the same only that the API will be more pleasent.
Using AspectJ, you could introduce an interface to the class, then code to the interface. After that, you're free to add whatever behavior behind the interface that you want. Alternately, just use AspectJ to weave in the collecting/executing behavior you're looking for.
Cglib or Javassist would also let you do it more cleanly by letting you basically proxy the class by dynamic subclassing (assuming it's not final).
There are plenty of options. Those are three third-party ones that occurred to me. An advantage of some of these approaches is that they'll give you some representation of a method invocation in object form, which you can easily collect and run at a later time.
You could use an aspect to intercept all calls to execute external lib methods and to pause the Thread, writing the Thread's ID to a synchronized Set. That Set is in a singleton being watched by another Thread.
When your business rule to execute is fired, have the singleton watcher iterate the Set and notify each thread to continue processing. The aspect will continue on and execute each originally requested external method.
I new to java so bear with me if this is a ridiculously simple question but I am curious about this method call which has {code} being taken in - see code below for an example in the method addSelectionListener. What is the purpose of this? I have been looking through docs for an explaination but cant seem to find what this practice is called never mind any useful information.
setStatusLine.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String message = "I would like to say hello to you.";
if (pressed) {
message = "Thank you for using me";
}
setStatusLine(message);
pressed = !pressed;
}
});
Thanks for any help or insights that can be offered
this is an Anonymous Class, or Anonymous inner class. If you google for that you will find some tutorials/examples. Sun has some docs too.
As the other contributors already said: It is an Anonymous Class
You could have created a new class named MyClass in a new file called McClass.java looking like that:
class MyClass extends SelectionAdapter {
public void widgetSelected(SelectionEvent e) {
<your code that's being executed whenever the widget is being selected>
}
}
Then you could have changed the first line like that:
setStatusLine.addSelectionListener(new MyClass());
See? Now you have an "explicit" class with just one function. Often that is too much overhead and would clutter your design.
Does that help?
The method addSelectionListener receives a SelectionListener instance. It doesn't receive "code". The confusing thing is the use of new <class/interface name>(){...}. This construct is used for anonymous inner classes. In fact what the code above does is extending the SelectionAdapter class, overriding its widgetSelected method, creating an instance of the new class and passing it to addSelectionListener().
Usage of anonymous inner classes is common with listeners, where we create a new class, to be used in one specific place. Therefore we don't give it a name, and we prefer implementing it directly in the context where it is being used.
There is not a method call in fact...
This code set a selection listener on the setStatusLine component.
An equivalent of this code could be
public class X implements SelectionListener{
//In the constructor or an other method.
setStatusLine.addSelectionListener(this);
public void widgetSelected(SelectionEvent e) {
String message = "I would like to say hello to you.";
if (pressed) {
message = "Thank you for using me";
}
setStatusLine(message);
pressed = !pressed;
}
}
It took me some time to understand Anonymous Inner classes. The basic things to remember are:
They are just like parameters, except instead of passing in an primitive or Object you pass in a class that implements an Interface/extends a class (yes they also work with interfaces) depending on method parameter.
They are anonymous, so "disappear" right after the method has popped off the stack.
}); is a dead give-away for an anonymous inner class.
They often pop-up in user interfaces for listener events
They save clutter in your code, but also make it harder to read.
For full punishment read the JLS: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.9.5
If you are interested in knowing the nitty gritty about such things, reading the SCJP book and doing the exam is good or you can study the JLS. It won't learn you how to code, but it will help you understand how Java, and in some way, many other OO languages work.