On Thursday, 28 January 2016 at 22:59:58 UTC, cym13 wrote:
On Thursday, 28 January 2016 at 11:53:48 UTC, Russel Winder
wrote:
It should be pointed out that anyone using the synchronized
keyword anywhere in Java code is doing concurrent and parallel
programming wrong. If they are using synchronized in single
threaded programming well, then…
[...]
I have seen you talk about this before and I too would love you
to elaborate on the subject.
One of the most obvious problems with using `synchronized` on
methods, or using `synchronized(this)`, is that an object has no
control over its monitor. All code that can see a particular
instance can choose to synchronize on that instance, which
creates opportunities for deadlocks. This problem can be avoided
by controlling access to the monitor you use. One of the easiest
ways to control access to your monitor is by having a private
object to synchronize on (e.g. `private final Object lock = new
Object();`) instead of synchronizing on `this`. Further
improvements can be made by explicitly using one of the classes
found in java.util.concurrent.locks: this allows you to be more
explicit by, for instance, choosing a ReadWriteLock, and it
provides access to proper conditions.
Another problem with `synchronized` in Java is that it requires
all objects to contain an implicit monitor, while the vast
majority of objects will never get synchronized on: for all those
objects this is useless overhead. Sadly backwards compatibility
implies that Java will likely never be able to entirely get rid
of this overhead.