Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make an overridden method synchronized?

I am overriding a method from superclass, however I want this method to be synchronized. Is it allowed? What could be the alternative?

like image 574
user1612078 Avatar asked Mar 21 '14 07:03

user1612078


People also ask

Can synchronized method be overridden?

For example, an overridden synchronized method's contract can be violated when a subclass provides an implementation that is unsafe for concurrent use. Such overriding can easily result in errors that are difficult to diagnose.

What happens when you override a method?

Instance Methods The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

Can we override already overridden method?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

Can methods be synchronized?

If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.


1 Answers

Yes, it's allowed as it doesn't change the contract but the implementation.

Think that you could always simply add a synchronized block :

synchronized(this) { 

just at the start of the method, which would achieve about the same result. There could also be other (possibly hidden) locks deeper in the method, which makes this really part of the implementation rather than the API.

like image 74
Denys Séguret Avatar answered Sep 29 '22 16:09

Denys Séguret