Path: blob/master/test/jdk/java/nio/channels/Pipe/SelectPipe.java
41152 views
/*1* Copyright (c) 2002, 2010, 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 selection of ready pipe25* @key randomness26*/2728import java.io.*;29import java.nio.ByteBuffer;30import java.nio.channels.*;31import java.nio.channels.spi.SelectorProvider;32import java.util.Random;3334/**35* Testing PipeChannel36*/37public class SelectPipe {3839private static Random generator = new Random();4041public static void main(String[] args) throws Exception {4243SelectorProvider sp = SelectorProvider.provider();44Selector selector = Selector.open();45Pipe p = sp.openPipe();46Pipe.SinkChannel sink = p.sink();47Pipe.SourceChannel source = p.source();4849source.configureBlocking(false);50sink.configureBlocking(false);5152SelectionKey readkey = source.register(selector, SelectionKey.OP_READ);53SelectionKey writekey = sink.register(selector, SelectionKey.OP_WRITE);5455ByteBuffer outgoingdata = ByteBuffer.allocateDirect(10);56byte[] someBytes = new byte[10];57generator.nextBytes(someBytes);58outgoingdata.put(someBytes);59outgoingdata.flip();6061int totalWritten = 0;62while (totalWritten < 10) {63int written = sink.write(outgoingdata);64if (written < 0)65throw new Exception("Write failed");66totalWritten += written;67}6869if (selector.select(1000) == 0) {70throw new Exception("test failed");71}7273ByteBuffer incomingdata = ByteBuffer.allocateDirect(10);74int totalRead = 0;75do {76int bytesRead = source.read(incomingdata);77if (bytesRead > 0)78totalRead += bytesRead;79} while(totalRead < 10);8081sink.close();82source.close();83selector.close();8485for(int i=0; i<10; i++)86if (outgoingdata.get(i) != incomingdata.get(i))87throw new Exception("Pipe failed");88}89}909192