Synchronized method Overriding
Parent Class:
public class Parent{
public synchronized void function() {
System.out.println(“function in Parent”);
}
}
public synchronized void function() {
System.out.println(“function in Parent”);
}
}
Child Class
public class Child extends Parent {
public void function() {
System.out.println(“function in Child”);
}
public void function() {
System.out.println(“function in Child”);
}
}
yes, synchronized method can be overriden. But It’s not thread safe in below scenario.
Parent a = new Child();
a.function();Here overridden synchronized method’s contract can be violated as subclass provides an implementation that is unsafe for concurrent use.
Vice-Versa : If overriding method i.e method implemented in B class is made synchronized and method in class A is not synchronized , still it is valid overriding.
Best case to ensure thread safety :make both methods , i.e methods declared in super class and child class synchronized.
No comments:
Post a Comment