java - Wrapping ExecutorService to provide custom execution -
i want write reusable piece of code allow waiting conditions while submitting tasks executor service. there alot of implementaions neat ways of blocking if many tasks queue, e.g. here
i need executor evaluates waiting threads, every time on task finished. deciding if task allowed submitted atm, current state of active tasks must considered. came following solution, doesn't have scale multiple submitters or high grade of simultaneous executed tasks.
question: following code safe use, or there flaw i'm missing? person implementing aquireaccess
method of conditionevaluator<t>
must ensure way state of threads in queried thread safe, implementer needn't safeguard iteration on activetasks collection. here code:
public class blockingexecutor<t extends runnable> { private final executor executor; private final conditionevaluator<t> evaluator; final reentrantlock lock = new reentrantlock(); final condition condition = this.lock.newcondition(); final linkedlist<t> active = new linkedlist<t>(); private final long reevaluatetime; private final timeunit reevaluatetimeunit; public blockingexecutor(executor executor, conditionevaluator<t> evaluator) { this.evaluator = evaluator; this.executor = executor; this.reevaluatetimeunit = null; this.reevaluatetime = 0; } public blockingexecutor(executor executor, conditionevaluator<t> evaluator, long reevaluatetime, timeunit reevaluatetimeunit) { this.evaluator = evaluator; this.executor = executor; this.reevaluatetime = reevaluatetime; this.reevaluatetimeunit = reevaluatetimeunit; } public void submittask(final t task) throws interruptedexception { this.lock.lock(); try { do{ if (this.reevaluatetimeunit == null) { this.condition.await(this.reevaluatetime, this.reevaluatetimeunit); } else { this.condition.await(); } }while(!this.evaluator.aquireaccess(this.active, task)); this.active.add(task); this.executor.execute(new runnable() { @override public void run() { try { task.run(); } { blockingexecutor.this.lock.lock(); try{ blockingexecutor.this.active.remove(task); blockingexecutor.this.condition.signalall(); }finally{ blockingexecutor.this.lock.unlock(); } } } }); } { this.lock.unlock(); } } } public interface conditionevaluator<t extends runnable> { public boolean aquireaccess(collection<t> activelist,t task); }
question: can code improved?
Comments
Post a Comment