java - Is there better way to use wait/notify with connection with AtomicInteger -
i've kind of code:
public class recursivequeue { //@inject private queueservice queueservice; public static void main(string[] args) { recursivequeue test = new recursivequeue(); test.enqueue(new node("x"), true); test.enqueue(new node("y"), false); test.enqueue(new node("z"), false); } private void enqueue(final node node, final boolean waittillfinished) { final atomiclong totalduration = new atomiclong(0l); final atomicinteger counter = new atomicinteger(0); aftercallback callback= new aftercallback() { @override public void onfinish(result result) { for(node anode : result.getchildren()) { counter.incrementandget(); queueservice.requestprocess(anode, this); } totalduration.addandget(result.getduration()); if(counter.decrementandget() <= 0) { //last 1 system.out.println("processing of " + node.tostring() + " has finished in " + totalduration.get() + " ms"); if(waittillfinished) { counter.notify(); } } } }; counter.incrementandget(); queueservice.requestprocess(node, callback); if(waittillfinished) { try { counter.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } } } imagine there queueservice uses blocking queue , few consumer threads process nodes = calls dao fetch children of nodes (it's tree). requestprocess method enqueues node , not block.
is there better/safe way avoid using wait/notify in sample ? according findings can use phaser (but work on java 6) or conditions (but i'm not using locks).
there no
synchronizedin example. mustn't callo.wait()oro.notify()except withinsynchronized(o) {...}block.your call
wait()not in loop. may not ever happen in jvm, language spec permitswait()return prematurely (that's known spurious wakeup) more generally, practice use loop because it's familiar design pattern.whilestatement costs no moreif, , should have because of possibility of spurious wakeup, , you'd absolutely must have in multi-consumer situation, , might write way.since must use
synchronizedblocks in order usewait(),notify(), there no reason useatomicanything.this "recursive" thing seems awfully complicated, callback adding more items queue. how deep can go?
Comments
Post a Comment