?
Solved

callback method and threads

Posted on 2003-02-26
14
Medium Priority
?
345 Views
Last Modified: 2013-11-23
With reference to Java can someone please provide some good rersources to an explanation of callback methods with examples of how to implement them in Java?

From what I know they are a better way to implement something than have a thread that continuously polls a method to check weather something has changed rather than a method calling back to say this has changed.
0
Comment
Question by:matjc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 3
  • +1
14 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8027107
You should use Obersver and Observable. Check out http://javaalmanac.com/egs/java.util/Obs.html
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 8028367
The approach CEHJ is suggesting is very common, and I have used it myself on several occasions.

Here is a simpler approach that might work for you;

// file: ThreadCallback.java

public interface ThreadCallback
{
   public boolean somethingHasChanged();
}

// file: MyThreadThatCallsBack.java

public class MyThreadThatCallsBack
extends Thread
{
   ThreadCallback callBackReceiver;

   public MyThreadThatCallsBack(ThreadCallback callBackReceiver)
   {
      this.callBackReceiver = callBackReceiver;
   }

   public void run()
   {
      boolean done = false;
      do
      {
         done = callBackReceiver.somethingHasChanged();
         if(!done)
         {
            // do some more work
         }
      } while(!done);
   }
}

// file: MyClassThatReceivesCallBacks.java

public class MyClassThatReceivesCallBacks
implements ThreadCallback
{
   public boolean somethingHasChanged()
   {
      // return if something has changed so that the thread should exit
   }
}

Good luck!
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:matjc
ID: 8093851
An outline to what I am trying to do and then some code ..

Explanation: I want to monitor a queue of objects, when something is added to the queue then I want to do some work on the object that is added then notify an object that there is a change in the queue. At the moment I am merely trying to get the callback stuff working. I am currently using the javaworld article above as a starting point but have not programmed with interface much .. so some help with the following would be useful..

//file: NetInterface.java
public interface NetInterface {

    public void interestingEvent();    
}

//file: EventNotifier.java
import java.util.*;

public class EventNotifier {

    static private NetInterface ie;

    static private boolean somethingHappened;
   
     public EventNotifier (NetInterface event) {

          ie = event;

          somethingHappened = false;
     }

    public static void doWork () {
          //check to see if something has hapenned
          if (somethingHappened) {
              // Signal the event by invoking the interface's method.
               //??
              ie.interestingEvent ();
         }
     }
     
     public static void main(String args[]) {
          HashMap newMap = new HashMap(5);
         
          int i = 0;
         
          while (i<0) {
               newMap.put((Integer.toString(i)), new String("hello "+i));
               i++;
          }
          somethingHappened = true;
          doWork();    
     }
}



//file: CallMe.java
public class CallMe implements NetInterface {

    private EventNotifier en;
   
     public CallMe () {

          // Create the event notifier and pass ourself to it
          en = new EventNotifier (this);
     }
    // Define the actual handler for the event.

    public void interestingEvent () {
          // Wow!  Something really interesting must have occurred!
          // Do something...
          System.out.println("oh something interesting has happened!");
     }
}
0
 
LVL 35

Expert Comment

by:girionis
ID: 8094484
 What exactly is the problem?
0
 

Author Comment

by:matjc
ID: 8094510
the above does not work. when it runs it returns null pointer exception ..

Exception in thread "main" java.lang.NullPointerException
     at EventNotifier.doWork(EventNotifier.java:22)
     at EventNotifier.main(EventNotifier.java:36)
0
 
LVL 35

Expert Comment

by:girionis
ID: 8094535
 Which one is the line 22 of the EventNotifier? This line is null and thus the programme fails.
0
 

Author Comment

by:matjc
ID: 8094562
public static void doWork () {
     //check to see if something has hapenned
     if (somethingHappened) {
         // Signal the event by invoking the interface's method.
         //??
         ie.interestingEvent ();
}

line 22 is actually the closing brace; so I pressume that ie.interestingEvent is null .. what do I need to do? How should this work?
0
 
LVL 35

Expert Comment

by:girionis
ID: 8094591
 Are you sure you have initialized properly the "ie" variable? It seems to me it's still null.
0
 

Author Comment

by:matjc
ID: 8094610
girionis, I have posted the code and asked the question what do _I_ need to do to make it work?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 210 total points
ID: 8094614
Your code doesn't seem to be heading in the right direction to me. Whay you need to be doing is something more like:

1. queue(x) is called
2. inside the method queue you should be calling
process(x)
3. add x to the queue, i.e. enqueue x
4. before exiting from queue, call notifyObservers(x);
5. return from enqueue

notifyObservers(x) would be called on a reference to whatever you'd decided to make your Observable and the objects that are implmenenting Observer would receive a reference (optional) to what had just been enqueued
0
 
LVL 35

Expert Comment

by:girionis
ID: 8094624
 Ok... I have to go to some birthday in 5 mins. I will look at it later on tonight (or tomorrow morning) and I will let you know, if nobody else does meanwhile.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8094629
As you can see, Threads are irrelevant. This functionality is all performed within the same thread. Indeed you don't want asynchronicity here.
0
 

Author Comment

by:matjc
ID: 8107664
Ok I am making v slow progress at the moment, and would like to try and finish this asap. CEHJ I think the following follows on from the help you have provided.

A couple of questions regarding the following .. If I want to make a callback to Left from a different class that would call Right from how would I do this? what call would I make to Right ?

the following process might explain this better:

PressButton ---> right.makeCall() --- > Interface ---> left_is_notified. ----> left do stuff.


//File: CallBack.java

public interface CallBack {
     public void qchange();
}

//File: Left.java

public class Left {
     CallBack c;
     
     public Left(CallBack ca) {
          this.c = ca;
     }
     
     public void go() {
          c.qchange();
     }
}

//File: Right.java

public class Right implements CallBack {
     
     public static void main(String args[]){
          new Right();
     }
     
     public Right() {
          Left l = new Left(this);
         
          l.go();
     }
     
     public void qchange() {
          System.out.println("in Right callback made");
     }
     
}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question