Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement event listener in background of the main program in java?

Tags:

java

Hi im a beginner so sorry for my question if it sounds naive.

I want to implement a thread that runs in the background and listens all the time. By listening i mean, say it keeps check on a value returned from main thread and if the vaue exceeds certain figure, it executes some method, or say exits the program.

If you could give me some idea or at least refer me to something useful, that'll be great.

like image 280
Space Rocker Avatar asked Dec 23 '10 00:12

Space Rocker


3 Answers

You wouldn't want this thread to run in a loop, continuously polling the value, because that would waste processing.

Ideally, the listener would be actively notified when the value had changed. This would require that any code that modifies the monitored value call a special method. It might not be necessary for the listener to run in a separate thread; it would depend on what the listener does when it is notified.

If the code that modifies the value cannot be changed, then the best you can do is to check the value at intervals. You won't see a change immediately, and its possible that you could miss changes altogether because the value is changing multiple times during an interval.

Which of these solutions fits your situation the best?

like image 114
erickson Avatar answered Nov 01 '22 22:11

erickson


You can find some information on using threads in Java Tutorials (if you are new to concurrency in Java I recommend reading this tutorial first). Especially this section may be useful for you (it shows how to create and start a new thread).

like image 26
Piotr Avatar answered Nov 01 '22 22:11

Piotr


If you simply need to poll for a result from another thread try using java.util.concurrent package as suggested by @Piotr. Here's a concrete example how you might do this:

import java.util.concurrent.*;

class Main{
    public static void main(String[] args) throws Exception{
        //Create a service for executing tasks in a separate thread
        ExecutorService ex = Executors.newSingleThreadExecutor();
        //Submit a task with Integer return value to the service
        Future<Integer> otherThread = ex.submit(new Callable<Integer>(){
            public Integer call(){
                //do you main logic here
                return 999;//return the desired result
            }
        }

        //you can do other stuff here (the main thread)
        //independently of the main logic (in a separate thread)

        //This will poll for the result from the main
        //logic and put it into "result" when it's available
        Integer result = otherTread.get();

        //whatever you wanna do with your result
    }
}

Hope this helps.

like image 20
rodion Avatar answered Nov 01 '22 22:11

rodion