python dude
python dude

Reputation: 8358

Event delay in Java program

In my Java program, I have a text component that can fire events in rapid succession. Since I'm doing a lot of background processing whenever the text is modified, this can noticeably decrease the responsiveness of the text component. That's why I'd like to introduce a delay: When the text component starts firing, the attached listener should wait for a certain amount of time (e.g. 1 second) until the text component has "calmed down", and then start its own processing.

I know that it's relatively easy to roll my own simple delay mechanism that does what I want, but I'm wondering if the java.util.concurrent package (or some other system package) has a ready-made solution for this. I've been looking into

Executors.newScheduledThreadPool(int)

but this doesn't seem to be what I'm looking for, since this will fire all incoming events - I only want exactly one event to make it through to the listener after the delay.

Thanks in advance.

Upvotes: 1

Views: 558

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137577

You're very close to the solution.

What you want is to schedule a firing of the listener to happen one second in the future, but to cancel that when the next event arrives (if it hasn't already happened) and reschedule. Using an executor is reasonable, but the key is that you need to keep around the Future object that scheduling returns, as it is that which you cancel.

Upvotes: 1

Related Questions