The benefit is that it's very clean and amazingly clear what it does (I don't understand your "so I can tell easily which regions are synchronized with each other" comment. What is hard?
The synchronized method format makes it so that the format is never accessed by more than one thread at any time. Synchronizing on a variable makes it the implicit "lock" (i.e anything else synchronizing on that variable will get a lock).
If you read more in the thread you'll see a construct which exactly handles the 'syncronized(variable) { ... }' case.
The whole idea is to avoid having to explicedly define mutex variables, which you often need to keep in global variables. If you always had to specify a mutex, that would remove half the purpose.
That said a implicit lambda construct I wrote earlier that uses a weak mapping can check to see if the variable sent to it is a mutex and if is use that rather than another entry in the weak mapping.
/ David Hedbor
Previous text:
2003-02-05 01:00: Subject: synchronized
I've never understood benefit of hiding mutexes like that Java construct does. It even does so in three different ways depending on how it's used. Is the code somehow made more clear because the mutexes disappear? I prefer to see them, so I can tell easily which regions are synchronized with each other. That also makes it easier to search on the mutex variable to find those regions.
There's one benefit with a block construct like that: It makes the region where the lock is held more clear. (The pike way of relying on refcount garbing of the lock has lead to many bugs, e.g. with the tail recursion optimization. I don't rely on refcounting for locks anymore; I always zero them explicitly afterwards.)
So in my view a good synchronized construct would always require a mutex argument. E.g:
Thread.Mutex my_mutex = Thread.Mutex(); synchronized(my_mutex) void my_first_function() {...}
void my_second_function() { ... synchronized(my_mutex) { ... } }
The second case above is solvable with implicit lambda, but I'd rather avoid implementing it that way since it "destroys" the syntax so it can't be upgraded to a better implementation later on (see the blurb about implicit lambdas in the CHANGES file).
As a transitionary measure, we could perhaps have something like this instead that works through implicit lambdas:
my_mutex->synchronize() { ... };
/ Martin Stjernholm, Roxen IS