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 }