3

I was going through the differences between scanner and BufferedReader in Java and one point which I could not understand was that said

Scanner is not synchronized while BufferedReader is.

Now can anyone please explain what it means?

Rahul Singh
  • 125
  • 10
  • 1
    http://stackoverflow.com/questions/2231369/scanner-vs-bufferedreader question has already asked before – Priyamal Apr 17 '16 at 05:25
  • 1
    [Here's an explanation](https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html) of synchronization in Java. But where exactly did you see that quote? – shmosel Apr 17 '16 at 05:27
  • I am not asking the difference between scanner and BufferedReader.I am asking what is the meaning of synchronization of BufferedReader and not of scanner.Is it clear now? – Rahul Singh Apr 17 '16 at 05:27
  • Possible duplicate of [Is the scanner in java is not thread safe?](http://stackoverflow.com/questions/31024254/is-the-scanner-in-java-is-not-thread-safe) – Jonathan Andersson Apr 17 '16 at 05:27
  • 1
    @Priyamal That question doesn't address the question of the author. The author wants to know what `synchronized` means, and that question doesn't ever explain what `synchronized` is, it only refers to the word multiple times. – Matt C Apr 17 '16 at 07:21

1 Answers1

3

Literally, it means what it says. Key operations of the BufferedReader API are implemented using synchronized blocks, and the equivalent operations in Scanner are not.

This means that a BufferedReader can be "safely" shared between multiple threads1, whereas a Scanner cannot. A Scanner is inherently non-thread-safe, even if it wraps a thread-safe input source.


1 - Actually, this does not absolve you from thinking about threading. If you have multiple threads calling read(...) operations on the same BufferedReader without some form of coordination, then there is no way to know which thread will read which characters from the stream. By some definitions, that would make the usage non-thread-safe. The disposition of the characters to the right threads is usually important to the correctness of the application.

ChiefTwoPencils
  • 11,778
  • 8
  • 39
  • 65
Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • For a certain, not necessarily intuitive, definition of "safely". And of course `Scanner`s can be safely shared between multiple threads, too, for a different definition of "safely" that involves external synchronization. – John Bollinger Apr 17 '16 at 05:31