jeudi 10 octobre 2019

How to avoid a busy while loop in event-driven Java

I am currently developing my event driven Java software in the following fashion (this is the essence of my main method):

while(true) {
    Event event = eventListener.poll();
    if(event != null) {
        // do something
    } else {
        // do nothing as usual, but burn CPU time.
    }
}

Depending on what I'm building, eventListener could be something that's listening to an external websocket, polling a Redis channel for updates, or waiting for a message from another process sitting on the same box (perhaps through UDP/TCP/shm).

My thinking is that this busy loop approach wastes a lot of CPU time when eventListener is returning null (which is most of the time), since it just sits there spinning. However, I don't know how else to approach this design, aside from putting a Thread.sleep each iteration which is not a great solution.

Ideally I would like to have a method:

void run(Event event) {
    // do something
}

where run is called any time an event hits eventListener. If no such event is available, the process should ideally just sitting there idling.

Now, I know there's websocket libraries that can actually do this, what I want to know is how can I build something like this for myself and liberate my CPU from sitting there wasting itself doing nothing?

Aucun commentaire:

Enregistrer un commentaire