Saturday, 15 January 2011

java - Is it necessary to make this variable volatile? -


I was going through a "JAX London 2011" time period between 43:20 - 43:40, the audience One person says that the shutdown variable in the code below should have been declared as the volatile and the presenter agrees (and says that it is As previously mentioned, they do not modify the presentation). The code in question is:

  Queue Reader Task executes the public abstract class Runnabel {Private Boolean lock = false; Protected block queue & lt; WorkUnit & lt; String & gt; & Gt; Lbq; Public run zero () (while (closed!) {Try {WorkUnit & lt; string> gt; Wu = lbq.poll (10, tymunit milliseconds); If (wu! = Null) {doAction (wu.getWork () );}} Grip (Interrupted Exception E) {shutdown = true;}}} Public Task Zero Work (String msg); Public Zero Set Quyu (Interrupt QUUT & Lt; WorkUnitText; String & gt; & gt; Q) {LBC = q;}}   

My question: I do not think that shutdown should be declared unstable . My argument is that being a member of shutdown a runner, , every work / thread will be a unique personal copy of that variable, then it will be variable Why do you make it?

But since this was discussed in Jade 2011, I am convinced that many of the viewers of that audience were Java developers, I do not think that all of them would remember this ! So, what am I missing?

PS: - I can understand that a variable Should be declared unstable , if it was shared by multilevel thread, such as double-check-locking pattern:

  class Foo {personal volatile helper assistant = Zero; Public Helper getHelper (if {Helpful == blank} {synchronize (this) {if (assistant == zero) helper = new helper (); }} Return Assistant; }}    

Each task / thread will be a specific private copy of that variable . So, why do they make 'unstable'?

If is off boolean has been modified from within only QueueReaderTask example In that case, shutdown is being modified by only one thread and there is no need to be instability .

Frankly, the code looks strange to me. Why take the interrupted steps , shut down set the boolean, and loop around it and why do you do the following now? Why the shutdown flag is at all?

  while (true) {try {workUnit & lt; String & gt; Wu = lbq.poll (10, tymunit milliseconds); If (wu! = Null) {doAction (wu.getWork ()); }} Grip (Interrupted E) E. {Thread. WrenchTrad () Interrupt (); Return; }}   

Perhaps there is additional code that was deleted in the post? If not, I wonder if it was pasted from a large part of a copy code, where a method was set to call shutdown correct too.

PS: - I can understand that a variable should be declared 'volatile' if it was shared by multilevel thread, such as in double-check-locking pattern:

right. A typical format is that shutdown has been modified from another thread which is asking the formula to stop processing. In that case it should be unstable .

No comments:

Post a Comment