java - Multi producer single consumer queue without dedicated consumer thread -
i'm writing async application submits elements work queue processing. requirements are:
- there no background thread listening on queue. thread submits element queue may responsible consuming queue.
- there can multiple concurrent producers, 1 thread can active consumer.
- if thread submits element thread b actively consuming queue, thread should return immediately. no waiting allowed.
here example of i'm trying do:
final queue<t> queue = new concurrentlinkedqueue<>(); final atomicboolean processing = new atomicboolean(); void offer(t t) { queue.offer(t); (;;) { if (processing.compareandset(false, true)) { try { (;;) { t t = queue.poll(); if (t == null) { break; } // process t } } { processing.set(false); } // see if thread submitted element didn't process // if not, can break if (queue.isempty()) { break; } } else { // losers should exit break; } } }
i think code works, problem sounds standard know if there textbook solution or @ least common name. far find algorithms require worker thread listening on queue.
your code correct, problem not seen standard: usually, having background thread not expensive, as:
having no finite time garantee producers. possible producer work long time in consumer mode.
complicate producer's code.
in case, question's title (mpsc without dedicated consumer thread
) describes problem well. resolve can combine trylock/unlock
approach mpsc implementation without notification mechanism. additional requirement mpsc concurrent queue.isempty()
method, not problem.
Comments
Post a Comment