java - Ignore threads if the pool is full -



java - Ignore threads if the pool is full -

i want accomplish next behaviour in java application:

when button clicked, task called in new thread. however, if button clicked 1 time again , current task still running, don't want run one.

i'm not sure what's approach this. i'm using code similar 1 below.

private executorservice backgroundtaskexecutor = executors.newsinglethreadexecutor(); private boolean runningbackgroundtask = false; private synchronized void setrunningbackgroundtask(boolean running) { this.runningbackgroundtask = running; } private synchronized boolean isrunningbackgroundtask() { homecoming runningbackgroundtask; } private void runbackgroundtask() { if (isrunningbackgroundtask()) { system.out.println("this task ignored because thread pool busy."); return; } runnable backgroundtask = new runnable() { @override public void run() { setrunningbackgroundtask(true); // takes time... setrunningbackgroundtask(false); } }; backgroundtaskexecutor.submit(backgroundtask); }

is practice? there utility in java doing this?

with current code end more 1 task in executor's queue @ time because check if task running @ start of method set true within runnable. possible phone call method twice before first line of runnable run , state set true.

to ensure not happen utilize atomicboolean , set state atomically.

private final atomicboolean runningbackgroundtask = new atomicboolean(false); private void runbackgroundtask() { if (runningbackgroundtask.getandset(true)) { system.out.println("this task ignored because thread pool busy."); return; } runnable backgroundtask = new runnable() { @override public void run() { // takes time... runningbackgroundtask.set(false); } }; backgroundtaskexecutor.submit(backgroundtask); }

java multithreading

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -