< prev index next >

test/jdk/java/nio/channels/DatagramChannel/InterruptibleOrNot.java

Print this page

  1 /*
  2  * Copyright (c) 2019, 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  * @test
 26  * @bug 8236246
 27  * @modules java.base/sun.nio.ch
 28  * @run testng InterruptibleOrNot
 29  * @summary Test SelectorProviderImpl.openDatagramChannel(boolean) to create
 30  *     DatagramChannel objects that optionally support interrupt
 31  */
 32 
 33 import java.io.Closeable;
 34 import java.io.IOException;
 35 import java.net.InetAddress;
 36 import java.net.InetSocketAddress;
 37 import java.net.SocketAddress;
 38 import java.nio.ByteBuffer;
 39 import java.nio.channels.AsynchronousCloseException;
 40 import java.nio.channels.ClosedByInterruptException;
 41 import java.nio.channels.DatagramChannel;
 42 import java.time.Duration;
 43 import java.util.concurrent.Executors;
 44 import java.util.concurrent.Future;
 45 import java.util.concurrent.ScheduledExecutorService;
 46 import java.util.concurrent.TimeUnit;
 47 import sun.nio.ch.DefaultSelectorProvider;
 48 
 49 import org.testng.annotations.Test;
 50 import static org.testng.Assert.*;


 51 
 52 @Test
 53 public class InterruptibleOrNot {


 54 
 55     public void testInterruptBeforeInterruptibleReceive() throws Exception {
 56         testInterruptBeforeReceive(true);
 57     }
 58 
 59     public void testInterruptDuringInterruptibleReceive() throws Exception {
 60         testInterruptDuringReceive(true);
 61     }
 62 
 63     public void testInterruptBeforeUninterruptibleReceive() throws Exception {
 64         testInterruptBeforeReceive(false);
 65     }
 66 
 67     public void testInterruptDuringUninterruptibleReceive() throws Exception {
 68         testInterruptDuringReceive(false);
 69     }
 70 
 71     public void testInterruptBeforeInterruptibleSend() throws Exception {
 72         testInterruptBeforeSend(true);
 73     }
 74 
 75     public void testInterruptBeforeUninterruptibleSend() throws Exception {
 76         testInterruptBeforeSend(false);












 77     }
 78 
 79     /**
 80      * Test invoking DatagramChannel receive with interrupt status set

 81      */
 82     static void testInterruptBeforeReceive(boolean interruptible)
 83         throws Exception
 84     {
 85         try (DatagramChannel dc = openDatagramChannel(interruptible)) {
 86             dc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
 87             Future<?> timeout = scheduleClose(dc, Duration.ofSeconds(2));
 88             try {
 89                 ByteBuffer buf = ByteBuffer.allocate(100);
 90                 Thread.currentThread().interrupt();
 91                 assertThrows(expectedException(interruptible), () -> dc.receive(buf));
 92             } finally {
 93                 timeout.cancel(false);
 94             }
 95         } finally {
 96             Thread.interrupted();  // clear interrupt
 97         }
 98     }
 99 
100     /**
101      * Test Thread.interrupt when target thread is blocked in DatagramChannel receive

102      */
103     static void testInterruptDuringReceive(boolean interruptible)
104         throws Exception
105     {
106         try (DatagramChannel dc = openDatagramChannel(interruptible)) {
107             dc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
108             Future<?> timerTask = scheduleClose(dc, Duration.ofSeconds(5));
109             Future<?> interruptTask = scheduleInterrupt(Thread.currentThread(), Duration.ofSeconds(1));
110             try {
111                 ByteBuffer buf = ByteBuffer.allocate(100);
112                 assertThrows(expectedException(interruptible), () -> dc.receive(buf));
113             } finally {
114                 timerTask.cancel(false);
115                 interruptTask.cancel(false);
116             }
117         } finally {
118             Thread.interrupted();  // clear interrupt
119         }
120     }
121 
122     /**
123      * Test invoking DatagramChannel send with interrupt status set

124      */
125     static void testInterruptBeforeSend(boolean interruptible)
126         throws Exception
127     {
128         try (DatagramChannel dc = openDatagramChannel(interruptible)) {
129             dc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
130             Future<?> timeout = scheduleClose(dc, Duration.ofSeconds(2));
131             try {
132                 ByteBuffer buf = ByteBuffer.allocate(100);
133                 SocketAddress target = dc.getLocalAddress();
134                 Thread.currentThread().interrupt();
135                 if (interruptible) {
136                     assertThrows(ClosedByInterruptException.class, () -> dc.send(buf, target));
137                 } else {
138                     int n = dc.send(buf, target);
139                     assertTrue(n == 100);
140                 }
141             } finally {
142                 timeout.cancel(false);
143             }
144         } finally {
145             Thread.interrupted();  // clear interrupt
146         }
147     }
148 
149     /**
150      * Creates a DatagramChannel that is interruptible or not.

151      */
152     static DatagramChannel openDatagramChannel(boolean interruptible) throws IOException {
153         if (interruptible) {
154             return DatagramChannel.open();
155         } else {
156             return DefaultSelectorProvider.get().openUninterruptibleDatagramChannel();





157         }
158     }
159 
160     /**
161      * Expect ClosedByInterruptException if interruptible.

162      */
163     static Class<? extends Exception> expectedException(boolean expectInterrupt) {
164         if (expectInterrupt) {
165             return ClosedByInterruptException.class;
166         } else {
167             return AsynchronousCloseException.class;






168         }
169     }
170 
171     /**
172      * Schedule the given object to be closed.

173      */
174     static Future<?> scheduleClose(Closeable c, Duration timeout) {
175         long nanos = TimeUnit.NANOSECONDS.convert(timeout);
176         return STPE.schedule(() -> {
177             c.close();
178             return null;
179         }, nanos, TimeUnit.NANOSECONDS);








180     }
181 
182     /**
183      * Schedule the given thread to be interrupted.
184      */
185     static Future<?> scheduleInterrupt(Thread t, Duration timeout) {
186         long nanos = TimeUnit.NANOSECONDS.convert(timeout);
187         return STPE.schedule(t::interrupt, nanos, TimeUnit.NANOSECONDS);














188     }
189 
190     static final ScheduledExecutorService STPE = Executors.newScheduledThreadPool(0);
191 }

  1 /*
  2  * Copyright (c) 2019, 2024, 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  * @test
 26  * @bug 8236246
 27  * @modules java.base/sun.nio.ch
 28  * @run junit InterruptibleOrNot
 29  * @summary Test SelectorProviderImpl.openDatagramChannel(boolean) to create
 30  *     DatagramChannel objects that optionally support interrupt
 31  */
 32 
 33 import java.io.Closeable;
 34 import java.io.IOException;
 35 import java.net.InetAddress;
 36 import java.net.InetSocketAddress;
 37 import java.net.SocketAddress;
 38 import java.nio.ByteBuffer;
 39 import java.nio.channels.AsynchronousCloseException;
 40 import java.nio.channels.ClosedByInterruptException;
 41 import java.nio.channels.DatagramChannel;
 42 import java.time.Duration;
 43 import java.util.Arrays;



 44 import sun.nio.ch.DefaultSelectorProvider;
 45 
 46 import org.junit.jupiter.api.Test;
 47 import org.junit.jupiter.api.BeforeAll;
 48 import org.junit.jupiter.api.function.Executable;
 49 import static org.junit.jupiter.api.Assertions.*;
 50 

 51 public class InterruptibleOrNot {
 52     // DatagramChannel implementation class
 53     private static String dcImplClassName;
 54 
 55     @BeforeAll
 56     static void setup() throws Exception {
 57         try (DatagramChannel dc = boundDatagramChannel(true)) {
 58             dcImplClassName = dc.getClass().getName();
 59         }













 60     }
 61 
 62     /**
 63      * Call DatagramChannel.receive with the interrupt status set, the DatagramChannel
 64      * is interruptible.
 65      */
 66     @Test
 67     public void testInterruptBeforeInterruptibleReceive() throws Exception {
 68         try (DatagramChannel dc = boundDatagramChannel(true)) {
 69             ByteBuffer buf = ByteBuffer.allocate(100);
 70             Thread.currentThread().interrupt();
 71             assertThrows(ClosedByInterruptException.class, () -> dc.receive(buf));
 72             assertFalse(dc.isOpen());
 73         } finally {
 74             Thread.interrupted();  // clear interrupt status
 75         }
 76     }
 77 
 78     /**
 79      * Test interrupting a thread blocked in DatagramChannel.receive, the DatagramChannel
 80      * is interruptible.
 81      */
 82     @Test
 83     public void testInterruptDuringInterruptibleReceive() throws Exception {
 84         try (DatagramChannel dc = boundDatagramChannel(true)) {
 85             ByteBuffer buf = ByteBuffer.allocate(100);
 86             Thread thread = Thread.currentThread();
 87             onReceive(thread::interrupt);
 88             assertThrows(ClosedByInterruptException.class, () -> dc.receive(buf));
 89             assertFalse(dc.isOpen());





 90         } finally {
 91             Thread.interrupted();  // clear interrupt status
 92         }
 93     }
 94 
 95     /**
 96      * Call DatagramChannel.receive with the interrupt status set, the DatagramChannel
 97      * is not interruptible.
 98      */
 99     @Test
100     public void testInterruptBeforeUninterruptibleReceive() throws Exception {
101         try (DatagramChannel dc = boundDatagramChannel(false)) {
102             ByteBuffer buf = ByteBuffer.allocate(100);
103             onReceive(() -> {
104                 // close the channel after a delay to ensure receive wakes up
105                 Thread.sleep(1000);
106                 dc.close();
107             });
108             Thread.currentThread().interrupt();
109             assertThrows(AsynchronousCloseException.class, () -> dc.receive(buf));
110             assertFalse(dc.isOpen());


111         } finally {
112             Thread.interrupted();  // clear interrupt status
113         }
114     }
115 
116     /**
117      * Test interrupting a thread blocked in DatagramChannel.receive, the DatagramChannel
118      * is not interruptible.
119      */
120     @Test
121     public void testInterruptDuringUninterruptibleReceive() throws Exception {
122         try (DatagramChannel dc = boundDatagramChannel(true)) {
123             ByteBuffer buf = ByteBuffer.allocate(100);
124 
125             Thread thread = Thread.currentThread();
126             onReceive(() -> {
127                 // interrupt should not cause the receive to wakeup
128                 thread.interrupt();
129 
130                 // close the channel after a delay to ensure receive wakes up
131                 Thread.sleep(1000);
132                 dc.close();
133             });
134             assertThrows(AsynchronousCloseException.class, () -> dc.receive(buf));
135             assertFalse(dc.isOpen());



136         } finally {
137             Thread.interrupted();  // clear interrupt status
138         }
139     }
140 
141     /**
142      * Call DatagramChannel.send with the interrupt status set, the DatagramChannel
143      * is interruptible.
144      */
145     @Test
146     public void testInterruptBeforeInterruptibleSend() throws Exception {
147         try (DatagramChannel dc = boundDatagramChannel(true)) {
148             ByteBuffer buf = ByteBuffer.allocate(100);
149             SocketAddress target = dc.getLocalAddress();
150             Thread.currentThread().interrupt();
151             assertThrows(ClosedByInterruptException.class, () -> dc.send(buf, target));
152             assertFalse(dc.isOpen());
153         } finally {
154             Thread.interrupted();  // clear interrupt
155         }
156     }
157 
158     /**
159      * Call DatagramChannel.send with the interrupt status set, the DatagramChannel
160      * is not interruptible.
161      */
162     @Test
163     public void testInterruptBeforeUninterruptibleSend() throws Exception {
164         try (DatagramChannel dc = boundDatagramChannel(false)) {
165             ByteBuffer buf = ByteBuffer.allocate(100);
166             SocketAddress target = dc.getLocalAddress();
167             Thread.currentThread().interrupt();
168             int n = dc.send(buf, target);
169             assertEquals(100, n);
170             assertTrue(dc.isOpen());
171         } finally {
172             Thread.interrupted();  // clear interrupt status
173         }
174     }
175 
176     /**
177      * Creates a DatagramChannel that is interruptible or not, and bound to the loopback
178      * address.
179      */
180     static DatagramChannel boundDatagramChannel(boolean interruptible) throws IOException {
181         DatagramChannel dc;
182         if (interruptible) {
183             dc = DatagramChannel.open();
184         } else {
185             dc = DefaultSelectorProvider.get().openUninterruptibleDatagramChannel();
186         }
187         try {
188             dc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
189         } catch (IOException ioe) {
190             dc.close();
191             throw ioe;
192         }
193         return dc;
194     }
195 
196     /**
197      * Runs the given action when the current thread is sampled in DatagramChannel.receive.
198      */
199     static void onReceive(Executable action) {
200         Thread target = Thread.currentThread();
201         Thread.ofPlatform().daemon().start(() -> {
202             try {
203                 boolean found = false;
204                 while (!found) {
205                     Thread.sleep(20);
206                     StackTraceElement[] stack = target.getStackTrace();
207                     found = Arrays.stream(stack)
208                             .anyMatch(e -> dcImplClassName.equals(e.getClassName())
209                                     && "receive".equals(e.getMethodName()));
210                 }
211                 action.execute();
212             } catch (Throwable ex) {
213                 ex.printStackTrace();
214             }
215         });
216     }


217 }
< prev index next >