gpt4 book ai didi

java - 分层死锁(具有依赖性),...或 : how do I get my "wait"s, "notify"s,设计对吗?

转载 作者:行者123 更新时间:2023-12-02 07:41:35 24 4
gpt4 key购买 nike

// multiple server instances (replicas), coordinated using MsgCoordinationService
public class Server {

ConcurrentHashMap<TxID,Future<Msg>> local_registry = new ...
MsgCoordinationService coordination_service = new ..

...

// Socket instance to communicate with a client...
public void accept(Socket s) {
new Thread(new Worker(s)).start();
}

// propose msg to coordination service, register demand to respond to client in local registry
public Future<Msg> register(Msg m) {
FutureMsg f = new MsgFuture(); // Future handle w. reference to an empty Msg object [= response]
TxID uniqueID = coordination_service.propose(s); // transaction ID
local_registry.add(uniqueID, f);
return f;
}

// called by coordination service, guaranteeing a global order on msg deliveries
public synchronized void deliver(TxID id, Msg m) {
... process Msg object [request]
... if local_registry.contains(id), 'compile' response
(using the Msg object from FutureMsg f, f.get() - f.isDone() when a certain Msg flag has been set)

___ now:
... notify waiting 'Worker' threads to check whether their 'Future' object isDone()
}

private class Worker implements Runnable {
...
public void run() {
...
Future<Msg> f = Server.this.register(request); // obtained through Socket s

while(!f.isDone())
wait();

response = f.get();
...
}
}
}

我正在实现一个复制服务[多个服务器,客户端通过.在单个服务器实例中,创建/更新/删除操作将通过协调服务进行分发,以保证消息传递的全局顺序]。

一旦客户端与服务器实例建立新连接,所有通信都将通过专用 Worker 进行 channel 传输。实例[在本地处理读取请求,并使用 Server.this.register(...) 广播 C/U/D 操作].

register其本身基本上记录了 future 本地处理/回复的请求 - 并转发 Msg反对协调服务。

服务重新传送 Msg对象通过 deliver ,...处理完封装的任务后,Worker通知最初收到客户端请求的实例交出相应的响应。

由于某些原因,我的设计似乎被破坏了... - w/o synchronized(this) [在Worker#run() ], wait()不会等待;与 synchronized(this) ,一个notifyAll()Server#deliver(...)不会释放“被阻止”上的锁 Worker实例。

长话短说:事实证明,我需要你的帮助......要么(a):了解 wait/notify/notifyAll 的基础知识或(b):改进我的设计...或(c):(a)(b)。

最佳答案

一个线程调用wait/notify需要锁定调用这些方法的对象,否则您将得到异常。在一般形式中,假设一个任意对象:

final Object obj = new Object();
...

synchronized(obj) {
while(/* condition */) {
obj.wait();
}
}

你的wait的原因未由 notify 发布是你正在做this.wait()在与您调用的对象不同的对象内 notify ,因此它们不配对。您需要为两个调用使用相同的实例。你在做this.wait()Worker 的实例内并在做this.notifyAll()Server 的实例内,所以this不引用同一个对象。

您应该创建一个跨类和线程可见的同步对象,并在该对象上进行同步。

关于java - 分层死锁(具有依赖性),...或 : how do I get my "wait"s, "notify"s,设计对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11528383/

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