본문 바로가기
개발/일반

BufferedReader 는 threadsafe?

by 로그인시러 2016. 11. 24.

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.

The hash codes for BufferedReaderInputStreamReader and InputStream 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.

출처: http://stackoverflow.com/questions/8342172/is-buffered-reader-thread-safe



실제 소스를 보면,

  170       public int read() throws IOException {
  171           synchronized (lock) {
  172               ensureOpen();
  173               for (;;) {
  174                   if (nextChar >= nChars) {
  175                       fill();
  176                       if (nextChar >= nChars)
  177                           return -1;
  178                   }
  179                   if (skipLF) {
  180                       skipLF = false;
  181                       if (cb[nextChar] == '\n') {
  182                           nextChar++;
  183                           continue;
  184                       }
  185                   }
  186                   return cb[nextChar++];
  187               }
  188           }
  189       }

lock 객체를 synchronized 거는 건다. 


따라서, threadsafe...

'개발 > 일반' 카테고리의 다른 글

디미터의 법칙  (0) 2017.01.11
java set 으로 union, intersection, difference, reverse  (0) 2016.12.27
디자인 패턴 ( DESIGN PATTERN ) 요약  (0) 2016.11.24
UML 표기법  (0) 2016.11.24
JAVA arrays contains  (0) 2016.11.11

댓글