Search code examples
javamultithreadingperformancequeuerunnable

Is there any way to have events with a variable in Java? Example inside


Say, I have a SystemQueue class that wraps a Queue object. I add to this queue using systemQueue.add(whatever), and I have a different object thats a Runnable that checks the queue, and if its not empty, takes from the queue and uses "whatever" in its code. Is there any way to do this besides having an infinite loop in the run like

    run(){
        while(true){
            if(!systemQueue.isEmpty()){
                  todo
             }
       }
   }

and have that run forever? What I'm asking is, how can I code using event-based-coding in java?

Is there any way I can add an eventListener to the queue inside SystemQueue, and if the queue changes, call out to SystemExecutor and have it run?


Solution

  • Queue itself doesn't provide that option. You can implement your own listener/event pair though.

    Event:

    public class SystemEvent extends java.util.EventObject{
        public SystemEvent(SystemQueue src){
            super(src);
        }
    
        public SystemQueue getSource(){
             return (SystemQueue) super.getSource();
        }
    }
    

    Listener:

    public interface SystemListener extends java.util.EventListener{
        public void eventQueued(SystemEvent e);
    }
    

    in SystemQueue:

    ArrayList<SystemListener> listeners = new ArrayList<>();
    
    protected void fireEventQueued(){
        SystemEvent e = new SystemEvent(this);
    
        listeners.forEach(l -> l.eventQueued(e));
    }
    
    public void addSystemListener(SystemListener l){
         listeners.add(l);
    }
    
    public void add(something){
        //add something
        fireEventQueued();
    }
    

    Now all you need to do is make SystemExecutor implement SystemListener and add the instance as listener.