<code>Reader</code> and <code>Writer</code> each have a ctor that takes an <code>Object</code> argument for use as a lock object. Could some knowledgable person discuss the implications of supplying an object for locking other than the constructed object itself? How does use of a separate object affect blocking I/O operations? Do <code>InputStream</code> and <code>OutputStream</code> lock on themselves when I/O blocks? So much to learn, so few neurons left...
Joined: Nov 22, 2008
I goofd. Would the moderator please move this post to Threads?
t1.start(); t2.start(); } </pre></code> This might be useful, for example, if you want to log error messages from all your threads in one file. Thread 1 uses bw1 to write a message to errors.log, and thread 2 does the same using bw2. The key is, you don't want the two messages to arrive simultaneously. You might get <code>Message from thread 1 Message from thread 2</code> or <code>Message from thread 2 Message from thread 1</code> but you don't want <code>MesMsessage fagroe m tfroreadm th2 read 1</code> which is one of many possible results if the two threads were to write simultaneously. As it happens though, you don't have to worry about this, because Java has already been designed to avoid this problem. The constructor <code>new BufferedReader(fw)</code> invokes the parent constructor <code>Reader(fw)</code>, which tells the new reader to sync on the fw object. This occurs for each of the BufferedReaders, so they both synchronize on the same fw object, and there is no way for them both to write simultaneously. Hmmm. I'm not sure how often this sort of situation comes up. Normally it's up to the programmer to make sure that two different threads aren't trying to access the same resource simultaneously. There are plenty of other things that can go wrong in this kind of situation if the programmer isn't careful. It just so happens that Java is able to prevent some of them though this design. To answer your last question, it doesn't look like InputStream and OutputStream & their descendants do much synchronization of their methods - and if they do, it's usually self-synchronized, not synchronized on another object. Anyway, I'll go ahead and move this to the Threads topic and see if any new ideas pop up.