我知道下面的代码中缺少一些内容,我的问题是关于 RemoteImplementation 中的同步机制。我还了解到该网站和其他网站上有几个关于 RMI 和同步的问题;我在这里寻找明确的确认/矛盾。
我的问题是:当我同时运行多个客户端时,这是同步对 add 方法的调用的合理方法吗?即,假设所有的 id 都不同,那么当 20 个客户端在同时启动的不同机器上完成执行后,树集的大小是否为 20,000?
public interface RemoteInterface extends Remote {
void add(String id) throws RemoteException;
}
public class RemoteImplemenation implements RemoteInterface{
TreeSet<String> ids = new TreeSet<String>();
final Object lock = new Object();
public void add(String id) {
synchronized(lock) {
ids.add(id);
}
}
}
public class Client {
public static void main(String[] args) {
RemoteInterface remote = (RemoteInterface)Naming.lookup(...);
for (int i=0;i<1000;i++) {
remote.add(ipaddress+"_"+i);
}
}
}
最佳答案
synchronized
关键字将使显示的服务器代码以线程安全的方式执行,因此 ids
将包含 20000 个项目(除非输入中有重复项,尽管这不太可能) .
关于Java RMI 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595125/