What is the purpose of passing parameter to synchronized block?

Because it doesn’t matter whether I pass String’s instance, Some random class’s instance to the synchronized block as the synchronized block works perfectly irrespective of the parameter being passed to the block. The purpose of the parameter is twofold: It makes it possible to synchronize other blocks on the same object, so that if you … Read more

What is the difference between a synchronized method and synchronized block in Java? [duplicate]

A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods). Synchronized blocks uses the expression as a lock. So the following two methods are equivalent from locking prospective: synchronized void mymethod() { … } void mymethod() { synchronized (this) { … } … Read more

What is the difference between synchronized on lockObject and using this as the lock?

Personally I almost never lock on “this”. I usually lock on a privately held reference which I know that no other code is going to lock on. If you lock on “this” then any other code which knows about your object might choose to lock on it. While it’s unlikely to happen, it certainly could … Read more

In java, return value within synchronized block seems like bad style. Does it really matter?

It’s absolutely fine – as is returning from a loop, or from a try block which has an appropriate finally block. You just need to be aware of the semantics, at which point it makes perfect sense. It’s certainly simpler code than introducing a local variable for the sake of it: // Ick – method … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)