I just realized where these can be useful. Say you have more than one writer that writes to the same stream, from different threads:
<code><pre>
public void method() {
FileWriter fw = new FileWriter("errors.log");
Thread t1 = new Thread() {
public void run() {
BufferedWriter bw1 = new BufferedWriter(fw);
bw.writeLine("Message from thread 1");
}
};
Thread t2 = new Thread() {
public void run() {
BufferedWriter bw1 = new BufferedWriter(fw);
bw.writeLine("Message from thread 2");
}
};
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.