简体   繁体   English

抽象类中的同步

[英]Synchronization in abstract class

I am working on Java Event Manager, and I want to add new future to it. 我正在使用Java Event Manager,并且想为其添加新的未来。 It is custom class selection, or custom matching class system. 它是自定义类选择或自定义匹配类系统。

EventManager eventManager = new EventManager();

Ways how to set new class selector to event manager: 如何将新的类选择器设置为事件管理器:

eventManager.setClassSelector(Class<? extends ClassSelector> classSelector);
eventManager.setClassSelector(ClassSelector classSelector);

This method using class selector: 此方法使用类选择器:

eventManager.callEvent(event);

There is structure of ClassSelector 有ClassSelector的结构

public abstract class ClassSelector{
    public List<Class<?>> classSelection(Class<?> clazz);
}

Method classSelection in ClassSelector must be synchronized, because callEvent is using ThreadPool with multiple Threads and only one instance of ClassSelector. 必须同步ClassSelector中的方法classSelection ,因为callEvent使用的ThreadPool具有多个线程,并且只有ClassSelector的一个实例。

But synchronize key word is not inherited from super class. 但是同步关键字不是从超类继承的。 I need advice, how to solve this problem, by changing code or by changing logic. 我需要建议,如何通过更改代码或更改逻辑来解决此问题。

It is pretty simple: when your abstract base class needs to "restrict" a method in a certain way (like: you want to enforce the method is synchronized ) - then that method should not be abstract. 这很简单:当您的抽象基类需要以某种方式“限制”一个方法时(例如:您要强制该方法被synchronized ),则该方法不应是抽象的。

Instead implement that method and make it final : 而是实现该方法并将其最终化

public abstract class ClassSelector{
   public final synchronized List<Class<?>> getClassSelection(Class<?> clazz) {
     return getSpecificClasses(clazz);
   }

   protected abstract List<Class<?>> getSpecificClasses(Class<?> clazz);

Now it is clear that a user of your class should call that public method - and that each subclass can only implement something that is guaranteed to be called in a synchronized manner. 现在很明显,您的类的用户应该调用该公共方法-每个子类只能实现保证以同步方式调用的某些方法。

(method naming isn't really great - just meant as example) (方法命名并不十分出色-仅作为示例)

You could make classSelection a real method, that calls an abstract method. 您可以将classSelection一个真正的方法,该方法调用一个抽象方法。 Each subclass would then only supply an implementation of the abstract method. 然后,每个子类将仅提供abstract方法的实现。 This could look something like this. 这可能看起来像这样。

public abstract class ClassSelector{
    public synchronized final List<Class<?>> classSelection(Class<?> clazz) {
        return doClassSelection(clazz);
    }
    protected List<Class<?>> doClassSelection(Class<?> clazz);
}

The final prevents someone from overriding your restriction, and implementing their own non-synchronized version of classSelection . final防止某人超越您的限制,并实现他们自己的classSelection的非同步版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM