Path: blob/master/test/jdk/java/net/Socket/asyncClose/Socket_getInputStream_read.java
41153 views
/*1* Copyright (c) 2001, 2019, 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/*24* Tests that a thread blocked in Socket.getInputStream().read()25* throws a SocketException if the socket is asynchronously closed.26*/27import java.net.*;28import java.io.*;29import java.util.concurrent.CountDownLatch;3031public class Socket_getInputStream_read extends AsyncCloseTest implements Runnable {32private final Socket s;33private final int timeout;34private final CountDownLatch latch;3536public Socket_getInputStream_read() {37this(0);38}3940public Socket_getInputStream_read(int timeout) {41this.timeout = timeout;42latch = new CountDownLatch(1);43s = new Socket();44}4546public String description() {47String s = "Socket.getInputStream().read()";48if (timeout > 0) {49s += " (with timeout)";50}51return s;52}5354public void run() {55try {56InputStream in = s.getInputStream();57if (timeout > 0) {58s.setSoTimeout(timeout);59}60latch.countDown();61int n = in.read();62failed("Socket.getInputStream().read() returned unexpectedly!!");63} catch (SocketException se) {64if (latch.getCount() != 1) {65closed();66}67} catch (Exception e) {68failed(e.getMessage());69} finally {70if (latch.getCount() == 1) {71latch.countDown();72}73}74}7576public AsyncCloseTest go() {77try {78InetAddress lh = InetAddress.getLocalHost();79ServerSocket ss = new ServerSocket(0, 0, lh);80s.connect( new InetSocketAddress(lh, ss.getLocalPort()) );81Socket s2 = ss.accept();82Thread thr = new Thread(this);83thr.start();84latch.await();85Thread.sleep(5000); //sleep, so Socket.getInputStream().read() can block86s.close();87thr.join();8889if (isClosed()) {90return passed();91} else {92return failed("Socket.getInputStream().read() wasn't preempted");93}94} catch (Exception x) {95failed(x.getMessage());96throw new RuntimeException(x);97}98}99}100101102