问题
Is there any way i can get a thread safe buffered reader .I got the the following info when i ran this code#
Threadid=28 ObjectReference=de.factfinder.resource.Resource@1b7aeb4
Threadid=28 ObjectReference=java.io.InputStream@3d6fb9
Threadid=28 ObjectReference=java.io.InputStreamReader@171e0f6
Threadid=28 ObjectReference=java.io.BufferedReader@1684179
28 started Reading
Threadid=28 ObjectReference=de.factfinder.resource.Resource@1b7aeb4
Threadid=28 ObjectReference=java.io.InputStream@3d6fb9
Threadid=28 ObjectReference=java.io.InputStreamReader@171e0f6
Threadid=28 ObjectReference=java.io.BufferedReader@1684179
28 finished Reading
Threadid=38 ObjectReference=de.factfinder.resource.Resource@1bebf14
Threadid=38 ObjectReference=java.io.InputStream@3d6fb9
Threadid=38 ObjectReference=java.io.InputStreamReader@171e0f6
Threadid=38 ObjectReference=java.io.BufferedReader@1684179
38 started Reading
Threadid=38 ObjectReference=de.factfinder.resource.Resource@1bebf14
Threadid=38 ObjectReference=java.io.InputStream@3d6fb9
Threadid=38 ObjectReference=java.io.InputStreamReader@171e0f6
Threadid=38 ObjectReference=java.io.BufferedReader@1684179
38 finished Reading
The hash codes for buffered reader , InputStreamReader and InputStream remains same.Why?
回答1:
Is
BufferedReader
thread safe?
The javadoc doesn't state the a BufferedReader is thread-safe, but when I look at the source code I see that the read methods use synchronize
and an internal lock
object. (You can check this for yourself at http://www.docjar.com/html/api/java/io/BufferedReader.java.html)
So the answer is (probably) yes, though it may depend on the implementation and version of Java that you are using.
However, there are two other things to take into account:
A
BufferedReader
is a wrapper for aReader
, which is typically a wrapper for other classes. If parts of the same "I/O stack" are used by other threads, the fact thatBufferedReader
is thread-safe is not sufficient.If you have two threads both trying to read from the same
BufferedReader
you can get into trouble due to the threads not coordinating. While the individual read operations behave atomically, sequences of operations do not.
In short, thread-safety is not necessarily sufficient to ensure that there won't be problems in a multi-threaded application.
The hash codes for
BufferedReader
,InputStreamReader
andInputStream
remains same. Why?
The probability of 3 new objects having the same identity hashcodes as 3 previously created objects is very small, so I can only assume that your assumption / assertion that you are creating new instances each time is in fact incorrect.
来源:https://stackoverflow.com/questions/8342172/is-buffered-reader-thread-safe