Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure that an overridden method is synchronized

I have a class of common code that is thread safe.

One of the methods in that class is abstract and needs to be overridden for different implementations.

I need to ensure or at least flag to other developers that all implementations of this method need to be thread-safe.

What is the best way to do this?

Is there a keyword or annotation to this effect?

I have already tried abstract synchronized but that combination of keywords is not allowed.

like image 846
ljbade Avatar asked Oct 02 '12 05:10

ljbade


People also ask

Can synchronized method be overridden?

Synchronized method Overriding !! Above code compiles ,so answer to above question is “yes,synchronized method can be overriden” .

How do you tell if a method is overridden?

getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.

How do you prevent a method from being overridden?

Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated. An abstract class can contain abstract methods—methods that are declared but not implemented.


1 Answers

You can't do it directly. One thing you can do is have the method be concrete, but invoke an abstract method:

public synchronized final void foo() {     doFoo(); } protected abstract void doFoo(); 

That way, doFoo() will always* be invoked under the synchronization established by foo().

* unless someone invokes it directly, so you should name and document it to make it clear that they shouldn't.

like image 51
yshavit Avatar answered Sep 29 '22 07:09

yshavit