Synchronized classes have no public members

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Oct 15 10:10:23 PDT 2015


On 10/15/15 11:50 AM, Jonathan M Davis wrote:
> On Thursday, 15 October 2015 at 15:16:59 UTC, Steven Schveighoffer wrote:
>> I don't really understand all the disdain for synchronized here...
>
> Because it's usually either the wrong solution or just unnecessary. If
> you are going to have a single mutex for an entire object, then it's
> nice in the way that it's nice that invariants are nice. They're not at
> all necessary, because the same thing can be done manually via
> assertions inside of all of the public member functions, but it does
> make them less error-prone.

I'm speaking just about the synchronized(mutex) statement, not about 
synchronized classes or methods.

I don't think I've ever used a synchronized class.

> As for synchronized statements/blocks, they're simply syntactic sugar
> that add no real value that I can see, and they can do less then the
> equivalent with guards/autolocks. These two pieces of code are equivalent:
>
> synchronized(mutex)
> {
> }
>
> {
>      Guard guard(mutex);
> }
>
> and the second one is far more flexible, since it allows for stuff like
> guard.unlock() or using the mutex with a condition variable.

You can do both of these with synchronized statements, mutex.unlock 
works and you can use with a condition variable.

As I said before, with the Guard lock, you have more room for error, and 
visually the lock is better identified with a synchronized statement.

> So,
> synchronized statements are a poor-man's guard/autolock and simply not
> worth having IMHO unless we find some way that it allows us to get the
> compiler to do stuff (like being able to implicitly remove shared on
> some level, though because you have arbitrary code within the
> synchronized block and aren't dealing with encapsulated shared variables
> like with synchronized classes, I don't see how we really can get the
> compiler to do much special with synchronized blocks).

We could do away with new, and require people to call malloc and 
constructors directly. The sugar is nice, and keeps your code from 
making dumb mistakes.

I see synchronized blocks as a clear advantage over arbitrary locking 
just from a cleanliness point of view.

-Steve


More information about the Digitalmars-d mailing list