有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

来自flyweight的java自移动资源

我正在使用需要关闭的不同资源开发应用程序,同时使用反应流

我有一个基于flyweight模式的工厂,它保留对对象的引用,并且它们实现了自动关闭接口。问题是我在Autocloseable类中使用close(), 我的问题是:在工厂中删除对封闭资源的引用的最佳解决方案是什么?我是否可以抛出某种事件并在工厂中捕获它,或者在每个可以关闭资源的操作之后,我是否应该迭代引用映射并删除关闭的资源

为了更好地了解情况: 我使用的是reactivex Observable,它会发出目录事件(创建、删除文件/目录),在每个订户取消订阅后,我会关闭我正在使用的WatchService

编辑#1

下面是我的factory类的外观:

public final class Factory {

    private final ConcurrentHashMap<String, ReactiveStream> reactiveStreams = new ConcurrentHashMap<>();

    public ReactiveStream getReactiveStream(Path path) throws IOException {

        ReactiveStream stream = reactiveStreams.get(path.toString());

        if (stream != null) return stream;

        stream = new ReactiveStream(path);
        reactiveStreams.put(path.toString(), stream);

        return stream;

    }

}

下面是我的ReactiveStream类的外观:

public class ReactiveStream implements AutoCloseable {

    (...)
    private WatchService service;
    private Observable<Event> observable;

    public Observable<Event> getObservable() throws IOException {

        (...) // where i create observable

        return observable;
    }

    (...)

    @Override
    public void close() throws IOException {
        service.close();
    }
}

正如您所看到的,我有一个工厂,它保存对ReactiveStream类的引用,它在可观察到之后关闭自己,将不再订阅(我使用doUnsubscribe(()->;在observable上使用share()之前关闭(),因此当没有订阅者时,将调用doUnsubscribe)

我的问题是,在工厂关闭后,如何删除对关闭的反应流的引用

编辑#2

observable = Observable.fromCallable(new EventObtainer()).flatMap(Observable::from).subscribeOn(Schedulers.io()).repeat().doOnUnsubscribe(() -> {
                try {
                    close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).share();

下面是我如何创建我的可观察对象。EventAcquiner是ReactiveStream中的嵌套类,它使用WatchService,每个订户停止订阅后都需要关闭WatchService


共 (1) 个答案

  1. # 1 楼答案

    今天我的同事告诉我解决这个问题的最佳方法。所以我创建了界面:

    @FunctionalInterface
    public interface CustomClosable {
    
        void onClosing();
    
    }
    

    并将此接口的引用添加到构造函数中的ReactiveStream

    现在我调用onClosing。onClosing()我需要关闭资源

    由于factory类负责声明在其资源关闭后应该执行的操作,而且我没有循环依赖,所以我的ReactiveStream类可以多次重用