As you can see the first class is creating 4 threads that are simultaneously reading from the same stdin.
As they are using BufferedReader.readLine() to read from, only one thread must be able to read at any given time(as readLine waits() till it receives a input ).
So after entering some text into the console only one of the threads must read it. So the expected output must be
Expected: Reader One: .Starting Console Reader .....
Reader Two: .Starting Console Reader .....
Reader Thr: .Starting Console Reader .....
Reader Fou: .Starting Console Reader .....
Reader One: reads : 12
Reader Thr: reads : 45
set up: Java - jdk1.6.0_18
IDE - Netbeans
OS - Windows XP SP 2
Executing the code multiple times yields the same result.
Am unable to reproduce the output you have listed.
Let me know if you can reproduce it successfully.
If so, let me know your software setup.
posted 8 years ago
Hi my setup was
IDE : eclipse3.3
OS : win xp sp3
I tried the application independent of eclipse though good old command prompt . Works well now .. Thinking might be something to do with eclipse.
Will try a few other PnC's to see. thanks for the reply though would never have doubted by environment otherwise .
You expect that the calls to readLine() are atomic. That's an assumption I wouldn't dare make. Fortunately that's easily remedied by putting the readLine() calls in a synchronized block:
Because all threads use the same BufferedReader the calls to readLine() are now guaranteed to not interweave.
Thread-safety of readLine was the first thing on my mind when I came across this post.
Digging in to the source yielded the following snippet from BufferedReader:
readLine in BufferedReader is thread-safe, so are most of the other methods in the class.
But nothing is mentioned in the API doc about thread-safety.
Now the question is, how will developers get to know whether a method/class is thread-safe if it is not documented in API?
Developers will end up locking/unlocking un-necessarily which incurs a significant performance cost.
Can someone shed some light in this issue?