"Klemme, Robert, myview" wrote:
>
> hi all!
>
> > -----Original Message-----
> > From: Luc Vanlerberghe [mailto:[EMAIL PROTECTED]]
> > Sent: Friday, January 26, 2001 6:14 PM
> > To: [EMAIL PROTECTED]
> > Subject: Re: Thread-safety
> >
> >
> > > Does this mean that the following code would be thread safe?
> > NO, it's not!
>
> sorry to intervene here. i think you are wrong. look at it again:
>
> > [...]
> > > Does this mean that the following code would be thread safe?
> > >
> > > if (_jspx_inited == false) {
> > > synchronized (this) {
> > > if (_jspx_inited == false) {
> > > synchronized(new Object()) {_jspx_init();}
> > > _jspx_inited = true;
> > > }
> > > }
> > > }
>
> this double check is a usual technique to improve performance. the inner
> check is necessary for proper operation. the outer check improves
> performance since it does not require a lock on the object to be acquired
> which is relatively costly.
The problem is that the point of the code block is to be
sure that the _jspx_init() method has been completed before
proceeding. The problem is that _jspx_inited might appear to other
threads to be set to true before the original thread has completed
executing the _jspx_init() method (or at least before its changes
are available to other threads).
This means that the second thread would come through, see
that _jspx_inited is true, and skip the synchronization block. That
threads execution would then proceed thinking that everything has
been initialized when it hasn't.
>
> and, btw. why did they not code this:
>
> if ( ! _jspx_inited ) {
> synchronized (this) {
> if ( ! _jspx_inited ) {
> // other initialization stuff
> _jspx_inited = true;
> }
> }
> }
>
> i think it is quite superfluous to compare a boolean with true or false
> (apart from the fact that in other programming languages this might even be
> dangerous, just think of C...)
>
Check out the article that is referenced in other mail in
this thread or hit JavaWorld and see the references section on the
article about singletons.
-Paul Speed
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, email: [EMAIL PROTECTED]