jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java
changeset 40545 11e43161b14e
parent 30046 cf2c86e1819e
--- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java	Wed Aug 24 17:57:20 2016 +0100
+++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java	Wed Aug 24 10:58:29 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -76,89 +76,91 @@
     }
 
     public static void main(String[] args) throws Exception {
-        // create listener to accept connections
-        final AsynchronousServerSocketChannel listener =
-            AsynchronousServerSocketChannel.open()
-                .bind(new InetSocketAddress(0));
-        listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
-            public void completed(final AsynchronousSocketChannel ch, Void att) {
-                listener.accept((Void)null, this);
-                final ByteBuffer buf = ByteBuffer.allocate(100);
-                ch.read(buf, ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
-                    public void completed(Integer bytesRead, AsynchronousSocketChannel ch) {
-                        if (bytesRead < 0) {
-                            try { ch.close(); } catch (IOException ignore) { }
-                        } else {
-                            buf.clear();
-                            ch.read(buf, ch, this);
-                        }
-                    }
-                    public void failed(Throwable exc, AsynchronousSocketChannel ch) {
-                        try { ch.close(); } catch (IOException ignore) { }
-                    }
-                });
-            }
-            public void failed(Throwable exc, Void att) {
-            }
-        });
-        int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
-        SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);
-
         // create 3-10 channels, each in its own group
         final int groupCount = 3 + rand.nextInt(8);
-        AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
+        final AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
         final AsynchronousSocketChannel[] channels = new AsynchronousSocketChannel[groupCount];
-        for (int i=0; i<groupCount; i++) {
-            ThreadFactory factory = createThreadFactory(i);
-            AsynchronousChannelGroup group;
-            if (rand.nextBoolean()) {
-                int nThreads = 1 + rand.nextInt(10);
-                group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, factory);
-            } else {
-                ExecutorService pool = Executors.newCachedThreadPool(factory);
-                group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
-            }
-            groups[i] = group;
+
+        // create listener to accept connections
+        try (final AsynchronousServerSocketChannel listener =
+                AsynchronousServerSocketChannel.open()) {
 
-            // create channel in group and connect it to the server
-            AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
-            ch.connect(sa).get();
-            channels[i] = ch;
-        }
+            listener.bind(new InetSocketAddress(0));
+            listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
+                public void completed(final AsynchronousSocketChannel ch, Void att) {
+                    listener.accept((Void)null, this);
+                    final ByteBuffer buf = ByteBuffer.allocate(100);
+                    ch.read(buf, ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
+                        public void completed(Integer bytesRead, AsynchronousSocketChannel ch) {
+                            if (bytesRead < 0) {
+                                try { ch.close(); } catch (IOException ignore) { }
+                            } else {
+                                buf.clear();
+                                ch.read(buf, ch, this);
+                            }
+                        }
+                        public void failed(Throwable exc, AsynchronousSocketChannel ch) {
+                            try { ch.close(); } catch (IOException ignore) { }
+                        }
+                    });
+                }
+                public void failed(Throwable exc, Void att) {
+                }
+            });
+            int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
+            SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);
 
-        // randomly write to each channel, ensuring that the completion handler
-        // is always invoked by a thread with the right identity.
-        final AtomicInteger writeCount = new AtomicInteger(100);
-        channels[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
-            public void completed(Integer bytesWritten, Integer groupId) {
-                if (bytesWritten != 1)
-                    fail("Expected 1 byte to be written");
-                if (!myGroup.get().equals(groupId))
-                    fail("Handler invoked by thread with the wrong identity");
-                if (writeCount.decrementAndGet() > 0) {
-                    int id = rand.nextInt(groupCount);
-                    channels[id].write(getBuffer(), id, this);
+            for (int i=0; i<groupCount; i++) {
+                ThreadFactory factory = createThreadFactory(i);
+                AsynchronousChannelGroup group;
+                if (rand.nextBoolean()) {
+                    int nThreads = 1 + rand.nextInt(10);
+                    group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, factory);
                 } else {
-                    done.countDown();
+                    ExecutorService pool = Executors.newCachedThreadPool(factory);
+                    group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
                 }
+                groups[i] = group;
+
+                // create channel in group and connect it to the server
+                AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
+                ch.connect(sa).get();
+                channels[i] = ch;
             }
-            public void failed(Throwable exc, Integer groupId) {
-                fail(exc.getMessage());
-            }
-        });
-
-        // wait until done
-        done.await();
 
-        // clean-up
-        for (AsynchronousSocketChannel ch: channels)
-            ch.close();
-        for (AsynchronousChannelGroup group: groups)
-            group.shutdownNow();
-        listener.close();
+            // randomly write to each channel, ensuring that the completion handler
+            // is always invoked by a thread with the right identity.
+            final AtomicInteger writeCount = new AtomicInteger(100);
+            channels[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
+                public void completed(Integer bytesWritten, Integer groupId) {
+                    if (bytesWritten != 1)
+                        fail("Expected 1 byte to be written");
+                    if (!myGroup.get().equals(groupId))
+                        fail("Handler invoked by thread with the wrong identity");
+                    if (writeCount.decrementAndGet() > 0) {
+                        int id = rand.nextInt(groupCount);
+                        channels[id].write(getBuffer(), id, this);
+                    } else {
+                        done.countDown();
+                    }
+                }
+                public void failed(Throwable exc, Integer groupId) {
+                    fail(exc.getMessage());
+                }
+            });
 
-        if (failed.get())
-            throw new RuntimeException("Test failed - see log for details");
+            // wait until done
+            done.await();
+        } finally {
+            // clean-up
+            for (AsynchronousSocketChannel ch: channels)
+                ch.close();
+            for (AsynchronousChannelGroup group: groups)
+                group.shutdownNow();
+
+            if (failed.get())
+                throw new RuntimeException("Test failed - see log for details");
+        }
     }
 
     static ByteBuffer getBuffer() {