java - How to throttle tasks such that only one runs at a time and rest are ignored -


i have object listens external events. upon receiving event, object needs execute task (a runnable). however, there restriction:

once task starts executing, should not start other tasks (i can ignore them) until original task finished , amount of time passed after (throttling).

here's suggested implementation using semaphore:

public class sample {      private final semaphore semaphore = new semaphore(1);      private final scheduledexecutorservice executor;      public sample(scheduledexecutorservice executor) {         this.executor = executor;         }      public void tryrun() {         if (semaphore.tryacquire()) {             try {                 executor.submit(                     new runnable() {                         @override                         public void run() {                             try {                                 doit();                             } {                                 try {                                     executor.schedule(                                         new runnable() {                                             @override                                             public void run() {                                                 semaphore.release();                                             }                                         },                                         1,                                          timeunit.minutes                                     );                                 } catch (throwable t) {                                     semaphore.release();                                 }                             }                         }                     }                 );             } catch (throwable t) {                 semaphore.release();                         }         }     }      private void doit() {         // exact task executing logic here     } } 

the code seems verbose me. there better way of doing this?

p.s. restriction scheduledexecutorservice interface have external executor , cannot start own threads/executors within object

just use threadpoolexecutor single thread. you'll have decide whether it's okay queue lot of other tasks. if not, pass own blockingqueue capacity 1, believe let @ 1 task queue up. i'm thinking how down zero.

one way create single threaded executor unbounded queue.

note need configure tpe discard rejected tasks via discardpolicy.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -