There were several thoughful answers to this question, but ultimately the answer is no. This does seem to be a design flaw in Java. There is simply no way to guarantee exclusive access to an object your own code did not create. Apparently other languages do exist that do solve this problem. In Java, however, the only thing you can do is fully document the intended use of the class and hope programmers read and understand the documentation. What's especially pernicious is that the behavior in a multithreaded environment of most of the Sun supplied classes in the java
packages is undocumented. This has gotten a little better in JDK 1.2, but not enough.
Several people argued that the question was silly; that it was ridiculous to attempt to guarantee behavior in the face of unknown objects produced by unknown programmers. The argument essentially went that classes only exist as part of a system and that you can only guarantee thread safety by considering the entire system. The problem with this attitude is that it runs completely counter to the alleged benefits of data encapsulation and code reuse that object oriented programming is supposed to provide. If you can only write safe code by writing every line of code in the system, then we might as well go back to C and Pascal and forget all the lessons learned in the last twenty years.
Read full article from Thread Safe Streams
No comments:
Post a Comment