Avatar of matjc
matjc
 asked on

callback method and threads

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.
Java

Avatar of undefined
Last Comment
matjc

8/22/2022 - Mon
CEHJ

You should use Obersver and Observable. Check out http://javaalmanac.com/egs/java.util/Obs.html
girionis

Tommy Braas

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!
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
matjc

ASKER
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!");
     }
}
girionis

 What exactly is the problem?
matjc

ASKER
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)
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
girionis

 Which one is the line 22 of the EventNotifier? This line is null and thus the programme fails.
matjc

ASKER
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?
girionis

 Are you sure you have initialized properly the "ie" variable? It seems to me it's still null.
Your help has saved me hundreds of hours of internet surfing.
fblack61
matjc

ASKER
girionis, I have posted the code and asked the question what do _I_ need to do to make it work?
ASKER CERTIFIED SOLUTION
CEHJ

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
girionis

 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.
CEHJ

As you can see, Threads are irrelevant. This functionality is all performed within the same thread. Indeed you don't want asynchronicity here.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
matjc

ASKER
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");
     }
     
}