Proposals: Synchronization

Kent Boogaart kentcb at internode.on.net
Sat Jul 22 20:54:20 PDT 2006


Hi all,

I have some ideas regarding D's synchronization support that I'd like to put 
forward. Any input would be much appreciated.

1. Change the "synchronization" keyword to "lock".

Pros:
   - easier and quicker to type
   - no confusion over spelling (it is spelt "synchronisation" in Australia, 
UK et al)

Cons:
   - none that I can think of

As a Java programmer, it used to annoy me typing "synchronization" every 
time I needed a locking construct. As a C# programmer, I rejoiced in the 
terser "lock" keyword.

2. Don't permit arbitrary locking of objects.

It is well accepted amongst the Java and .NET communities that allowing 
locking of arbitrary objects is a bad thing. For example, this is considered 
bad practice:

public void myMethod()
{
    ...
    lock (this)
    {
        ...
    }
}

It is bad because any other code could lock the object refered to by this. 
That can result in deadlocks, race conditions and all sorts of weird 
behavior. The accepted practice is:

private object _lock = new object();

public void myMethod()
{
     ...
     lock (_lock)
     {
         ...
     }
}

That way only the owning class can lock on the object.

So my suggestion is to disallow locking on arbitrary objects and change the 
lock keyword to only allow locking on a Phobos-provided Lock class like 
this:

private Lock _lock = new Lock(); //the Lock class or struct is implemented 
in Phobos

public void myMethod()
{
    lock (_lock)  //OK
    {
    }

     lock (this) {} //compile error

     lock (new object()) {} //compile error
}

I would also suggest NOT allowing this syntax:

public lock(_lock) void myMethod()
{
}

Because it is ugly and synchronization is an implementation detail that 
should be kept out of the method signature.

Pros:
   - the synch block can be removed from every object stored on the gc heap 
(that's a saving of at least 4 bytes per gc object - that's huge for 
applications that allocate a lot of small objects)
   - programmers are forced to lock in a safer manner. The problems of Java 
/ .NET locking on arbitrary objects are avoided.
   - D will be able to provide better diagnostics of locks as a program runs 
and during debug sessions. Locks could be named, for example

Cons:
   - none that I can think of

Love to hear what others think,
Kent Boogaart 





More information about the Digitalmars-d mailing list