gpt4 book ai didi

java - 在调用 EJB 方法时中断客户端线程的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:22 25 4
gpt4 key购买 nike

我有一个 java 客户端,它在新线程中管理其服务器调用,以防止 GUI 卡住。

即使在许多地方都阻止了这种情况,该方法也可能会在同一模型上再次调用,例如使用不同的参数。在这种情况下,我显然希望具有最新参数的最新调用成为“成功”并显示其结果的调用。

我有一个系统,它跟踪先前启动的线程,并在启动新线程之前中断它(Thread.interrupt())。然后,其他方法在将新结果发送到 GUI 元素之前检查它们是否在非中断线程中运行(使用 if (Thread.currentThread().isInterrupted()))。

此结构与服务器的先前连接器一起使用,因为我是唯一检查进程上的中断标志的人。我的问题是,我现在在客户端中使用 EJB 方法调用,它们对中断的线程 react 很糟糕。在 EJB 调用期间中断线程将触发 RuntimeException,其中包括 InterruptedException。而且这似乎不是一件正常的事情。

显然,我可以在每个服务器调用中捕获 RuntimeExceptions 并检查其中断原因,但它看起来不太“干净”。

我的问题是:在这种情况下我能做什么?中断运行 EJB 方法调用的线程的正确方法是什么?

最佳答案

既然您不介意过时的 EJB 调用在服务器上继续,为什么不允许调用线程“自然”终止而是丢弃结果,因为它的调用已被另一个线程取代?我没有时间提供示例实现,但您可能会发现使用 Future 和相关的 Java 并发类已经取得了一些进展。

编辑

除此之外,您可能会发现类似的方法可以解决问题,但对我来说这感觉很老套,我确信还有更优雅的解决方案。

在调用线程上(可能是按钮的 onclick 方法):

AsynchronousResultManager.registerRequest("UNIQUE_IDENTIFIER", runnableExecuteRequest);

registerRequest 会执行以下操作:

registerClick(String id, Runnable execution) {
AtomicReference ref = executions.get(id); //executions is a Map<String, AtomicReference> created as a a computing map by Guava MapMaker
execution.setReference(ref); //so that the Runnable has a reference to it later
ref.set(execution); //this will overwrite an existing reference to a previous invocation.
//here you need to actually kick off your thread in whatever way works best for you
}

执行请求的runnable将是以下子类:

public abstract class RequestRunnable implements Runnable {

private AtomicReference ref;

public void run() {
doRunInternal(); //actually go off and do the request to the J2EE server
if (this == ref.get()) { //ie if the current runnable is the same as in the reference, we can proceed to actually dispatch the result
dispatchResult(); //this method would do something like add a runnable to the SwingWorkerThread
}
}

protected abstract void doRunInternal();
protected abstract void dispatchResult();

public void setReference(AtomicReference ref) {
this.ref = ref;
}

}

这可能会崩溃并烧毁,但希望它能为您指明一条线索......

关于java - 在调用 EJB 方法时中断客户端线程的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5231302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com