--- /dev/null Tue Nov 9 09:07:33 2010 +++ new/test/java/nio/channels/FileChannel/ClosedByInterrupt.java Tue Nov 9 09:07:32 2010 @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 6979009 + * @summary Ensure ClosedByInterruptException is thrown when I/O operation + * interrupted by Thread.interrupt + */ + +import java.io.*; +import java.util.Random; +import java.nio.ByteBuffer; +import java.nio.channels.*; + +public class ClosedByInterrupt { + + static final int K = 1024; + static final Random rand = new Random(); + + static volatile boolean failed; + + public static void main(String[] args) throws Exception { + File f = File.createTempFile("blah", null); + f.deleteOnExit(); + + // create 1MB file. + byte[] b = new byte[K*K]; + rand.nextBytes(b); + ByteBuffer bb = ByteBuffer.wrap(b); + try (FileChannel fc = new FileOutputStream(f).getChannel()) { + while (bb.hasRemaining()) + fc.write(bb); + } + + // test with 1-8 concurrent threads + for (int i=1; i<=8; i++) { + System.out.format("%d thread(s)%n", i); + test(f, i); + if (failed) + break; + } + } + + /** + * Starts "nThreads" that do I/O on the given file concurrently. Continuously + * interrupts one of the threads to cause the file to be closed and + * ClosedByInterruptException to be thrown. The other threads should "fail" with + * ClosedChannelException (or the more specific AsynchronousCloseException). + */ + static void test(File f, int nThreads) throws Exception { + try (FileChannel fc = new RandomAccessFile(f, "rwd").getChannel()) { + Thread[] threads = new Thread[nThreads]; + + // start threads + for (int i=0; i