Subj : Re: Java vs. C++ To : comp.programming.threads From : doug Date : Mon May 30 2005 10:26 am "dayton" wrote in message news:ONAme.22831$J12.18249@newssvr14.news.prodigy.com... >>>>-- The Java synchronization model is rather broken. If one object with >>>>synchronized methods contains another object with synchronized methods, >>>>you become subject to deadlock because you haven't acquired all the >>>>required locks at once -- and you have no control of the level of the >>>>locks. >>> >>>It's not broken. It's more of an issue with mindlessly making all class >>>methods synchronized in the mistaken belief that this is all you need to > > I concede its not that broken, but its pretty close. A user may make their > own object synchronized, and without realizing it, compose another > synchronous object within it. The calling object locks its resources then > calls at a later time a method that locks its own resources. Unless you > have intimate knowledge of the composition and dependency of the objects, > you can't eliminate deadlock. Not being able to isolate your objects > makes the synchronized keyword dangerous. Aspect-oriented programming may > provide a means of resolving this deficiency. If a method could expose > what resources that needed to be locked to a calling method, then the > calling method could either acquire all the locks at once in an > edge-locking pattern, or use hierarchical locking like a database manager > does. In the meantime, the Java synchronized keyword can seduce you if > you're not aware of its dangers -- but I have yet to see any discussion in > a textbook of those dangers. > > You're absolutely correct that nearly all C++ "threadsafe" wrappers have > the same problem. They all tend to protect their resources with a mutex, > and most of time those wrappers are containers for your own objects. If > your objects contain mutexes, and "threadsafe" wrapped containers, you can > generate dependencies you didn't know about. Not nearly enough do we see > discussion of non-blocking algorithms such as those for a double-ended > queue. At least in C++ we can access and write code to implement such > algorithms, even though we do have to resort to assembly language for the > atomic CAS instructions. In Java, if you want to do such things you have > to call a C or C++ routine that's been written with a Java interface to do > the same work. Indeed, lots of ways to nail yourself. I usually get around these (in all languages) using: - a (n up to date!) High Level Design - some sort of debug-runtime semaphore hierarchy checker (e.g. we have our own Java 'debug pre-processor' to add the appropriate code to standard code files) .