[Mono-list] Class library developers: locking issues to keep in mind

Serge serge@wildwestsoftware.com
Mon, 29 Oct 2001 03:05:23 +0200


This is a multi-part message in MIME format.

------=_NextPart_000_0089_01C16026.8D156D60
Content-Type: text/plain;
	charset="ISO-8859-1"
Content-Transfer-Encoding: 7bit

> making reference volatile does not save you from the situation
> when the reference is OK, but the object it points to has not been
> completely initialized

That's right, it wont help. This is true for both UP and MP machines.
As long as constructor inlining is a valid optimization for JIT (and I
suppose it is).
I guess, it is possible to fix this by disabling inlining using
MethodImplAttribute:

   [MethodImplAttribute(MethodImplOptions.NoInlining)]
   private static MyObject Create () {
        return new MyObject ();
   }

then

 get {
    if (obj != null) return obj;
      lock (typeof (X)) {
         if (obj == null) obj = Create ();
         return obj;
      }
 }

This won't solve SMP issues though,
one way is to use Threading.Interlocked methods and have an additional int
to flag object initialization. Using TLS is another way (but I don't think
this is faster than mere synchronization).

However, I have an idea for DCL replacement.
Why not use function pointers (or delegates) to replace the original
(locked) initializer after its first execution with empty non-synched
method?
See attached sources (OneShot.il/cs) - IL code uses raw function pointers
and C# version uses delegates, but I think this should work for Java too
with two object references (for example two Runnable objects).
This pattern can be applied to both static and instance fields.

Have fun,
Sergey









------=_NextPart_000_0089_01C16026.8D156D60
Content-Type: application/x-gzip;
	name="one-shot.tar.gz"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename="one-shot.tar.gz"

H4sIAPS93DsADu1aXWwcVxU+s7Y3u5tumnWaxIGEXCdtWMfNeNe/1ImLGzttXOWv2TRNSdNkdvba
O/XszDIz68SJEkKFQhEF0iKVCqEKqj6AeKkQFRUSPPLUSpVAvBSkShTUNx6ABxBKOfdndmbX658U
7ECY48yd+3Puueeeuefc795NsWaYJbWoebB6RAgZGRoi7E2G+hvfjAbyw8gxMDySx6e/n5B8big/
DCS3ijrVqeZ6mkMIvqmzFF/JdtdCnbWmcaqXbWJPT6dTxjSxbI/QS4brkaJhkcpsyXBYDttMza2Q
vpJpkj675lVr3hjWP2Nb1C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