< prev index next >

src/java.base/share/classes/java/io/BufferedInputStream.java

Print this page
rev 13993 : 8153334: Replace BufferedInputStreams use of AtomicReferenceFieldUpdater with Unsafe
Reviewed-by: TBD


   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
  28 
  29 /**
  30  * A <code>BufferedInputStream</code> adds
  31  * functionality to another input stream-namely,
  32  * the ability to buffer the input and to
  33  * support the <code>mark</code> and <code>reset</code>
  34  * methods. When  the <code>BufferedInputStream</code>
  35  * is created, an internal buffer array is
  36  * created. As bytes  from the stream are read
  37  * or skipped, the internal buffer is refilled
  38  * as necessary  from the contained input stream,
  39  * many bytes at a time. The <code>mark</code>
  40  * operation  remembers a point in the input
  41  * stream and the <code>reset</code> operation
  42  * causes all the  bytes read since the most
  43  * recent <code>mark</code> operation to be
  44  * reread before new bytes are  taken from
  45  * the contained input stream.
  46  *
  47  * @author  Arthur van Hoff


  51 class BufferedInputStream extends FilterInputStream {
  52 
  53     private static int DEFAULT_BUFFER_SIZE = 8192;
  54 
  55     /**
  56      * The maximum size of array to allocate.
  57      * Some VMs reserve some header words in an array.
  58      * Attempts to allocate larger arrays may result in
  59      * OutOfMemoryError: Requested array size exceeds VM limit
  60      */
  61     private static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
  62 
  63     /**
  64      * The internal buffer array where the data is stored. When necessary,
  65      * it may be replaced by another array of
  66      * a different size.
  67      */
  68     protected volatile byte buf[];
  69 
  70     /**
  71      * Atomic updater to provide compareAndSet for buf. This is
  72      * necessary because closes can be asynchronous. We use nullness
  73      * of buf[] as primary indicator that this stream is closed. (The
  74      * "in" field is also nulled out on close.)
  75      */
  76     private static final
  77         AtomicReferenceFieldUpdater<BufferedInputStream, byte[]> bufUpdater =
  78         AtomicReferenceFieldUpdater.newUpdater
  79         (BufferedInputStream.class,  byte[].class, "buf");







  80 
  81     /**
  82      * The index one greater than the index of the last valid byte in
  83      * the buffer.
  84      * This value is always
  85      * in the range <code>0</code> through <code>buf.length</code>;
  86      * elements <code>buf[0]</code>  through <code>buf[count-1]
  87      * </code>contain buffered input data obtained
  88      * from the underlying  input stream.
  89      */
  90     protected int count;
  91 
  92     /**
  93      * The current position in the buffer. This is the index of the next
  94      * character to be read from the <code>buf</code> array.
  95      * <p>
  96      * This value is always in the range <code>0</code>
  97      * through <code>count</code>. If it is less
  98      * than <code>count</code>, then  <code>buf[pos]</code>
  99      * is the next byte to be supplied as input;


 215         if (markpos < 0)
 216             pos = 0;            /* no mark: throw away the buffer */
 217         else if (pos >= buffer.length)  /* no room left in buffer */
 218             if (markpos > 0) {  /* can throw away early part of the buffer */
 219                 int sz = pos - markpos;
 220                 System.arraycopy(buffer, markpos, buffer, 0, sz);
 221                 pos = sz;
 222                 markpos = 0;
 223             } else if (buffer.length >= marklimit) {
 224                 markpos = -1;   /* buffer got too big, invalidate mark */
 225                 pos = 0;        /* drop buffer contents */
 226             } else if (buffer.length >= MAX_BUFFER_SIZE) {
 227                 throw new OutOfMemoryError("Required array size too large");
 228             } else {            /* grow buffer */
 229                 int nsz = (pos <= MAX_BUFFER_SIZE - pos) ?
 230                         pos * 2 : MAX_BUFFER_SIZE;
 231                 if (nsz > marklimit)
 232                     nsz = marklimit;
 233                 byte nbuf[] = new byte[nsz];
 234                 System.arraycopy(buffer, 0, nbuf, 0, pos);
 235                 if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
 236                     // Can't replace buf if there was an async close.
 237                     // Note: This would need to be changed if fill()
 238                     // is ever made accessible to multiple threads.
 239                     // But for now, the only way CAS can fail is via close.
 240                     // assert buf == null;
 241                     throw new IOException("Stream closed");
 242                 }
 243                 buffer = nbuf;
 244             }
 245         count = pos;
 246         int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
 247         if (n > 0)
 248             count = n + pos;
 249     }
 250 
 251     /**
 252      * See
 253      * the general contract of the <code>read</code>
 254      * method of <code>InputStream</code>.
 255      *


 459      *          the <code>mark</code> and <code>reset</code> methods.
 460      * @see     java.io.InputStream#mark(int)
 461      * @see     java.io.InputStream#reset()
 462      */
 463     public boolean markSupported() {
 464         return true;
 465     }
 466 
 467     /**
 468      * Closes this input stream and releases any system resources
 469      * associated with the stream.
 470      * Once the stream has been closed, further read(), available(), reset(),
 471      * or skip() invocations will throw an IOException.
 472      * Closing a previously closed stream has no effect.
 473      *
 474      * @exception  IOException  if an I/O error occurs.
 475      */
 476     public void close() throws IOException {
 477         byte[] buffer;
 478         while ( (buffer = buf) != null) {
 479             if (bufUpdater.compareAndSet(this, buffer, null)) {
 480                 InputStream input = in;
 481                 in = null;
 482                 if (input != null)
 483                     input.close();
 484                 return;
 485             }
 486             // Else retry in case a new buf was CASed in fill()
 487         }
 488     }
 489 }


   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;

  27 
  28 /**
  29  * A <code>BufferedInputStream</code> adds
  30  * functionality to another input stream-namely,
  31  * the ability to buffer the input and to
  32  * support the <code>mark</code> and <code>reset</code>
  33  * methods. When  the <code>BufferedInputStream</code>
  34  * is created, an internal buffer array is
  35  * created. As bytes  from the stream are read
  36  * or skipped, the internal buffer is refilled
  37  * as necessary  from the contained input stream,
  38  * many bytes at a time. The <code>mark</code>
  39  * operation  remembers a point in the input
  40  * stream and the <code>reset</code> operation
  41  * causes all the  bytes read since the most
  42  * recent <code>mark</code> operation to be
  43  * reread before new bytes are  taken from
  44  * the contained input stream.
  45  *
  46  * @author  Arthur van Hoff


  50 class BufferedInputStream extends FilterInputStream {
  51 
  52     private static int DEFAULT_BUFFER_SIZE = 8192;
  53 
  54     /**
  55      * The maximum size of array to allocate.
  56      * Some VMs reserve some header words in an array.
  57      * Attempts to allocate larger arrays may result in
  58      * OutOfMemoryError: Requested array size exceeds VM limit
  59      */
  60     private static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
  61 
  62     /**
  63      * The internal buffer array where the data is stored. When necessary,
  64      * it may be replaced by another array of
  65      * a different size.
  66      */
  67     protected volatile byte buf[];
  68 
  69     /**
  70      * Get Unsafe and offset of buf to provide compareAndSet functionality.
  71      * This is necessary because closes can be asynchronous. We use nullness
  72      * of buf[] as primary indicator that this stream is closed. (The
  73      * "in" field is also nulled out on close.)
  74      */
  75     private static final jdk.internal.misc.Unsafe U =
  76             jdk.internal.misc.Unsafe.getUnsafe();
  77     private static final long BUF_OFFSET;
  78     static {
  79         try {
  80             BUF_OFFSET = U.objectFieldOffset
  81                 (BufferedInputStream.class.getDeclaredField("buf"));
  82         } catch (ReflectiveOperationException e) {
  83             throw new Error(e);
  84         }
  85     }
  86 
  87     /**
  88      * The index one greater than the index of the last valid byte in
  89      * the buffer.
  90      * This value is always
  91      * in the range <code>0</code> through <code>buf.length</code>;
  92      * elements <code>buf[0]</code>  through <code>buf[count-1]
  93      * </code>contain buffered input data obtained
  94      * from the underlying  input stream.
  95      */
  96     protected int count;
  97 
  98     /**
  99      * The current position in the buffer. This is the index of the next
 100      * character to be read from the <code>buf</code> array.
 101      * <p>
 102      * This value is always in the range <code>0</code>
 103      * through <code>count</code>. If it is less
 104      * than <code>count</code>, then  <code>buf[pos]</code>
 105      * is the next byte to be supplied as input;


 221         if (markpos < 0)
 222             pos = 0;            /* no mark: throw away the buffer */
 223         else if (pos >= buffer.length)  /* no room left in buffer */
 224             if (markpos > 0) {  /* can throw away early part of the buffer */
 225                 int sz = pos - markpos;
 226                 System.arraycopy(buffer, markpos, buffer, 0, sz);
 227                 pos = sz;
 228                 markpos = 0;
 229             } else if (buffer.length >= marklimit) {
 230                 markpos = -1;   /* buffer got too big, invalidate mark */
 231                 pos = 0;        /* drop buffer contents */
 232             } else if (buffer.length >= MAX_BUFFER_SIZE) {
 233                 throw new OutOfMemoryError("Required array size too large");
 234             } else {            /* grow buffer */
 235                 int nsz = (pos <= MAX_BUFFER_SIZE - pos) ?
 236                         pos * 2 : MAX_BUFFER_SIZE;
 237                 if (nsz > marklimit)
 238                     nsz = marklimit;
 239                 byte nbuf[] = new byte[nsz];
 240                 System.arraycopy(buffer, 0, nbuf, 0, pos);
 241                 if (!U.compareAndSwapObject(this, BUF_OFFSET, buffer, nbuf)) {
 242                     // Can't replace buf if there was an async close.
 243                     // Note: This would need to be changed if fill()
 244                     // is ever made accessible to multiple threads.
 245                     // But for now, the only way CAS can fail is via close.
 246                     // assert buf == null;
 247                     throw new IOException("Stream closed");
 248                 }
 249                 buffer = nbuf;
 250             }
 251         count = pos;
 252         int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
 253         if (n > 0)
 254             count = n + pos;
 255     }
 256 
 257     /**
 258      * See
 259      * the general contract of the <code>read</code>
 260      * method of <code>InputStream</code>.
 261      *


 465      *          the <code>mark</code> and <code>reset</code> methods.
 466      * @see     java.io.InputStream#mark(int)
 467      * @see     java.io.InputStream#reset()
 468      */
 469     public boolean markSupported() {
 470         return true;
 471     }
 472 
 473     /**
 474      * Closes this input stream and releases any system resources
 475      * associated with the stream.
 476      * Once the stream has been closed, further read(), available(), reset(),
 477      * or skip() invocations will throw an IOException.
 478      * Closing a previously closed stream has no effect.
 479      *
 480      * @exception  IOException  if an I/O error occurs.
 481      */
 482     public void close() throws IOException {
 483         byte[] buffer;
 484         while ( (buffer = buf) != null) {
 485             if (U.compareAndSwapObject(this, BUF_OFFSET, buffer, null)) {
 486                 InputStream input = in;
 487                 in = null;
 488                 if (input != null)
 489                     input.close();
 490                 return;
 491             }
 492             // Else retry in case a new buf was CASed in fill()
 493         }
 494     }
 495 }
< prev index next >