BufferedReader bug

jmc@cmpharm.ucsf.edu jmc@cmpharm.ucsf.edu
Wed Jun 23 13:16:00 GMT 1999


There is a bug in BufferedReader which causes it to sometimes
lose data during mark/reset operations.  The testcase is system
dependent, so I'll describe it:

1)  make a text file with 2 lines, the first containing about 10
  characters and the second containing hundreds.
2)  create a BufferedReader around a FileReader on this file.
3)  set a mark at the beginning of the file, with a limit of 512 bytes
4)  readLine() -- this will return the first line.  In doing so,
the fill() call in BufferedReader will load 100 bytes from the FileReader
into the buffer.  The number of bytes that gets read is pretty random,
and will trigger the bug only if it's greater than the length of the
first line, but less than the second.  On faster computers, you might
read in a lot more than 100 bytes and never notice the bug.  I only
see this on a slower machine.
5)  readLine() again -- this will return the second line.  In doing so,
the fill() method gets called again (because there is still more data
in the second line after the 100 bytes in the buffer are used up).
A bug in fill() causes the first 100 bytes of the buffer to be lost
when pos and limit are reset to zero.
6)  reset() -- markPos is still zero, so this appears to work.
7)  readLine() should return the first line again, but the previous
call to fill() wiped out the data, so it returns the second part of
the second line.

The fix is simple once looked for... here's a patch against the 6/18
snapshot:

diff -u -r libgcj-snapshot-1999-06-18.orig/libjava/java/io/BufferedReader.java libgcj-snapshot-1999-06-18/libjava/java/io/BufferedReader.java
--- libgcj-snapshot-1999-06-18.orig/libjava/java/io/BufferedReader.java Wed Jun
23 11:08:24 1999
+++ libgcj-snapshot-1999-06-18/libjava/java/io/BufferedReader.java      Wed Jun
23 12:53:29 1999
@@ -214,7 +214,7 @@

     if (markPos >= 0 && limit == buffer.length)
       markPos = -1;
-    if (markPos <= 0)
+    if (markPos < 0)
       pos = limit = 0;
     int count = in.read(buffer, limit, buffer.length - limit);
     if (count > 0)

-- 
John-Marc Chandonia (jmc@cmpharm.ucsf.edu)              We're everywhere...
Cohen Lab, University of California San Francisco       for your convenience.
http://yuri.harvard.edu/~jmc                                -- Psi Corps <*>


More information about the Java mailing list