java中Singleton的并发访问
我有一个单一对象,它包含一种方法,但不同步。单例可以同时被多个客户端访问 - 如果多个客户端访问该对象会发生什么?对象引用是否会以先到先服务的方式提供给他们...也就是说,一个客户端是否必须等待第一个客户端完成该对象,或者它将在内存中获得相同的对象引用?
我对单例中不同步的方法有一种奇怪的感觉。如果 2 个客户端使用不同的参数调用 Singleton.method(param) - 他们不会给彼此带来问题,对吗?
I have a sinlgeton object which holds one method, witch is NOT synchronized. The singleton can be accessed by many clients at a time - what will happen if multiple clients access that object ? Will the object reference be provided to them in a First come- first serve manner...that is, would one client have to wait for the first one to finish the object, or it will be given the same object reference in memory ?
I get a weird feeling about the method in the singleton which is not synchronized. If 2 clients call Singleton.method(param), with different params - they wont create problems for each other right ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的方法不使用任何共享状态(例如单例字段),那么这是完全安全的。方法参数在线程堆栈上传递 - 这是本地的并且是堆栈独占的。
想象一下两个处理器运行相同的代码,但在内存中的不同区域运行。
If your method does not use any shared state (e.g. singleton fields), this is completely safe. Method parameters are passed on the thread stack - which is local and exclusive to the stack.
Think about two processors running the same code but operating on different areas in memory.
Singleton 意味着该类应该只有一个实例。好吧,如果单例没有正确实现,这可能不是真的。拥有单例的最安全方法是将其声明为
枚举
。如果有一个方法不同步,则意味着多个线程可以同时执行该方法的主体。如果单例是不可变的,那么就不用担心。否则你应该注意可能的不一致。一个线程可以更改状态,而另一个线程也可以更改状态,从而导致难以调试的不可预测的结果。
Singleton means that there should be only one instance of the class. Well, this may not be true if the singleton is not properly implemented. Safest way of having a singleton is to declare it as an
enum
.If there's a method that's not synchronized it means that multiple threads can execute the body of the method in the same time. If the singleton is immutable then there's no worry. Otherwise you should pay attention to possible inconsistencies. One thread can change a state while the other one is doing the same resulting in unpredictable outcome very hard to debug.