< prev index next >

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

Print this page
@@ -369,13 +369,48 @@
       * available(), reset(), or skip() invocations will throw an IOException.
       * Closing a previously closed stream has no effect.
       *
       * @throws     IOException  if an I/O error occurs.
       */
-     public synchronized void close() throws IOException {
-         if (in == null)
-             return;
-         in.close();
-         in = null;
-         buf = null;
+     public void close() throws IOException {
+         synchronized (this) {
+             waitIfClosing();
+             if (in == null) {
+                 // closed by another thread
+                 return;
+             }
+             closing = true;
+         }
+         try {
+             in.close();
+         } finally {
+             in = null;
+             buf = null;
+ 
+             // notify anyone waiting for close
+             closing = false;
+             synchronized (this) {
+                 notifyAll();
+             }
+         }
+     }
+ 
+     private volatile boolean closing;
+ 
+     private void waitIfClosing() {
+         assert Thread.holdsLock(this);
+         boolean interrupted = false;
+         try {
+             while (closing) {
+                 try {
+                     wait();
+                 } catch (InterruptedException e) {
+                     interrupted = true;
+                 }
+             }
+         } finally {
+             if (interrupted) {
+                 Thread.currentThread().interrupt();
+             }
+         }
      }
  }
< prev index next >