gpt4 book ai didi

java - 等待计算值(或超时)的高效并发数据结构

转载 作者:行者123 更新时间:2023-11-29 08:29:04 25 4
gpt4 key购买 nike

我希望一些并发专家可以提供建议,因为我不想重写可能存在的东西。

描绘问题;我有一个网络连接来寻找他们独特的计算结果(使用他们提供的 key 来检索他们的结果) - 但是结果可能尚未计算,所以我希望连接等待( block )最多 n 秒,然后放弃并告诉他们我(还)没有他们的结果(计算值的计算时间是不确定的)。类似的东西;

String getValue (String key)
{
String value = [MISSING_PIECE_OF_PUZZLE].getValueOrTimeout(key, 10, TimeUnit.SECONDS)
if (value == null)
return "Not computed within 10 Seconds";
else
return "Value was computed and was " + value;

}

然后有另一个线程(计算线程)进行计算——类似;

public void writeValues()
{
....
[MISSING_PIECE_OF_PUZZLE].put(key, computedValue)
}

在这种情况下,有许多线程在后台 工作以计算最终将由网络连接获取的值。 Web 连接对计算的内容和计算的执行时间没有控制权或权限——正如我所说的——这是在后台的池中完成的,但是这些线程可以在计算完成时发布(它们的工作方式是这个问题的要点)。发布消息可能会被消费,也可能不会被消费——取决于是否有任何订阅者对此计算值感兴趣。

因为这些是将被阻塞的网络连接——我可能有 1000 多个并发连接等待(订阅)它们的特定计算值,所以这样的解决方案需要非常轻地阻塞资源。我最接近的是这个 SO question我将进一步探索,但想在自己写这篇文章之前检查我是否没有遗漏明显的东西?

enter image description here

最佳答案

我认为您应该使用 Future,它能够在单独的线程中计算数据并在请求的时间段内阻塞等待答案。注意如果超过 3 秒它是如何抛出异常的

public class MyClass {

// Simulates havy work that takes 10 seconds
private static int getValueOrTimeout() throws InterruptedException {
TimeUnit.SECONDS.sleep(10);
return 123;
}


public static void main(String... args) throws InterruptedException, ExecutionException {
Callable<Integer> task = () -> {
Integer val = null;
try {
val = getValueOrTimeout();
} catch (InterruptedException e) {
throw new IllegalStateException("task interrupted", e);
}

return val;
};

ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);

System.out.println("future done? " + future.isDone());

try {
Integer result = future.get(3, TimeUnit.SECONDS);
System.out.print("Value was computed and was : " + result);
} catch (TimeoutException ex) {
System.out.println("Not computed within 10 Seconds");
}
}

关于java - 等待计算值(或超时)的高效并发数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794862/

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