与Java的级联同步
我非常努力地搜索有关该问题的信息,但没有任何相关信息。 任何贡献将不胜感激。
DataStructure ds = new DataStructure();
public synchronized void run() { b(); }
private void b() { ds.update(); }
public synchronized void c() { ds.update(); }
假设上面的代码是使用线程实现的。 您可能会注意到,有一个 DataStructure 对象通过同步方法进行共享和访问,而在任何给定时间只能调用一个同步方法(我没有记错,对吧?)。 是否有可能通过公共方法以不同步的方式访问 DataStructure 对象?
谢谢。
I tried really hard to search for information about the issue, but nothing was relevant.
Any contribution will be appreciated.
DataStructure ds = new DataStructure();
public synchronized void run() { b(); }
private void b() { ds.update(); }
public synchronized void c() { ds.update(); }
Suppose that the above code is implemented using a thread.
as you might notice, there is a DataStructure object which is being shared and accessed through synchronized methods, when only one synchronized method can be called at any given time (I am not mistaken. right?).
Is there any possibility that the DataStructure object will be accessed through the public methods in unsynchronized manner?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码不完整,但如果上述代码是
Runnable
或Thread
的一部分,则给定方法不可能并发,因为您正在同步整个run() 方法。在这种情况下使用线程是毫无意义的。
我也没有看到
DataStructure
在线程之间共享的位置 - 看起来像是为每个线程创建了一个单独的结构。如果它实际上是共享的,那么访问将不会同步,因为您在 Runnable 或 Thread 而不是共享对象上进行同步。Your code is incomplete, but if the above is part of a
Runnable
orThread
, then no concurrency is possible with the given methods since you're synchronizing the entirerun()
method. Using threads is pretty pointless in that case.I also don't see where the
DataStructure
would be shared between threads - looks like a separate one is created for each one. If it actually is shared, then access would not be synchronized because you synchronize on theRunnable
orThread
rather than the shared object.如果没有看到更多代码,很难判断。这些方法属于什么类?它们是如何调用的,以及由哪些类调用?
并发问题很难诊断,如果没有足够的信息,诊断就更困难。
我假设您有执行上面 run() 方法的线程,并且有不同的线程执行 c() 方法。同步发生在上述方法所在的类上,因此不会有任何问题(除非线程很多,否则会很慢)。
Without seeing more code, its very hard to tell. What is the class that those methods belong to? how are they invoked, and by what classes?
Concurrency problems are hard to diagnose, and harder if there isn't enough information.
What i assume you have are threads that execute the run() method above, and there are different threads that execute the c() method. The synchronization happens on the class that the above method resides, so there wouldn't be any problems (except slowness if lots of threads).
如果
那么你所期待的是正确的。不应该通过类的公共方法对 ds 进行任何并发访问。
老实说,我在您的类中没有看到任何特殊之处,使其与普通同步方法示例不同。
If
then what you are expecting is correct. There shouldn't be any concurrent access to ds through public methods of your class.
Honestly I don't see anything special in your class that make it different from normal synchronized method example.