[英]Two different classes A and B on their own thread calling a method of the same class instance C
So I've got a simple Server class that creates an instance of a Listener class for every connection made to the "server". 因此,我有一个简单的Server类,它为与“服务器”的每个连接创建了一个Listener类的实例。 The Listeners run on their own thread.
侦听器在自己的线程上运行。
I get that there might be a concurrency control problem when invoking methods on the Server class that alter files/variables. 我知道在Server类上更改文件/变量的方法时可能存在并发控制问题。 But what happens if 2 Listeners try to invoke a method that eg only returns some information about the server status?
但是,如果2个侦听器尝试调用一个仅返回有关服务器状态的信息的方法,会发生什么? Can the same Server instance handle 2 calls at the same time?
同一服务器实例可以同时处理2个呼叫吗? Or will one of the listeners have to wait till the server is done executing the method of the first caller?
还是一个监听者必须等到服务器执行完第一个调用者的方法之后,才开始?
Thanks for any help you guys might be able to provide! 感谢您可能提供的任何帮助!
If the method is not synchronized, the server can handle the two calls concurrently. 如果该方法不同步,则服务器可以同时处理两个调用。
But if they ask for status, this means that the status changes over time. 但是,如果他们要求获得身份,则意味着状态会随着时间而改变。 And if it changes over time, then all accesses, read and write, to this status should be done in a synchronized way.
而且,如果它随时间而变化,那么对该状态的所有访问(读写)都应该以同步方式进行。 Otherwise, the listener threads could see an obsolete value of the status.
否则,侦听器线程可能会看到状态的过时值。
So the method should be synchronized, or the status should be an AtomicXxx value, or it should be volatile. 因此,方法应该同步,或者状态应该是AtomicXxx值,或者应该是易失的。 The best, and correct solution is hard to give without seeing the code and knowing how the status is read and modified.
如果不查看代码并不知道如何读取和修改状态,就很难给出最佳,正确的解决方案。
对于类似的事情,我想它不会经常改变,我会考虑使用ReadWriteLock-因此,大多数情况下,您可以让多个线程同时读取状态,并且只在需要更新值时才阻塞它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.