Path: blob/master/test/micro/org/openjdk/bench/java/net/SocketChannelReadWrite.java
41161 views
/*1* Copyright (c) 2014, 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*/22package org.openjdk.bench.java.net;2324import java.io.IOException;25import java.net.InetAddress;26import java.net.InetSocketAddress;27import java.nio.ByteBuffer;28import java.nio.channels.ClosedChannelException;29import java.nio.channels.ServerSocketChannel;30import java.nio.channels.SocketChannel;31import java.util.concurrent.TimeUnit;3233import org.openjdk.jmh.annotations.*;3435/**36* Tests the overheads of I/O API.37* This test is known to depend heavily on network conditions and paltform.38*/39@BenchmarkMode(Mode.Throughput)40@OutputTimeUnit(TimeUnit.MILLISECONDS)41@State(Scope.Thread)42public class SocketChannelReadWrite {4344private ServerSocketChannel ssc;45private SocketChannel s1, s2;46private ReadThread rt;47private ByteBuffer bb = ByteBuffer.allocate(1);4849@Setup(Level.Trial)50public void beforeRun() throws IOException {51InetAddress iaddr = InetAddress.getLocalHost();5253ssc = ServerSocketChannel.open().bind(null);54s1 = SocketChannel.open(new InetSocketAddress(iaddr, ssc.socket().getLocalPort()));55s2 = ssc.accept();5657rt = new ReadThread(s2);58rt.start();5960bb.put((byte) 47);61bb.flip();62}6364@TearDown(Level.Trial)65public void afterRun() throws IOException, InterruptedException {66s1.close();67s2.close();68ssc.close();69rt.join();70}7172@Benchmark73public void test() throws IOException {74s1.write(bb);75bb.flip();76}7778static class ReadThread extends Thread {79private SocketChannel sc;8081public ReadThread(SocketChannel s2) {82this.sc = s2;83}8485public void run() {86try {87ByteBuffer bb = ByteBuffer.allocate(1);88while (sc.read(bb) > 0) {89bb.flip();90}91} catch (ClosedChannelException ex) {92// shutdown time93} catch (IOException e) {94e.printStackTrace();95}96}97}9899}100101102