[英]PipeLine release resources lambda
我遇到以下问题。 我已经实现了管道处理,有时我必须释放资源,例如文件。 同时,我的管道是异步的,因此它立即释放控制权。我在Non-lamda实现中使用了shutdown方法。 我无法使用Lambda将其插入。 我当前的代码如下所示:
@FunctionalInterface
public interface Stage<T,Q> {
public Q process(T toProcess);
}
@FunctionalInterface
public interface IntermediatStage<T,Q> extends Stage<T,Q> {
public default <P> IntermediatStage<T,P> nextStage(Stage<Q,P> nextStage) {
return (T t) -> {return nextStage.process(this.process(t)); };
}
}
随后,我需要在不同阶段调用关闭方法。 问题是通过默认方法链接它们时,我对它们没有可见性。 当我添加阶段也能够添加关闭钩子时,是否可能以某种方式出现,我以后可以基于管道是异步的事实来独立调用该钩子?
谢谢
您不能仅使用接口和lambda表达式解决所有问题。 对于具有以下模式的普通类来说,这看起来像一个简单的任务:
public final class Stage<T,R> {
static final Runnable NO_OP = () -> {};
public static <I,O> Stage<I,O> create(Function<I,O> f) {
return new Stage<>(f, NO_OP);
}
public static <I,O> Stage<I,O> create(Function<I,O> f, Runnable cleanup) {
return new Stage<>(f, cleanup);
}
private final Function<T,R> actualAction;
private final Runnable cleanup;
private Stage(Function<T,R> f, Runnable r) {
actualAction=f;
cleanup=r;
}
public <P> Stage<T,P> nextStage(Function<R,P> nextStage) {
return new Stage<>(actualAction.andThen(nextStage), cleanup);
}
public <P> Stage<T,P> nextStage(Function<R,P> nextStage, Runnable nextCleanup) {
return new Stage<>(actualAction.andThen(nextStage),
cleanup==NO_OP? nextCleanup: () -> { cleanup.run(); nextCleanup.run(); });
}
public R process(T t) {
return actualAction.apply(t);
}
public Function<T, R> getActualAction() {
return actualAction;
}
public void cleanup() {
cleanup.run();
}
public Runnable getCleanup() {
return cleanup;
}
}
Stage
类是简单且不变的,但是它的实际行为由Function
和Runnable
实例确定,可以根据需要通过lambda表达式创建它们。 您可以仅使用普通函数或通过提供函数和清除操作来创建和链接。 您将获得两个不同的函数和清除操作链,从而可以独立执行它们。
没有更多有关如何清理资源的信息,人们可能会想像
@FunctionalInterface
public interface Stage<T,Q> {
Q process(T toProcess);
static <T,Q> Stage<T,Q> of(Stage<T,Q> stage){
return stage;
}
default Stage<T,Q> withRelease(Consumer<T> releaser){
return t -> {
Q q = process(t);
releaser.accept(t);
return q;
};
}
}
你可以像这样调用
Stage.of(Thing::process).withRelease(Thing::close)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.