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 synchronized in example. mustn't call o.wait() or o.notify() except within synchronized(o) {...} block.

  • your call wait() not in loop. may not ever happen in jvm, language spec permits wait() return prematurely (that's known spurious wakeup) more generally, practice use loop because it's familiar design pattern. while statement costs no more if, , should have because of possibility of spurious wakeup, , you'd absolutely must have in multi-consumer situation, , might write way.

  • since must use synchronized blocks in order use wait() , notify(), there no reason use atomic anything.

  • this "recursive" thing seems awfully complicated, callback adding more items queue. how deep can go?


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -