Path: blob/master/test/jdk/java/nio/channels/SocketChannel/CloseDuringWrite.java
41154 views
/*1* Copyright (c) 2012, 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/* @test24* @summary Test asynchronous close during a blocking write25* @key randomness26*/2728import java.io.Closeable;29import java.io.IOException;30import java.nio.ByteBuffer;31import java.nio.channels.*;32import java.net.*;33import java.util.concurrent.*;34import java.util.Random;3536public class CloseDuringWrite {3738static final Random rand = new Random();3940/**41* A task that closes a Closeable42*/43static class Closer implements Callable<Void> {44final Closeable c;45Closer(Closeable c) {46this.c = c;47}48public Void call() throws IOException {49c.close();50return null;51}52}5354public static void main(String[] args) throws Exception {55ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();56try {57try (ServerSocketChannel ssc = ServerSocketChannel.open()) {58ssc.bind(new InetSocketAddress(0));59InetAddress lh = InetAddress.getLocalHost();60int port = ssc.socket().getLocalPort();61SocketAddress sa = new InetSocketAddress(lh, port);6263ByteBuffer bb = ByteBuffer.allocate(2*1024*1024);6465for (int i=0; i<20; i++) {66try (SocketChannel source = SocketChannel.open(sa);67SocketChannel sink = ssc.accept())68{69// schedule channel to be closed70Closer c = new Closer(source);71int when = 1000 + rand.nextInt(2000);72Future<Void> result = pool.schedule(c, when, TimeUnit.MILLISECONDS);7374// the write should either succeed or else throw a75// ClosedChannelException (more likely an76// AsynchronousCloseException)77try {78for (;;) {79int limit = rand.nextInt(bb.capacity());80bb.position(0);81bb.limit(limit);82int n = source.write(bb);83System.out.format("wrote %d, expected %d%n", n, limit);84}85} catch (ClosedChannelException expected) {86System.out.println(expected + " (expected)");87} finally {88result.get();89}90}91}92}93} finally {94pool.shutdown();95}96}97}9899100