无循环死锁
如果我绘制一个图表,表示对阻塞函数(java同步方法)的所有可能调用,并且在该图表中没有任何循环,我可以确定死锁是不可能的吗? Petri网不是这样工作的吗?
我不是在寻找这样的答案:使用一些怪物框架等等。
我想用同步方法处理多线程。
EDIT1:尖箭头表示一个类是否调用另一个类的任何同步方法 编辑2:klick @here示例,显示一个循环
if I draw a graph that symbolizes all possible calls to blocking functions (java synchronized methods) and I haven't got any cycle in this graph, can I be sure that deadlocks are imposible. Do petri-nets not work like that?
I am not looking for answers like this: Use some monster framework blahblah.
I want to handle my multithreading with synchronized methodes.
EDIT1: The pointed arrows symbolize if one class calls any synchronized method of another class
EDIT2:klick @here the example, showing a cycle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这还不够。假设你必须有线程:A和B。A调用对象o1的方法m1,该方法调用对象o2的方法m1。线程B调用对象o2的方法m2,对象o2又调用对象o1的方法m2。假设所有方法都是同步的。现在,A和B同时执行,导致死锁。虽然,方法之间不存在循环调用关系。
那是作业吗?
即使您对类进行了编辑,但这还不够,因为您可以通过非同步方法调用来关闭循环。
No, that is not enough. Suppose you have to threads: A and B. A calls a method m1 of object o1, which calls method m1 of object o2. Thread B calls method m2 of object o2, which calls method m2 of object o1. Suppose all methods are synchronized. Now, there are concurrent executions of A and B which lead to dead-locks. Although, there is no cyclic call relation between methods.
Is that homework?
Even with your edit regarding class it is not enough, because you can close the cycle through a non synchronized method call.
否。请考虑:
请参阅 http://pastebin.com/QfK5ZByj 以获取可运行的示例。对我来说,它很快就会陷入僵局。
No. Consider:
See http://pastebin.com/QfK5ZByj for a runnable example. It deadlocks pretty quickly for me.
如果没有
synchronized
关键字,某些方法可能会阻塞。例如,这适用于 java.util.concurrent 包中的许多方法。您还应该考虑方法内的synchronized
块。如果仅考虑同步方法,则可能会在方法调用中出现没有循环的死锁,因为同步方法使用对象实例作为监视器。例如,如果您有两个对象 A 和 B,每个对象都有同步方法 1() 和 2()。如果 A.1() 调用 B.1() 且 B.2() 调用 A.2(),尽管方法中没有循环,但如果线程在以下位置调用
B.2()
同时另一个调用A.1()
则存在死锁风险。Some methods might block without a
synchronized
key word. This applies to many methods in packagejava.util.concurrent
for instance. You should also take into account thesynchronized
blocks inside methods.If considering only synchronized methods, you can have deadlocks without cycle in methods calls, as the synchronized methods use the object instance as a monitor. For instance if you have two objects A and B, each one with synchronized methods 1() and 2(). If A.1() calls B.1() and B.2() calls A.2(), although there is no cycle in methods, if a thread calls
B.2()
at the same time an other callsA.1()
then there is a deadlock risk.