1/* 2 * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24/* 25 * Tests that a thread blocked in DatagramSocket.receive 26 * throws a SocketException if the socket is asynchronously closed. 27 */ 28import java.net.*; 29import java.util.concurrent.CountDownLatch; 30 31public class DatagramSocket_receive extends AsyncCloseTest implements Runnable { 32 private final DatagramSocket s; 33 private final int timeout; 34 private final CountDownLatch latch; 35 36 public DatagramSocket_receive() throws SocketException { 37 this(0); 38 } 39 40 public DatagramSocket_receive(int timeout) throws SocketException { 41 this.timeout = timeout; 42 latch = new CountDownLatch(1); 43 s = new DatagramSocket(); 44 } 45 46 public String description() { 47 String s = "DatagramSocket.receive(DatagramPacket)"; 48 if (timeout > 0) { 49 s += " (timeout specified)"; 50 } 51 return s; 52 } 53 54 public void run() { 55 try { 56 byte b[] = new byte[1024]; 57 DatagramPacket p = new DatagramPacket(b, b.length); 58 if (timeout > 0) { 59 s.setSoTimeout(timeout); 60 } 61 latch.countDown(); 62 s.receive(p); 63 failed("DatagramSocket.receive(DatagramPacket) returned unexpectly!!"); 64 } catch (SocketException se) { 65 if (latch.getCount() != 1) { 66 closed(); 67 } 68 } catch (Exception e) { 69 failed(e.getMessage()); 70 } finally { 71 if (latch.getCount() == 1) { 72 latch.countDown(); 73 } 74 } 75 } 76 77 public AsyncCloseTest go() { 78 try { 79 Thread thr = new Thread(this); 80 thr.start(); 81 latch.await(); 82 Thread.sleep(5000); //sleep, so receive(DatagramPacket) can block 83 s.close(); 84 thr.join(); 85 86 if (isClosed()) { 87 return passed(); 88 } else { 89 return failed("DatagramSocket.receive(DatagramPacket) wasn't preempted"); 90 } 91 } catch (Exception x) { 92 failed(x.getMessage()); 93 throw new RuntimeException(x); 94 } 95 } 96} 97