synchronized (this[.classinfo]) in druntime and phobos

Jonathan M Davis jmdavisProg at gmx.com
Mon May 28 16:24:00 PDT 2012


On Tuesday, May 29, 2012 01:11:49 Alex Rønne Petersen wrote:
> 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.

Per TDPL, having individually synchronized functions is illegal. Either all 
of the functions in a class are synchronized or none of them are. Putting 
synchronized on a function should actually be illegal. It belongs only on 
classes or in synchronized blocks, never on functions.

Now, unfortuntately, I don't believe that the compiler enforces any of that 
right now, so you end up synchronizing indivdual functions rather than whole 
classes, but the synchronized functions themselves should function the same.

> 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)

Well, then you should probably be arguing about the design of synchronized 
classes/functions rather than synchronized(this). However, given the design of 
synchronized classes, synchronized(this) would probably never be appropriate. 
If you're using a synchronized class, then you don't need it. And if you're 
not using a synchronized class, then you shouldn't be synchronizing your 
class. I would definitely think that synchronized blocks should synchronize on 
something else, since they're trying to lock a much smaller area than an 
entire class.

- Jonathan M Davis


More information about the Digitalmars-d mailing list