Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rob's comment got me thinking about a possible alternative solution. You can utilize an ExecutorService in which a start would submit to said service. When the runnable completes and pause or stop were not selected then the callable will re submit itself to the service. So you will now effectively have only a pre determined number of threads running with sequential consistency amongst work execution.</p> <p>A lot of the code is still the same just underlying execution would differ.</p> <pre><code>public class MedicalDeviceWorkManager { private ConcurrentHashMap&lt;String, DelegatedWorker &gt; devices = new ConcurrentHashMap&lt;...&gt;(); private final ExecutorService worker = Executors.newFixedThreadPool(10); public void registerDevice(String device, Runnable singleUnitOfWork){ devices.put(device,new DelegatedWorker (singleUnitOfWork)); } public void startDevice(String device){ devices.get(device).startDevice(); } public void stopDevice(String device){ devices.remove(device).stopDevice(); } public void pauseDevice(String device){ devices.get(device).pauseDevice(); } private class DelegatedWorker { private final Runnable r; private volatile Future&lt;?&gt; running; DelegatedWorker (Runnable r) {this.r =r ;} public void startDevice(){ if(running != null){ running = worker.submit(new Callable&lt;Object&gt;(){ public Object call(){ if(Thread.interrupted())return null; r.run(); if(Thread.interrupted())return null; return worker.submit(this); } }); } } public void stopDevice(){ pauseDevice(); } public void pauseDevice(){ if(running!=null){ running.cancel(true); running = null; } } } } </code></pre> <p>Keep in mind here, instead of a volatile Future, you may want one which you lock around because of the compound function included in <code>pauseDevice()</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload