How can I ensure that an overridden method is synchronized

前端 未结 3 438
傲寒
傲寒 2021-02-02 09:59

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

3条回答
  •  日久生厌
    2021-02-02 10:42

    This link to the JLS confirms that we can't mix abstract and synchronized.

    Though much weaker than a keyword or standard annotation, but stronger than documentation: perhaps try a Marker interface?

    ... provides a means to associate metadata with a class where the language does not have explicit support for such metadata.

    This is a stretch, but might help, in that the derived class makes a declaration (edit: new example tests the declaration):

    interface EatMethodIsThreadSafe {}
    
    abstract class Animal {
        public Animal() {
            if (! (this instanceof EatMethodIsThreadSafe)) { 
                throw new IllegalArgumentException("eat method must be thread safe");
            }
        }
        public abstract void eat();
    }
    
    public class Bear extends Animal implements EatMethodIsThreadSafe {
        public synchronized void eat() {}
        public static void main(String...args) { Bear b = new Bear(); } 
    }
    

提交回复
热议问题