JavaRMI同步
我知道下面的代码中有很多部分缺失,我的问题是关于RemoteImplementation中的同步机制。我还了解到在这个网站和其他网站上有一些关于RMI和同步的问题;我在这里寻找明确的确认/矛盾
我的问题是:当我有几个客户端同时运行时,这是同步add方法调用的合理方法吗?也就是说,假设所有的ID都不同,那么在20个客户端在不同的机器上完成执行后,树集的大小是否会达到20000,而这些机器是同时启动的
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);
}
}
}
# 1 楼答案
那会管用的。您实际上不需要lock对象,可以直接在
ids
上进行同步# 2 楼答案
synchronized
关键字将使显示的服务器代码以线程安全的方式执行,因此ids
将包含20000项(除非输入中有重复项,但这不太可能)