java - Double-Checked Locking without creating objects -


i'm using double-checked locking (dcl) avoid need of synchronization on object if not needed so. in case need synchronize when buffer empty, have "processing thread" wait "delivery thread" notify again - otherwise, "processing thread" run in loops without doing useful.

both threads share these objects:

object bufferlock = new object(); queue<command> commands = new concurrentlinkedqueue<>(); // thread safe! 

thread 1 ("delivery thread" - fills buffer):

while (true)     command command = readcommand();     commands.add(command);     synchronize (bufferlock){         bufferlock.notify(); // wake thread 2 (if waiting)     } } 

thread 2 ("processing thread" - empties buffer):

while (true){     if (commands.peek() == null){ // not creating here         synchronized (bufferlock){             if (commands.peek() == null){ // not creating                 bufferlock.wait();             }         }     }     command command = commands.poll();     processcommand(command); } 

now, netbeans showing warning dcl, made me dig subject deeper because concept of dcl unknown me - started use on own.

as far understand reading several articles on internet, there java bug when using pattern, examples use in combination lazy loading. in these examples, objects created within synchronized block. in synchronized code, not create objects.

is code unsafe? netbeans correct in showing warning? note netbeans had bug related dcl before, i'm confused.

the pattern (or rather, anti-pattern!) have created not strictly constitute double checked locking, refers case object reference starts off null instantiated first thread needs reference it, synchronization after null check. java 5, couldn't strictly speaking implement correctly in java (though because of how jvms implemented, accidentally away it). of java 5, can use it, it's pointless. (you may interested in article on double-checked locking in java wrote while ago looks @ issue in more detail. class-loader has built-in synchronisation rare cases need dcl.)

now, that's kind of by. have here isn't dcl strictly-speaking.

the problem have you're trying mix paradigms. raison d'ĂȘtre of java concurrency library avoid low-level locking synchronized , wait/notify. should use flavour of blockingqueue , use built-in blocking behaviour. again, among other examples might refer material have written on blocking queues.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -