synchronized (this[.classinfo]) in druntime and phobos
Alex Rønne Petersen
alex at lycus.org
Mon May 28 16:11:49 PDT 2012
On 29-05-2012 00:42, Jonathan M Davis wrote:
> On Tuesday, May 29, 2012 00:36:13 Alex Rønne Petersen wrote:
>> Hi,
>>
>> I've seen several occurrences of synchronized (this) and synchronized
>> (this.classinfo) in both druntime and phobos by now. I propose that we
>> officially ban these patterns with extreme prejudice.
>>
>> 1) Locking on the object instance is a HORRIBLE IDEA. Anyone who happens
>> to use the object for locking will most likely end up with a deadlock on
>> their hands.
>> 2) Locking on something as fundamental as type info means that any
>> arbitrary part of the application could cause a deadlock by doing the same.
>>
>> The solution to (1) is to simply use a Mutex internally (or an Object
>> with synchronized statements), and for (2), to simply use private global
>> objects.
>>
>> (Now, regarding (1), you might argue that anyone who locks on an
>> arbitrary object is doing it wrong, but you can't really blame them -
>> it's frankly D's fault for allowing monitors on arbitrary objects, which
>> is a horrible mess.)
>>
>> Anyone against this?
>
> Don't synchronized classes synchronize on the object for all of their function
> calls? How is this any different?
>
> - Jonathan M Davis
I have no idea how synchronized classes work; they are not a documented
feature of the language. We have synchronized functions which
synchronize on the this reference. Perhaps synchronized classes just
make all functions in a class do this.
Either way, this is a fundamental language design fallacy. This is
anti-pattern number one when it comes to locking:
* http://stackoverflow.com/a/251668/438034
* http://msdn.microsoft.com/en-us/library/ms173179.aspx (The lock and
SyncLock Keywords section)
--
Alex Rønne Petersen
alex at lycus.org
http://lycus.org
More information about the Digitalmars-d
mailing list