Path: blob/master/test/jdk/java/io/BufferedWriter/Cleanup.java
41152 views
/*1* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 626637726* @summary Test to ensure that BufferedWriter releases27* resources if flushing the buffer results in an28* exception during a call to close().29*/3031import java.io.*;3233public class Cleanup extends Thread {3435static PipedWriter w;36static PipedReader r;37static boolean isWriterClosed = false;3839public void run() {40try {41System.out.println("Reader reading...");42r.read(new char[2048], 0, 2048);4344// Close abruptly before reading all the bytes45System.out.println("Reader closing stream...");46r.close();4748Thread.sleep(3000);49} catch (Throwable e) {50System.out.println("Reader exception:");51e.printStackTrace();52}53}5455public static void main(String args[]) throws Exception {56r = new PipedReader();57w = new PipedWriter(r);5859Cleanup reader = new Cleanup();60reader.start();6162BufferedWriter bw = new BufferedWriter(w);6364boolean isWriterClosed = false;6566try {67System.out.println("Writer started.");6869for (int i = 0; i < 3; i++) {70bw.write(new char[1024], 0, (1024));71}7273// This call to close() will raise an exception during74// flush() since the reader is already closed75bw.close();7677} catch (Throwable e) {78try {79e.printStackTrace();8081// Make sure that the BufferedWriter releases the resources82// A write to a properly closed Writer should raise an exception83bw.write('a');8485} catch (IOException ex) {86ex.printStackTrace();87isWriterClosed = true;88}89} finally {90System.out.println("Writer done.");91reader.join();92if (!isWriterClosed) {93throw new Exception("BufferedWriter is not closed properly");94}95}96}97}9899100