Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/nio/channels/AsyncCloseAndInterrupt.java
38813 views
/*1* Copyright (c) 2002, 2016, 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* @bug 4460583 4470470 4840199 6419424 6710579 6596323 6824135 6395224 714291925* 815158226* @run main/othervm AsyncCloseAndInterrupt27* @summary Comprehensive test of asynchronous closing and interruption28* @author Mark Reinhold29*/3031import java.io.*;32import java.net.*;33import java.nio.channels.*;34import java.nio.ByteBuffer;35import java.util.ArrayList;36import java.util.List;37import java.util.concurrent.ExecutorService;38import java.util.concurrent.Executors;39import java.util.concurrent.ThreadFactory;40import java.util.concurrent.Callable;41import java.util.concurrent.Future;42import java.util.concurrent.TimeUnit;4344public class AsyncCloseAndInterrupt {4546static PrintStream log = System.err;4748static void sleep(int ms) {49try {50Thread.sleep(ms);51} catch (InterruptedException x) { }52}5354// Wildcard address localized to this machine -- Windoze doesn't allow55// connecting to a server socket that was previously bound to a true56// wildcard, namely new InetSocketAddress((InetAddress)null, 0).57//58private static InetSocketAddress wildcardAddress;596061// Server socket that blindly accepts all connections6263static ServerSocketChannel acceptor;6465private static void initAcceptor() throws IOException {66acceptor = ServerSocketChannel.open();67acceptor.socket().bind(wildcardAddress);6869Thread th = new Thread("Acceptor") {70public void run() {71try {72for (;;) {73SocketChannel sc = acceptor.accept();74}75} catch (IOException x) {76x.printStackTrace();77}78}79};8081th.setDaemon(true);82th.start();83}848586// Server socket that refuses all connections8788static ServerSocketChannel refuser;8990private static void initRefuser() throws IOException {91refuser = ServerSocketChannel.open();92refuser.bind(wildcardAddress, 1); // use minimum backlog93}9495// Dead pipe source and sink9697static Pipe.SourceChannel deadSource;98static Pipe.SinkChannel deadSink;99100private static void initPipes() throws IOException {101if (deadSource != null)102deadSource.close();103deadSource = Pipe.open().source();104if (deadSink != null)105deadSink.close();106deadSink = Pipe.open().sink();107}108109110// Files111112private static File fifoFile = null; // File that blocks on reads and writes113private static File diskFile = null; // Disk file114115private static void initFile() throws Exception {116117diskFile = File.createTempFile("aci", ".tmp");118diskFile.deleteOnExit();119FileChannel fc = new FileOutputStream(diskFile).getChannel();120buffer.clear();121if (fc.write(buffer) != buffer.capacity())122throw new RuntimeException("Cannot create disk file");123fc.close();124125if (TestUtil.onWindows()) {126log.println("WARNING: Cannot completely test FileChannels on Windows");127return;128}129fifoFile = new File("x.fifo");130if (fifoFile.exists()) {131if (!fifoFile.delete())132throw new IOException("Cannot delete existing fifo " + fifoFile);133}134Process p = Runtime.getRuntime().exec("mkfifo " + fifoFile);135if (p.waitFor() != 0)136throw new IOException("Error creating fifo");137new RandomAccessFile(fifoFile, "rw").close();138139}140141142// Channel factories143144static abstract class ChannelFactory {145private final String name;146ChannelFactory(String name) {147this.name = name;148}149public String toString() {150return name;151}152abstract InterruptibleChannel create() throws IOException;153}154155static ChannelFactory socketChannelFactory156= new ChannelFactory("SocketChannel") {157InterruptibleChannel create() throws IOException {158return SocketChannel.open();159}160};161162static ChannelFactory connectedSocketChannelFactory163= new ChannelFactory("SocketChannel") {164InterruptibleChannel create() throws IOException {165SocketAddress sa = acceptor.socket().getLocalSocketAddress();166return SocketChannel.open(sa);167}168};169170static ChannelFactory serverSocketChannelFactory171= new ChannelFactory("ServerSocketChannel") {172InterruptibleChannel create() throws IOException {173ServerSocketChannel ssc = ServerSocketChannel.open();174ssc.socket().bind(wildcardAddress);175return ssc;176}177};178179static ChannelFactory datagramChannelFactory180= new ChannelFactory("DatagramChannel") {181InterruptibleChannel create() throws IOException {182DatagramChannel dc = DatagramChannel.open();183InetAddress lb = InetAddress.getByName("127.0.0.1");184dc.bind(new InetSocketAddress(lb, 0));185dc.connect(new InetSocketAddress(lb, 80));186return dc;187}188};189190static ChannelFactory pipeSourceChannelFactory191= new ChannelFactory("Pipe.SourceChannel") {192InterruptibleChannel create() throws IOException {193// ## arrange to close sink194return Pipe.open().source();195}196};197198static ChannelFactory pipeSinkChannelFactory199= new ChannelFactory("Pipe.SinkChannel") {200InterruptibleChannel create() throws IOException {201// ## arrange to close source202return Pipe.open().sink();203}204};205206static ChannelFactory fifoFileChannelFactory207= new ChannelFactory("FileChannel") {208InterruptibleChannel create() throws IOException {209return new RandomAccessFile(fifoFile, "rw").getChannel();210}211};212213static ChannelFactory diskFileChannelFactory214= new ChannelFactory("FileChannel") {215InterruptibleChannel create() throws IOException {216return new RandomAccessFile(diskFile, "rw").getChannel();217}218};219220221// I/O operations222223static abstract class Op {224private final String name;225protected Op(String name) {226this.name = name;227}228abstract void doIO(InterruptibleChannel ich) throws IOException;229void setup() throws IOException { }230public String toString() { return name; }231}232233static ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 20);234235static ByteBuffer[] buffers = new ByteBuffer[] {236ByteBuffer.allocateDirect(1 << 19),237ByteBuffer.allocateDirect(1 << 19)238};239240static void clearBuffers() {241buffers[0].clear();242buffers[1].clear();243}244245static void show(Channel ch) {246log.print("Channel " + (ch.isOpen() ? "open" : "closed"));247if (ch.isOpen() && (ch instanceof SocketChannel)) {248SocketChannel sc = (SocketChannel)ch;249if (sc.socket().isInputShutdown())250log.print(", input shutdown");251if (sc.socket().isOutputShutdown())252log.print(", output shutdown");253}254log.println();255}256257static final Op READ = new Op("read") {258void doIO(InterruptibleChannel ich) throws IOException {259ReadableByteChannel rbc = (ReadableByteChannel)ich;260buffer.clear();261int n = rbc.read(buffer);262log.println("Read returned " + n);263show(rbc);264if (rbc.isOpen()265&& (n == -1)266&& (rbc instanceof SocketChannel)267&& ((SocketChannel)rbc).socket().isInputShutdown()) {268return;269}270throw new RuntimeException("Read succeeded");271}272};273274static final Op READV = new Op("readv") {275void doIO(InterruptibleChannel ich) throws IOException {276ScatteringByteChannel sbc = (ScatteringByteChannel)ich;277clearBuffers();278int n = (int)sbc.read(buffers);279log.println("Read returned " + n);280show(sbc);281if (sbc.isOpen()282&& (n == -1)283&& (sbc instanceof SocketChannel)284&& ((SocketChannel)sbc).socket().isInputShutdown()) {285return;286}287throw new RuntimeException("Read succeeded");288}289};290291static final Op RECEIVE = new Op("receive") {292void doIO(InterruptibleChannel ich) throws IOException {293DatagramChannel dc = (DatagramChannel)ich;294buffer.clear();295dc.receive(buffer);296show(dc);297throw new RuntimeException("Read succeeded");298}299};300301static final Op WRITE = new Op("write") {302void doIO(InterruptibleChannel ich) throws IOException {303304WritableByteChannel wbc = (WritableByteChannel)ich;305306SocketChannel sc = null;307if (wbc instanceof SocketChannel)308sc = (SocketChannel)wbc;309310int n = 0;311for (;;) {312buffer.clear();313int d = wbc.write(buffer);314n += d;315if (!wbc.isOpen())316break;317if ((sc != null) && sc.socket().isOutputShutdown())318break;319}320log.println("Wrote " + n + " bytes");321show(wbc);322}323};324325static final Op WRITEV = new Op("writev") {326void doIO(InterruptibleChannel ich) throws IOException {327328GatheringByteChannel gbc = (GatheringByteChannel)ich;329330SocketChannel sc = null;331if (gbc instanceof SocketChannel)332sc = (SocketChannel)gbc;333334int n = 0;335for (;;) {336clearBuffers();337int d = (int)gbc.write(buffers);338n += d;339if (!gbc.isOpen())340break;341if ((sc != null) && sc.socket().isOutputShutdown())342break;343}344log.println("Wrote " + n + " bytes");345show(gbc);346347}348};349350static final Op CONNECT = new Op("connect") {351void setup() {352waitPump("connect waiting for pumping refuser ...");353}354void doIO(InterruptibleChannel ich) throws IOException {355SocketChannel sc = (SocketChannel)ich;356if (sc.connect(refuser.socket().getLocalSocketAddress()))357throw new RuntimeException("Connection succeeded");358throw new RuntimeException("Connection did not block");359}360};361362static final Op FINISH_CONNECT = new Op("finishConnect") {363void setup() {364waitPump("finishConnect waiting for pumping refuser ...");365}366void doIO(InterruptibleChannel ich) throws IOException {367SocketChannel sc = (SocketChannel)ich;368sc.configureBlocking(false);369SocketAddress sa = refuser.socket().getLocalSocketAddress();370if (sc.connect(sa))371throw new RuntimeException("Connection succeeded");372sc.configureBlocking(true);373if (sc.finishConnect())374throw new RuntimeException("Connection succeeded");375throw new RuntimeException("Connection did not block");376}377};378379static final Op ACCEPT = new Op("accept") {380void doIO(InterruptibleChannel ich) throws IOException {381ServerSocketChannel ssc = (ServerSocketChannel)ich;382ssc.accept();383throw new RuntimeException("Accept succeeded");384}385};386387// Use only with diskFileChannelFactory388static final Op TRANSFER_TO = new Op("transferTo") {389void doIO(InterruptibleChannel ich) throws IOException {390FileChannel fc = (FileChannel)ich;391long n = fc.transferTo(0, fc.size(), deadSink);392log.println("Transferred " + n + " bytes");393show(fc);394}395};396397// Use only with diskFileChannelFactory398static final Op TRANSFER_FROM = new Op("transferFrom") {399void doIO(InterruptibleChannel ich) throws IOException {400FileChannel fc = (FileChannel)ich;401long n = fc.transferFrom(deadSource, 0, 1 << 20);402log.println("Transferred " + n + " bytes");403show(fc);404}405};406407408409// Test modes410411static final int TEST_PREINTR = 0; // Interrupt thread before I/O412static final int TEST_INTR = 1; // Interrupt thread during I/O413static final int TEST_CLOSE = 2; // Close channel during I/O414static final int TEST_SHUTI = 3; // Shutdown input during I/O415static final int TEST_SHUTO = 4; // Shutdown output during I/O416417static final String[] testName = new String[] {418"pre-interrupt", "interrupt", "close",419"shutdown-input", "shutdown-output"420};421422423static class Tester extends TestThread {424425private InterruptibleChannel ch;426private Op op;427private int test;428volatile boolean ready = false;429430protected Tester(ChannelFactory cf, InterruptibleChannel ch,431Op op, int test)432{433super(cf + "/" + op + "/" + testName[test]);434this.ch = ch;435this.op = op;436this.test = test;437}438439@SuppressWarnings("fallthrough")440private void caught(Channel ch, IOException x) {441String xn = x.getClass().getName();442switch (test) {443444case TEST_PREINTR:445case TEST_INTR:446if (!xn.equals("java.nio.channels.ClosedByInterruptException"))447throw new RuntimeException("Wrong exception thrown: " + x);448break;449450case TEST_CLOSE:451case TEST_SHUTO:452if (!xn.equals("java.nio.channels.AsynchronousCloseException"))453throw new RuntimeException("Wrong exception thrown: " + x);454break;455456case TEST_SHUTI:457if (TestUtil.onWindows())458break;459// FALL THROUGH460461default:462throw new Error(x);463}464465if (ch.isOpen()) {466if (test == TEST_SHUTO) {467SocketChannel sc = (SocketChannel)ch;468if (!sc.socket().isOutputShutdown())469throw new RuntimeException("Output not shutdown");470} else if ((test == TEST_INTR) && (op == TRANSFER_FROM)) {471// Let this case pass -- CBIE applies to other channel472} else {473throw new RuntimeException("Channel still open");474}475}476477log.println("Thrown as expected: " + x);478}479480final void go() throws Exception {481if (test == TEST_PREINTR)482Thread.currentThread().interrupt();483ready = true;484try {485op.doIO(ch);486} catch (ClosedByInterruptException x) {487caught(ch, x);488} catch (AsynchronousCloseException x) {489caught(ch, x);490} finally {491ch.close();492}493}494495}496497private static volatile boolean pumpDone = false;498private static volatile boolean pumpReady = false;499500private static void waitPump(String msg){501log.println(msg);502while (!pumpReady){503sleep(200);504}505log.println(msg + " done");506}507508// Create a pump thread dedicated to saturate refuser's connection backlog509private static Future<Integer> pumpRefuser(ExecutorService pumperExecutor) {510511Callable<Integer> pumpTask = new Callable<Integer>() {512513@Override514public Integer call() throws IOException {515// Can't reliably saturate connection backlog on Windows Server editions516assert !TestUtil.onWindows();517log.println("Start pumping refuser ...");518List<SocketChannel> refuserClients = new ArrayList<>();519520// Saturate the refuser's connection backlog so that further connection521// attempts will be blocked522pumpReady = false;523while (!pumpDone) {524SocketChannel sc = SocketChannel.open();525sc.configureBlocking(false);526boolean connected = sc.connect(refuser.socket().getLocalSocketAddress());527528// Assume that the connection backlog is saturated if a529// client cannot connect to the refuser within 50 milliseconds530long start = System.currentTimeMillis();531while (!pumpReady && !connected532&& (System.currentTimeMillis() - start < 50)) {533connected = sc.finishConnect();534}535536if (connected) {537// Retain so that finalizer doesn't close538refuserClients.add(sc);539} else {540sc.close();541pumpReady = true;542}543}544545for (SocketChannel sc : refuserClients) {546sc.close();547}548refuser.close();549550log.println("Stop pumping refuser ...");551return refuserClients.size();552}553};554555return pumperExecutor.submit(pumpTask);556}557558// Test559static void test(ChannelFactory cf, Op op, int test)560throws Exception561{562log.println();563initPipes();564InterruptibleChannel ch = cf.create();565Tester t = new Tester(cf, ch, op, test);566log.println(t);567op.setup();568t.start();569do {570sleep(50);571} while (!t.ready);572573switch (test) {574575case TEST_INTR:576t.interrupt();577break;578579case TEST_CLOSE:580ch.close();581break;582583case TEST_SHUTI:584if (TestUtil.onWindows()) {585log.println("WARNING: Asynchronous shutdown not working on Windows");586ch.close();587} else {588((SocketChannel)ch).socket().shutdownInput();589}590break;591592case TEST_SHUTO:593if (TestUtil.onWindows()) {594log.println("WARNING: Asynchronous shutdown not working on Windows");595ch.close();596} else {597((SocketChannel)ch).socket().shutdownOutput();598}599break;600601default:602break;603}604605t.finishAndThrow(500);606}607608609static void test(ChannelFactory cf, Op op) throws Exception {610// Test INTR cases before PREINTER cases since sometimes611// interrupted threads can't load classes612test(cf, op, TEST_INTR);613test(cf, op, TEST_PREINTR);614615// Bugs, see FileChannelImpl for details616if (op == TRANSFER_FROM) {617log.println("WARNING: transferFrom/close not tested");618return;619}620if ((op == TRANSFER_TO) && !TestUtil.onWindows()) {621log.println("WARNING: transferTo/close not tested");622return;623}624625test(cf, op, TEST_CLOSE);626}627628static void test(ChannelFactory cf)629throws Exception630{631InterruptibleChannel ch = cf.create(); // Sample channel632ch.close();633634if (ch instanceof ReadableByteChannel) {635test(cf, READ);636if (ch instanceof SocketChannel)637test(cf, READ, TEST_SHUTI);638}639640if (ch instanceof ScatteringByteChannel) {641test(cf, READV);642if (ch instanceof SocketChannel)643test(cf, READV, TEST_SHUTI);644}645646if (ch instanceof DatagramChannel) {647test(cf, RECEIVE);648649// Return here: We can't effectively test writes since, if they650// block, they do so only for a fleeting moment unless the network651// interface is overloaded.652return;653654}655656if (ch instanceof WritableByteChannel) {657test(cf, WRITE);658if (ch instanceof SocketChannel)659test(cf, WRITE, TEST_SHUTO);660}661662if (ch instanceof GatheringByteChannel) {663test(cf, WRITEV);664if (ch instanceof SocketChannel)665test(cf, WRITEV, TEST_SHUTO);666}667668}669670public static void main(String[] args) throws Exception {671672wildcardAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);673initAcceptor();674if (!TestUtil.onWindows())675initRefuser();676initPipes();677initFile();678679if (TestUtil.onWindows()) {680log.println("WARNING: Cannot test FileChannel transfer operations"681+ " on Windows");682} else {683test(diskFileChannelFactory, TRANSFER_TO);684test(diskFileChannelFactory, TRANSFER_FROM);685}686if (fifoFile != null)687test(fifoFileChannelFactory);688689// Testing positional file reads and writes is impractical: It requires690// access to a large file soft-mounted via NFS, and even then isn't691// completely guaranteed to work.692//693// Testing map is impractical and arguably unnecessary: It's694// unclear under what conditions mmap(2) will actually block.695696test(connectedSocketChannelFactory);697698if (TestUtil.onWindows()) {699log.println("WARNING Cannot reliably test connect/finishConnect"700+ " operations on Windows");701} else {702// Only the following tests need refuser's connection backlog703// to be saturated704ExecutorService pumperExecutor =705Executors.newSingleThreadExecutor(706new ThreadFactory() {707708@Override709public Thread newThread(Runnable r) {710Thread t = new Thread(r);711t.setDaemon(true);712t.setName("Pumper");713return t;714}715});716717pumpDone = false;718try {719Future<Integer> pumpFuture = pumpRefuser(pumperExecutor);720waitPump("\nWait for initial Pump");721722test(socketChannelFactory, CONNECT);723test(socketChannelFactory, FINISH_CONNECT);724725pumpDone = true;726Integer newConn = pumpFuture.get(30, TimeUnit.SECONDS);727log.println("Pump " + newConn + " connections.");728} finally {729pumperExecutor.shutdown();730}731}732733test(serverSocketChannelFactory, ACCEPT);734test(datagramChannelFactory);735test(pipeSourceChannelFactory);736test(pipeSinkChannelFactory);737}738}739740741