Let's say I have a synchronized method on some class:
abstract class Foo { public synchronized void foo() { // synchronized! // ... }; }
and I overrode it without using the synchronized modifier:
class Bar extends Foo { @Override public void foo() { // NOT synchronized! super.foo(); // ... } }
I have a couple of specific question regarding this scenario:
super
-call be synchronized?super
-call, will anything be synchronized?synchronized
(I noticed that abstract method definitions or method definitions inside an interface don't allow the synchronized keyword)?Yes. Overloaded methods can be synchronized.
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.
Non-Synchronized means that two or more threads can access the methods of that particular class at any given time. StringBuilder is an example of a non-synchronized class. Generally, a non-synchronized class is not thread-safe. ( but some non-synchronized classes are thread-safe)
public synchronized void foo() { // synchronized! // ... };
Is essentially the same as:
public void foo() { synchronized (this) { // synchronized! // ... } };
The latter is more explicit, so I would generally suggest using that form. Or better using a lock that is a private field instead of the "outer" object.
So: 1. No. 2. Yes. 3. No. 4. Mark the method final
and call a protected
method that may be overridden.
public final void foo() { synchronized (this) { fooImpl(); } }; protected void fooImpl() { // ... }
As ever, you may well be better off with delegation rather than subclassing.
Failing to use synchronized when overriding a synchronized method has the potential for causing runtime bugs. As a safeguard, there is an Eclipse checker you can turn on to detect this condition. The default is "ignore". "Warning" is also a valid choice.
which will produce this message:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With