changeset 2548:eb84b89ef3ff

6963027: TEST_BUG: channels and buffer tests need to run in samevm mode Reviewed-by: ohair, sherman, chegar
author alanb
date Wed, 23 Jun 2010 20:19:29 +0100
parents 3c745249065f
children 55aa27b8bb98
files test/Makefile test/ProblemList.txt test/java/nio/BufferPoolMXBean/Basic.java test/java/nio/MappedByteBuffer/Basic.java test/java/nio/MappedByteBuffer/Force.java test/java/nio/MappedByteBuffer/ZeroMap.java test/java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java test/java/nio/channels/AsynchronousChannelGroup/Identity.java test/java/nio/channels/AsynchronousDatagramChannel/Basic.java test/java/nio/channels/AsynchronousFileChannel/Basic.java test/java/nio/channels/AsynchronousFileChannel/Lock.java test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java test/java/nio/channels/AsynchronousSocketChannel/Basic.java test/java/nio/channels/Channels/Basic2.java test/java/nio/channels/Channels/Write.java test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java test/java/nio/channels/DatagramChannel/EmptyBuffer.java test/java/nio/channels/DatagramChannel/ReceiveISA.java test/java/nio/channels/DatagramChannel/SelectWhenRefused.java test/java/nio/channels/FileChannel/Args.java test/java/nio/channels/FileChannel/ClosedChannelTransfer.java test/java/nio/channels/FileChannel/ExpandingMap.java test/java/nio/channels/FileChannel/Lock.java test/java/nio/channels/FileChannel/MapOverEnd.java test/java/nio/channels/FileChannel/MapReadOnly.java test/java/nio/channels/FileChannel/MapTest.java test/java/nio/channels/FileChannel/Mode.java test/java/nio/channels/FileChannel/Position.java test/java/nio/channels/FileChannel/Pread.java test/java/nio/channels/FileChannel/Pwrite.java test/java/nio/channels/FileChannel/Read.java test/java/nio/channels/FileChannel/ReadFull.java test/java/nio/channels/FileChannel/ReadToLimit.java test/java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java test/java/nio/channels/FileChannel/ScatteringRead.java test/java/nio/channels/FileChannel/Size.java test/java/nio/channels/FileChannel/Transfer.java test/java/nio/channels/FileChannel/TransferToChannel.java test/java/nio/channels/FileChannel/TransferToNonWritable.java test/java/nio/channels/FileChannel/Transfers.java test/java/nio/channels/FileChannel/TryLock.java test/java/nio/channels/FileChannel/Write.java test/java/nio/channels/Pipe/NonBlocking.java test/java/nio/channels/Pipe/SelectPipe.java test/java/nio/channels/SelectionKey/AtomicAttachTest.java test/java/nio/channels/Selector/BasicAccept.java test/java/nio/channels/Selector/BasicConnect.java test/java/nio/channels/Selector/CheckLocking.java test/java/nio/channels/Selector/CloseInvalidatesKeys.java test/java/nio/channels/Selector/CloseWhenKeyIdle.java test/java/nio/channels/Selector/Connect.java test/java/nio/channels/Selector/ConnectWrite.java test/java/nio/channels/Selector/HelperSlowToDie.java test/java/nio/channels/Selector/KeysReady.java test/java/nio/channels/Selector/LotsOfChannels.java test/java/nio/channels/Selector/RegAfterPreClose.java test/java/nio/channels/Selector/SelectAndCancel.java test/java/nio/channels/Selector/SelectorLimit.java test/java/nio/channels/Selector/SelectorTest.java test/java/nio/channels/Selector/WakeupNow.java test/java/nio/channels/Selector/WakeupOverflow.java test/java/nio/channels/Selector/WakeupSpeed.java test/java/nio/channels/ServerSocketChannel/AcceptAddress.java test/java/nio/channels/SocketChannel/AdaptSocket.java test/java/nio/channels/SocketChannel/Bind.java test/java/nio/channels/SocketChannel/Close.java test/java/nio/channels/SocketChannel/CloseRegisteredChannel.java test/java/nio/channels/SocketChannel/CloseTimeoutChannel.java test/java/nio/channels/SocketChannel/IsConnectable.java test/java/nio/channels/SocketChannel/LocalAddress.java test/java/nio/channels/SocketChannel/SocketInheritance.java test/java/nio/channels/SocketChannel/Trivial.java test/java/nio/channels/SocketChannel/UnboundSocketTests.java test/java/nio/channels/etc/Shadow.java test/java/nio/channels/spi/SelectorProvider/inheritedChannel/ClosedStreams.java test/sun/nio/ch/Basic.java test/sun/nio/ch/TempBuffer.java test/sun/nio/cs/ReadZero.java test/sun/nio/cs/Test4206507.java test/sun/nio/cs/TestStringCoding.java
diffstat 80 files changed, 659 insertions(+), 432 deletions(-) [+]
line wrap: on
line diff
--- a/test/Makefile	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/Makefile	Wed Jun 23 20:19:29 2010 +0100
@@ -495,19 +495,17 @@
 jdk_nio1: java/nio/file
 	$(call RunSamevmBatch)
 
-# Stable othervm testruns (minus items from PROBLEM_LIST)
-#   Using samevm has serious problems with these tests
+# Stable samevm testruns (minus items from PROBLEM_LIST)
 JDK_ALL_TARGETS += jdk_nio2
 jdk_nio2: java/nio/Buffer java/nio/ByteOrder \
           java/nio/channels java/nio/BufferPoolMXBean java/nio/MappedByteBuffer
 	$(call SharedLibraryPermissions,java/nio/channels)
-	$(call RunOthervmBatch)
+	$(call RunSamevmBatch)
 
-# Stable othervm testruns (minus items from PROBLEM_LIST)
-#   Using samevm has serious problems with these tests
+# Stable samevm testruns (minus items from PROBLEM_LIST)
 JDK_ALL_TARGETS += jdk_nio3
 jdk_nio3: com/sun/nio sun/nio
-	$(call RunOthervmBatch)
+	$(call RunSamevmBatch)
 
 # All nio tests
 jdk_nio: jdk_nio1 jdk_nio2 jdk_nio3
--- a/test/ProblemList.txt	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/ProblemList.txt	Wed Jun 23 20:19:29 2010 +0100
@@ -507,25 +507,46 @@
 
 ############################################################################
 
+# jdk_io
+
+# 6962637
+java/io/File/MaxPathLength.java                                 windows-all
+
+############################################################################
+
 # jdk_nio
 
-# Suspect many of these tests auffer from using fixed ports, no concrete 
-#   evidence.
+# 6944810
+java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java       windows-all
 
-# Occasionally Failing with java.lang.AssertionError on Windows X64
-#  at sun.nio.ch.PendingIoCache.clearPendingIoMap(PendingIoCache.java:144)
-#java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java	windows-all
+# 6963118
+java/nio/channels/Selector/Wakeup.java                          windows-all
 
-# Some kind of sleep/wake problem on Windows X64
-java/nio/channels/Selector/Wakeup.java				windows-all
+# The asynchronous I/O implementation on Windows requires Windows XP or newer.
+# We can remove the following once all Windows 2000 machines have been
+# decommissioned.
+java/nio/channels/AsynchronousChannelGroup/Basic.java           windows-5.0
+java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java      windows-5.0
+java/nio/channels/AsynchronousChannelGroup/Identity.java        windows-5.0
+java/nio/channels/AsynchronousChannelGroup/Restart.java         windows-5.0
+java/nio/channels/AsynchronousChannelGroup/Unbounded.java       windows-5.0
+java/nio/channels/AsynchronousDatagramChannel/Basic.java        windows-5.0
+java/nio/channels/AsynchronousFileChannel/Lock.java             windows-5.0
+java/nio/channels/AsynchronousServerSocketChannel/Basic.java    windows-5.0
+java/nio/channels/AsynchronousServerSocketChannel/WithSecurityManager.java windows-5.0
+java/nio/channels/AsynchronousSocketChannel/Basic.java          windows-5.0
+java/nio/channels/AsynchronousSocketChannel/DieBeforeComplete.java windows-5.0
+java/nio/channels/AsynchronousSocketChannel/Leaky.java          windows-5.0
+java/nio/channels/AsynchronousSocketChannel/StressLoopback.java windows-5.0
+java/nio/channels/Channels/Basic2.java                          windows-5.0
+
+# 6959891
+com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
 
 # Fails with -ea -esa, Assertion error, but only on Solaris 10 machines?
 com/sun/nio/sctp/SctpChannel/Send.java				generic-all
 com/sun/nio/sctp/SctpChannel/Shutdown.java			generic-all
 
-# Fails on Windows 2000,  times out
-java/nio/channels/FileChannel/Transfer.java			generic-all
-
 # Fails on OpenSolaris, IllegalStateException: Cannot add or remove addresses 
 #    from a channel that is bound to the wildcard address
 com/sun/nio/sctp/SctpChannel/Bind.java				generic-all
@@ -533,12 +554,6 @@
 # Failed on OpenSolaris, java.lang.AssertionError: Unknown event type
 com/sun/nio/sctp/SctpChannel/Receive.java			generic-all
 
-# Runtime exception on windows X64, samevm mode
-java/nio/channels/Selector/WakeupNow.java			generic-all
-
-# Occasional errors, solarix x86, address already in use, othervm mode
-java/nio/channels/Selector/SelectorTest.java			generic-all
-
 # Solaris 11 gave assert error and "connection refused", samevm issues?
 com/sun/nio/sctp/SctpServerChannel/NonBlockingAccept.java 	generic-all
 
@@ -549,43 +564,6 @@
 com/sun/nio/sctp/SctpMultiChannel/Send.java			generic-all
 com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java	generic-all
 
-# Linux 64bit failures. too many files open
-java/nio/channels/Selector/HelperSlowToDie.java			generic-all
-
-# Gets java.lang.ExceptionInInitializerError on Windows 2000 (need XP or newer)
-java/nio/channels/AsynchronousChannelGroup/Basic.java	 	windows-5.0
-java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java 	windows-5.0
-java/nio/channels/AsynchronousChannelGroup/Identity.java 	windows-5.0
-java/nio/channels/AsynchronousChannelGroup/Restart.java 	windows-5.0
-java/nio/channels/AsynchronousChannelGroup/Unbounded.java	windows-5.0
-java/nio/channels/AsynchronousDatagramChannel/Basic.java 	windows-5.0
-java/nio/channels/AsynchronousFileChannel/Lock.java	 	windows-5.0
-java/nio/channels/AsynchronousServerSocketChannel/Basic.java 	windows-5.0
-java/nio/channels/AsynchronousServerSocketChannel/WithSecurityManager.java windows-5.0
-java/nio/channels/AsynchronousSocketChannel/Basic.java	 	windows-5.0
-java/nio/channels/AsynchronousSocketChannel/DieBeforeComplete.java windows-5.0
-java/nio/channels/AsynchronousSocketChannel/Leaky.java	 	windows-5.0
-java/nio/channels/AsynchronousSocketChannel/StressLoopback.java windows-5.0
-java/nio/channels/Channels/Basic2.java			 	windows-5.0
-
-# Failed loopback connection? On windows 32bit? 
-#   Considered a stress test, can consume all resources.
-java/nio/channels/Selector/LotsOfChannels.java		 	generic-all
-
-# Windows i586 client, crashed hotspot? Unpredictable
-#   Considered a stress test, can consume all resources.
-java/nio/channels/Selector/RegAfterPreClose.java	 	generic-all
-
-# Solaris i586, cannot assign address, samevm issues
-java/nio/channels/Selector/SelectorLimit.java		 	generic-all
-
-# Socket timeout windows X64
-java/nio/channels/ServerSocketChannel/AdaptServerSocket.java 	windows-all
-
-# Timeouts etc. on Window
-java/nio/channels/SocketChannel/ConnectState.java	 	windows-all
-java/nio/channels/SocketChannel/FinishConnect.java	 	windows-all
-
 ############################################################################
 
 # jdk_rmi
--- a/test/java/nio/BufferPoolMXBean/Basic.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/BufferPoolMXBean/Basic.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 6606598
  * @summary Unit test for java.nio.BufferPoolMXBean
+ * @run main/othervm Basic
  */
 
 import java.nio.ByteBuffer;
--- a/test/java/nio/MappedByteBuffer/Basic.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/MappedByteBuffer/Basic.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 4462336
  * @summary Simple MappedByteBuffer tests
+ * @run main/othervm Basic
  */
 
 import java.io.*;
--- a/test/java/nio/MappedByteBuffer/Force.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/MappedByteBuffer/Force.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 4625907
  * @summary Testing force()
+ * @run main/othervm Force
  */
 
 import java.io.*;
--- a/test/java/nio/MappedByteBuffer/ZeroMap.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/MappedByteBuffer/ZeroMap.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 4802340
  * @summary Testing force(), load() isLoaded() of zero len MBB
+ * @run main/othervm ZeroMap
  */
 
 import java.io.*;
--- a/test/java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java	Wed Jun 23 20:19:29 2010 +0100
@@ -29,6 +29,7 @@
 import java.nio.ByteBuffer;
 import java.nio.channels.*;
 import java.net.*;
+import java.util.*;
 import java.util.concurrent.*;
 import java.io.IOException;
 
@@ -44,8 +45,12 @@
         final AsynchronousServerSocketChannel listener =
             AsynchronousServerSocketChannel.open()
                 .bind(new InetSocketAddress(0));
+        final List<AsynchronousSocketChannel> accepted = new ArrayList<AsynchronousSocketChannel>();
         listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
             public void completed(AsynchronousSocketChannel ch, Void att) {
+                synchronized (accepted) {
+                    accepted.add(ch);
+                }
                 listener.accept((Void)null, this);
             }
             public void failed(Throwable exc, Void att) {
@@ -58,6 +63,14 @@
         test(sa, true, false);
         test(sa, false, true);
         test(sa, true, true);
+
+        // clean-up
+        listener.close();
+        synchronized (accepted) {
+            for (AsynchronousSocketChannel ch: accepted) {
+                ch.close();
+            }
+        }
     }
 
     static void test(SocketAddress sa,
--- a/test/java/nio/channels/AsynchronousChannelGroup/Identity.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousChannelGroup/Identity.java	Wed Jun 23 20:19:29 2010 +0100
@@ -32,6 +32,7 @@
 import java.util.*;
 import java.util.concurrent.*;
 import java.util.concurrent.atomic.*;
+import java.io.IOException;
 
 /**
  * Tests that the completion handler is invoked by a thread with
@@ -81,14 +82,18 @@
         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, (Void)null, new CompletionHandler<Integer,Void>() {
-                    public void completed(Integer bytesRead, Void att) {
-                        buf.clear();
-                        ch.read(buf, (Void)null, this);
+                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, Void att) {
+                    public void failed(Throwable exc, AsynchronousSocketChannel ch) {
+                        try { ch.close(); } catch (IOException ignore) { }
                     }
                 });
             }
@@ -100,7 +105,8 @@
 
         // create 3-10 channels, each in its own group
         final int groupCount = 3 + rand.nextInt(8);
-        final AsynchronousSocketChannel[] channel = new AsynchronousSocketChannel[groupCount];
+        AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
+        final AsynchronousSocketChannel[] channels = new AsynchronousSocketChannel[groupCount];
         for (int i=0; i<groupCount; i++) {
             ThreadFactory factory = createThreadFactory(i);
             AsynchronousChannelGroup group;
@@ -111,17 +117,18 @@
                 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();
-            channel[i] = ch;
+            channels[i] = ch;
         }
 
         // 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);
-        channel[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
+        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");
@@ -129,7 +136,7 @@
                     fail("Handler invoked by thread with the wrong identity");
                 if (writeCount.decrementAndGet() > 0) {
                     int id = rand.nextInt(groupCount);
-                    channel[id].write(getBuffer(), id, this);
+                    channels[id].write(getBuffer(), id, this);
                 } else {
                     done.countDown();
                 }
@@ -139,8 +146,16 @@
             }
         });
 
-        // wait until
+        // wait until done
         done.await();
+
+        // clean-up
+        for (AsynchronousSocketChannel ch: channels)
+            ch.close();
+        for (AsynchronousChannelGroup group: groups)
+            group.shutdownNow();
+        listener.close();
+
         if (failed.get())
             throw new RuntimeException("Test failed - see log for details");
     }
--- a/test/java/nio/channels/AsynchronousDatagramChannel/Basic.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousDatagramChannel/Basic.java	Wed Jun 23 20:19:29 2010 +0100
@@ -371,17 +371,22 @@
     static void doMulticastTests() throws Exception {
         final byte[] msg = "hello".getBytes();
 
+        InetAddress lh = InetAddress.getLocalHost();
+        NetworkInterface interf = NetworkInterface.getByInetAddress(lh);
+        if (interf.isLoopback() || !interf.supportsMulticast()) {
+            System.out.println("Multicasting not tested");
+            return;
+        }
+
         AsynchronousDatagramChannel ch = AsynchronousDatagramChannel
             .open(StandardProtocolFamily.INET, null)
             .setOption(StandardSocketOption.SO_REUSEADDR, true)
             .bind(new InetSocketAddress(0));
 
-        InetAddress lh = InetAddress.getLocalHost();
         int port = ((InetSocketAddress)(ch.getLocalAddress())).getPort();
 
         // join group
         InetAddress group = InetAddress.getByName("225.4.5.6");
-        NetworkInterface interf = NetworkInterface.getByInetAddress(lh);
         MembershipKey key = ch.join(group, interf);
 
         // check key
--- a/test/java/nio/channels/AsynchronousFileChannel/Basic.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousFileChannel/Basic.java	Wed Jun 23 20:19:29 2010 +0100
@@ -45,16 +45,18 @@
         File blah = File.createTempFile("blah", null);
         blah.deleteOnExit();
 
-        final AsynchronousFileChannel ch = AsynchronousFileChannel
+        AsynchronousFileChannel ch = AsynchronousFileChannel
             .open(blah.toPath(), READ, WRITE);
+        try {
+            // run tests
+            testUsingCompletionHandlers(ch);
+            testUsingWaitOnResult(ch);
+            testInterruptHandlerThread(ch);
+        } finally {
+            ch.close();
+        }
 
-        // run tests
-        testUsingCompletionHandlers(ch);
-        testUsingWaitOnResult(ch);
-        testInterruptHandlerThread(ch);
-
-        // close channel and invoke test that expects channel to be closed
-        ch.close();
+        // run test that expects channel to be closed
         testClosedChannel(ch);
 
         // these tests open the file themselves
@@ -63,6 +65,9 @@
         testAsynchronousClose(blah.toPath());
         testCancel(blah.toPath());
         testTruncate(blah.toPath());
+
+        // eagerly clean-up
+        blah.delete();
     }
 
     /*
--- a/test/java/nio/channels/AsynchronousFileChannel/Lock.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousFileChannel/Lock.java	Wed Jun 23 20:19:29 2010 +0100
@@ -53,13 +53,17 @@
         LockSlaveMirror slave = startLockSlave();
         try {
 
-             // create temporary file
+            // create temporary file
             File blah = File.createTempFile("blah", null);
             blah.deleteOnExit();
 
+            // run tests
             testLockProtocol(blah, slave);
             testAsyncClose(blah, slave);
 
+            // eagerly clean-up
+            blah.delete();
+
         } finally {
             slave.shutdown();
         }
@@ -150,7 +154,12 @@
         String sep = FileSystems.getDefault().getSeparator();
 
         String command = System.getProperty("java.home") +
-            sep + "bin" + sep + "java Lock -lockslave " + port;
+            sep + "bin" + sep + "java";
+        String testClasses = System.getProperty("test.classes");
+        if (testClasses != null)
+            command += " -cp " + testClasses;
+        command += " Lock -lockslave " + port;
+
         Process p = Runtime.getRuntime().exec(command);
         IOHandler.handle(p.getInputStream());
         IOHandler.handle(p.getErrorStream());
--- a/test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java	Wed Jun 23 20:19:29 2010 +0100
@@ -135,6 +135,7 @@
         latch.await();
 
         // verify content of each file
+        boolean failed = false;
         byte[] buf = new byte[8192];
         for (int i=0; i<count ;i++) {
             Writer writer = writers[i];
@@ -145,18 +146,35 @@
                 int nread = in.read(buf);
                 while (nread > 0) {
                     for (int j=0; j<nread; j++) {
-                        if (buf[j] != expected)
-                            throw new RuntimeException("Unexpected byte");
+                        if (buf[j] != expected) {
+                            System.err.println("Unexpected contents");
+                            failed = true;
+                            break;
+                        }
                         expected++;
                     }
+                    if (failed)
+                        break;
                     size += nread;
                     nread = in.read(buf);
                 }
-                if (size != writer.size())
-                    throw new RuntimeException("Unexpected size");
+                if (!failed && size != writer.size()) {
+                    System.err.println("Unexpected size");
+                    failed = true;
+                }
+                if (failed)
+                    break;
             } finally {
                 in.close();
             }
         }
+
+        // clean-up
+        for (int i=0; i<count; i++) {
+            writers[i].file().delete();
+        }
+
+        if (failed)
+            throw new RuntimeException("Test failed");
     }
 }
--- a/test/java/nio/channels/AsynchronousSocketChannel/Basic.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/AsynchronousSocketChannel/Basic.java	Wed Jun 23 20:19:29 2010 +0100
@@ -776,6 +776,7 @@
             throw new RuntimeException("RuntimeException expected after timeout.");
 
         ch.close();
+        server.close();
     }
 
     // returns ByteBuffer with random bytes
--- a/test/java/nio/channels/Channels/Basic2.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Channels/Basic2.java	Wed Jun 23 20:19:29 2010 +0100
@@ -61,6 +61,9 @@
         writerThread.join();
         readerThread.join();
 
+        // shutdown listener
+        listener.close();
+
         // check that reader received what we expected
         if (reader.total() != writer.total())
             throw new RuntimeException("Unexpected number of bytes read");
--- a/test/java/nio/channels/Channels/Write.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Channels/Write.java	Wed Jun 23 20:19:29 2010 +0100
@@ -47,5 +47,6 @@
         out.close();
         fc.close();
         fos.close();
+        testFile.delete();
     }
 }
--- a/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java	Wed Jun 23 20:19:29 2010 +0100
@@ -82,8 +82,6 @@
                 }
                 throw x;
             }
-            if (shouldTimeout)
-                throw new Exception("Receive did not time out");
             break;
         }
 
--- a/test/java/nio/channels/DatagramChannel/EmptyBuffer.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/DatagramChannel/EmptyBuffer.java	Wed Jun 23 20:19:29 2010 +0100
@@ -46,21 +46,25 @@
         Thread serverThread = new Thread(server);
         serverThread.start();
         DatagramChannel dc = DatagramChannel.open();
-        ByteBuffer bb = ByteBuffer.allocateDirect(12);
-        bb.order(ByteOrder.BIG_ENDIAN);
-        bb.putInt(1).putLong(1);
-        bb.flip();
-        InetAddress address = InetAddress.getLocalHost();
-        InetSocketAddress isa = new InetSocketAddress(address, server.port());
-        dc.connect(isa);
-        dc.write(bb);
-        bb.rewind();
-        dc.write(bb);
-        bb.rewind();
-        dc.write(bb);
-        Thread.sleep(2000);
-        serverThread.interrupt();
-        server.throwException();
+        try {
+            ByteBuffer bb = ByteBuffer.allocateDirect(12);
+            bb.order(ByteOrder.BIG_ENDIAN);
+            bb.putInt(1).putLong(1);
+            bb.flip();
+            InetAddress address = InetAddress.getLocalHost();
+            InetSocketAddress isa = new InetSocketAddress(address, server.port());
+            dc.connect(isa);
+            dc.write(bb);
+            bb.rewind();
+            dc.write(bb);
+            bb.rewind();
+            dc.write(bb);
+            Thread.sleep(2000);
+            serverThread.interrupt();
+            server.throwException();
+        } finally {
+            dc.close();
+        }
     }
 
     public static class Server implements Runnable {
@@ -118,6 +122,8 @@
                 }
             } catch (Exception ex) {
                 e = ex;
+            } finally {
+                try { dc.close(); } catch (IOException ignore) { }
             }
         }
     }
--- a/test/java/nio/channels/DatagramChannel/ReceiveISA.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/DatagramChannel/ReceiveISA.java	Wed Jun 23 20:19:29 2010 +0100
@@ -66,6 +66,10 @@
             rb.clear();
         }
 
+        dc1.close();
+        dc2.close();
+        dc3.close();
+
         /*
          * Check that sa[0] equals sa[1] (both from dc1)
          * Check that sa[1] not equal to sa[2] (one from dc1, one from dc2)
--- a/test/java/nio/channels/DatagramChannel/SelectWhenRefused.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/DatagramChannel/SelectWhenRefused.java	Wed Jun 23 20:19:29 2010 +0100
@@ -43,9 +43,9 @@
         SocketAddress refuser = new InetSocketAddress(InetAddress.getLocalHost(), port);
 
         dc = DatagramChannel.open().bind(new InetSocketAddress(0));
+        Selector sel = Selector.open();
         try {
             dc.configureBlocking(false);
-            Selector sel = Selector.open();
             dc.register(sel, SelectionKey.OP_READ);
 
             /* Test 1: not connected so ICMP port unreachable should not be received */
@@ -81,6 +81,7 @@
             }
 
         } finally {
+            sel.close();
             dc.close();
         }
     }
--- a/test/java/nio/channels/FileChannel/Args.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Args.java	Wed Jun 23 20:19:29 2010 +0100
@@ -97,6 +97,8 @@
                            (long)Integer.MAX_VALUE << 3);
                 }});
 
+        fc.close();
+        f.delete();
     }
 
 }
--- a/test/java/nio/channels/FileChannel/ClosedChannelTransfer.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/ClosedChannelTransfer.java	Wed Jun 23 20:19:29 2010 +0100
@@ -38,6 +38,7 @@
         test1(channel);
         test2(channel);
         channel.close();
+        file.delete();
     }
 
     static void test1(FileChannel channel) throws Exception {
--- a/test/java/nio/channels/FileChannel/ExpandingMap.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/ExpandingMap.java	Wed Jun 23 20:19:29 2010 +0100
@@ -25,6 +25,7 @@
  * @bug 4938372 6541641
  * @summary Flushing dirty pages prior to unmap can cause Cleaner thread to
  *          abort VM if memory system has pages locked
+ * @run main/othervm ExpandingMap
  */
 import java.io.File;
 import java.io.RandomAccessFile;
--- a/test/java/nio/channels/FileChannel/Lock.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Lock.java	Wed Jun 23 20:19:29 2010 +0100
@@ -55,6 +55,7 @@
         test2(blah, true);
         test2(blah, false);
         test3(blah);
+        blah.delete();
     }
 
     private static void test2(File blah, boolean b) throws Exception {
@@ -90,7 +91,11 @@
 
         // Exec the tamperer
         String command = System.getProperty("java.home") +
-            File.separator + "bin" + File.separator + "java Lock " + str + " " + blah;
+            File.separator + "bin" + File.separator + "java";
+        String testClasses = System.getProperty("test.classes");
+        if (testClasses != null)
+            command += " -cp " + testClasses;
+        command += " Lock " + str + " " + blah;
         Process p = Runtime.getRuntime().exec(command);
 
         BufferedReader in = new BufferedReader
--- a/test/java/nio/channels/FileChannel/MapOverEnd.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/MapOverEnd.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 4463036
  * @summary Check if file mapping extends beyond end of file
+ * @run main/othervm MapOverEnd
  */
 
 import java.nio.*;
--- a/test/java/nio/channels/FileChannel/MapReadOnly.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/MapReadOnly.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 4510489
  * @summary Verify IOUtil.java reads to buffer limits
+ * @run main/othervm MapReadOnly
  */
 import java.io.*;
 import java.nio.*;
--- a/test/java/nio/channels/FileChannel/MapTest.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/MapTest.java	Wed Jun 23 20:19:29 2010 +0100
@@ -23,6 +23,7 @@
 
 /* @test
  * @summary Test file mapping with FileChannel
+ * @run main/othervm MapTest
  */
 
 import java.io.*;
--- a/test/java/nio/channels/FileChannel/Mode.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Mode.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
    @bug 4462298
  * @summary Test FileChannel maps with different accesses
+ * @run main/othervm Mode
  */
 
 import java.nio.channels.*;
--- a/test/java/nio/channels/FileChannel/Position.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Position.java	Wed Jun 23 20:19:29 2010 +0100
@@ -63,6 +63,7 @@
 
         c.close();
         fis.close();
+        blah.delete();
     }
 
     /**
--- a/test/java/nio/channels/FileChannel/Pread.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Pread.java	Wed Jun 23 20:19:29 2010 +0100
@@ -65,6 +65,9 @@
             throw new RuntimeException("Expected exception not thrown");
         } catch(IllegalArgumentException e) {
             // Correct result
+        } finally {
+            fc.close();
+            blah.delete();
         }
     }
 
@@ -73,13 +76,18 @@
         File blah = File.createTempFile("blah2", null);
         blah.deleteOnExit();
         FileOutputStream fos = new FileOutputStream(blah);
-        fos.write(new byte[128]);
-        FileChannel fc = fos.getChannel();
         try {
-            fc.read(ByteBuffer.allocate(256),1);
-            throw new RuntimeException("Expected exception not thrown");
-        } catch(NonReadableChannelException e) {
-            // Correct result
+            fos.write(new byte[128]);
+            FileChannel fc = fos.getChannel();
+            try {
+                fc.read(ByteBuffer.allocate(256),1);
+                throw new RuntimeException("Expected exception not thrown");
+            } catch(NonReadableChannelException e) {
+                // Correct result
+            }
+        } finally {
+            fos.close();
+            blah.delete();
         }
     }
 
@@ -130,6 +138,7 @@
 
         c.close();
         fis.close();
+        blah.delete();
     }
 
     /**
--- a/test/java/nio/channels/FileChannel/Pwrite.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Pwrite.java	Wed Jun 23 20:19:29 2010 +0100
@@ -62,6 +62,9 @@
             throw new RuntimeException("Expected exception not thrown");
         } catch(NonWritableChannelException e) {
             // Correct result
+        } finally {
+            fc.close();
+            blah.delete();
         }
     }
 
@@ -123,6 +126,7 @@
         }
         c.close();
         raf.close();
+        blah.delete();
     }
 
     /**
--- a/test/java/nio/channels/FileChannel/Read.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Read.java	Wed Jun 23 20:19:29 2010 +0100
@@ -80,6 +80,7 @@
 
         c.close();
         fis.close();
+        blah.delete();
     }
 
     /**
--- a/test/java/nio/channels/FileChannel/ReadFull.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/ReadFull.java	Wed Jun 23 20:19:29 2010 +0100
@@ -54,5 +54,6 @@
 
         fc.close();
         fis.close();
+        blah.delete();
     }
 }
--- a/test/java/nio/channels/FileChannel/ReadToLimit.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/ReadToLimit.java	Wed Jun 23 20:19:29 2010 +0100
@@ -48,6 +48,7 @@
                 throw new Exception("Test failed");
         fc.close();
         fis.close();
+        blah.delete();
     }
 
     /**
--- a/test/java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java	Wed Jun 23 20:19:29 2010 +0100
@@ -39,8 +39,12 @@
     public static void main(String[] args) throws IOException {
         File blah = File.createTempFile("blah", null);
         blah.deleteOnExit();
-        for (int i=0; i<100; i++) {
-            test(blah.toPath());
+        try {
+            for (int i=0; i<100; i++) {
+                test(blah.toPath());
+            }
+        } finally {
+            blah.delete();
         }
     }
 
--- a/test/java/nio/channels/FileChannel/ScatteringRead.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/ScatteringRead.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
    @bug 4452020 4629048 4638365 4869859
  * @summary Test FileChannel scattering reads
+ * @run main/othervm ScatteringRead
  */
 
 import java.nio.channels.*;
--- a/test/java/nio/channels/FileChannel/Size.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Size.java	Wed Jun 23 20:19:29 2010 +0100
@@ -24,6 +24,7 @@
 /* @test
  * @bug 4563125
  * @summary Test size method of FileChannel
+ * @run main/othervm Size
  */
 
 import java.io.*;
--- a/test/java/nio/channels/FileChannel/Transfer.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Transfer.java	Wed Jun 23 20:19:29 2010 +0100
@@ -25,7 +25,7 @@
  * @bug 4434723 4482726 4559072 4638365 4795550 5081340 5103988 6253145
  * @summary Test FileChannel.transferFrom and transferTo
  * @library ..
- * @run main/timeout=180 Transfer
+ * @run main/timeout=240 Transfer
  */
 
 import java.io.*;
@@ -96,6 +96,9 @@
 
         sourceChannel.close();
         sinkChannel.close();
+
+        source.delete();
+        sink.delete();
     }
 
     private static void testReadableByteChannel(int size) throws Exception {
@@ -139,6 +142,8 @@
         fc.close();
         sink.close();
         source.close();
+
+        f.delete();
     }
 
     public static void xferTest02() throws Exception {
@@ -173,6 +178,9 @@
         fc2.close();
         raf1.close();
         raf2.close();
+
+        source.delete();
+        dest.delete();
     }
 
     public static void xferTest03() throws Exception {
@@ -207,6 +215,9 @@
         fc2.close();
         raf1.close();
         raf2.close();
+
+        source.delete();
+        dest.delete();
     }
 
     // Test transferTo with large file
@@ -245,6 +256,8 @@
         sourceChannel.close();
         sinkChannel.close();
 
+        source.delete();
+        sink.delete();
     }
 
     // Test transferFrom with large file
@@ -293,6 +306,8 @@
         }
         sourceChannel.close();
         sinkChannel.close();
+        source.delete();
+        sink.delete();
     }
 
     static void checkFileData(File file, String expected) throws Exception {
@@ -338,6 +353,8 @@
 
         checkFileData(source, data);
         checkFileData(sink, data.substring(7,data.length()));
+
+        source.delete();
     }
 
     // Test transferTo to non-blocking socket channel
@@ -371,6 +388,7 @@
         sink.close();
         other.close();
         ssc.close();
+        source.delete();
     }
 
 
@@ -473,6 +491,7 @@
             source.close();
             ssc.close();
             fc.close();
+            file.delete();
         }
     }
 
--- a/test/java/nio/channels/FileChannel/TransferToChannel.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/TransferToChannel.java	Wed Jun 23 20:19:29 2010 +0100
@@ -51,6 +51,8 @@
         test1();
         test2();
         in.close();
+        file.delete();
+        outFile.delete();
     }
 
     static void test1() throws Exception {
--- a/test/java/nio/channels/FileChannel/TransferToNonWritable.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/TransferToNonWritable.java	Wed Jun 23 20:19:29 2010 +0100
@@ -43,6 +43,9 @@
             throw new RuntimeException("Test failed");
         } catch (NonWritableChannelException nwce) {
             // Correct result
+        } finally {
+            channel.close();
+            blah.delete();
         }
     }
 }
--- a/test/java/nio/channels/FileChannel/Transfers.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Transfers.java	Wed Jun 23 20:19:29 2010 +0100
@@ -554,6 +554,10 @@
                 break;
         }
 
+        sourceFile.delete();
+        targetFile.delete();
+        fn.delete();
+
         if (failures > 0) {
             out.println();
             throw new RuntimeException("Some tests failed");
--- a/test/java/nio/channels/FileChannel/TryLock.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/TryLock.java	Wed Jun 23 20:19:29 2010 +0100
@@ -56,7 +56,6 @@
 
     public static void test1(boolean shared, boolean trylock) throws Exception {
         File testFile = File.createTempFile("test1", null);
-        testFile.deleteOnExit();
         FileInputStream fis = new FileInputStream(testFile);
         FileChannel fc = fis.getChannel();
         FileLock fl = null;
@@ -73,12 +72,13 @@
         } finally {
             if (fl != null)
                 fl.release();
+            fc.close();
+            testFile.delete();
         }
     }
 
     public static void test2(boolean shared, boolean trylock) throws Exception {
         File testFile = File.createTempFile("test2", null);
-        testFile.deleteOnExit();
         FileOutputStream fis = new FileOutputStream(testFile);
         FileChannel fc = fis.getChannel();
         FileLock fl = null;
@@ -95,19 +95,25 @@
         } finally {
             if (fl != null)
                 fl.release();
+            fc.close();
+            testFile.delete();
         }
     }
 
     public static void test3(boolean shared, boolean trylock) throws Exception {
         File testFile = File.createTempFile("test3", null);
-        testFile.deleteOnExit();
         RandomAccessFile fis = new RandomAccessFile(testFile, "rw");
         FileChannel fc = fis.getChannel();
-        FileLock fl = null;
-        if (trylock)
-            fl = fc.tryLock(0, fc.size(), shared);
-        else
-            fl = fc.lock(0, fc.size(), shared);
-        fl.release();
+        try {
+            FileLock fl = null;
+            if (trylock)
+                fl = fc.tryLock(0, fc.size(), shared);
+            else
+                fl = fc.lock(0, fc.size(), shared);
+            fl.release();
+        } finally {
+            fc.close();
+            testFile.delete();
+        }
     }
 }
--- a/test/java/nio/channels/FileChannel/Write.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Write.java	Wed Jun 23 20:19:29 2010 +0100
@@ -25,6 +25,7 @@
  * @test
  * @bug 4475533 4698138 4638365 4796221
  * @summary Test FileChannel write
+ * @run main/othervm Write
  */
 
 import java.nio.channels.*;
@@ -46,23 +47,25 @@
 
     // Test to see that offset > length does not throw exception
     static void test1() throws Exception {
-        File testFile = File.createTempFile("test1", null);
-        testFile.deleteOnExit();
-
         ByteBuffer[] dsts = new ByteBuffer[4];
         for (int i=0; i<4; i++)
             dsts[i] = ByteBuffer.allocateDirect(10);
 
-        FileOutputStream fos = new FileOutputStream(testFile);
-        FileChannel fc = fos.getChannel();
-        fc.write(dsts, 2, 1);
-        fos.close();
+        File testFile = File.createTempFile("test1", null);
+        try {
+            FileOutputStream fos = new FileOutputStream(testFile);
+            FileChannel fc = fos.getChannel();
+            fc.write(dsts, 2, 1);
+            fos.close();
+        } finally {
+            testFile.delete();
+        }
     }
 
     // Test to see that the appropriate buffers are updated
     static void test2() throws Exception {
         File testFile = File.createTempFile("test2", null);
-        testFile.deleteOnExit();
+        testFile.delete();
         ByteBuffer[] srcs = new ByteBuffer[4];
         for (int i=0; i<4; i++)
             srcs[i] = ByteBuffer.allocateDirect(10);
@@ -74,25 +77,34 @@
 
         FileOutputStream fos = new FileOutputStream(testFile);
         FileChannel fc = fos.getChannel();
-        fc.write(srcs, 1, 2);
-        fos.close();
+        try {
+            fc.write(srcs, 1, 2);
+        } finally {
+            fc.close();
+        }
 
         FileInputStream fis = new FileInputStream(testFile);
         fc = fis.getChannel();
-        ByteBuffer bb = ByteBuffer.allocateDirect(10);
-        fc.read(bb);
-        bb.flip();
-        if (bb.get() != 2)
-            throw new RuntimeException("Write failure");
-        if (bb.get() != 3)
-            throw new RuntimeException("Write failure");
         try {
-            bb.get();
-            throw new RuntimeException("Write failure");
-        } catch (BufferUnderflowException bufe) {
-            // correct result
+            ByteBuffer bb = ByteBuffer.allocateDirect(10);
+            fc.read(bb);
+            bb.flip();
+            if (bb.get() != 2)
+                throw new RuntimeException("Write failure");
+            if (bb.get() != 3)
+                throw new RuntimeException("Write failure");
+            try {
+                bb.get();
+                throw new RuntimeException("Write failure");
+            } catch (BufferUnderflowException bufe) {
+                // correct result
+            }
+        } finally {
+            fc.close();
         }
-        fis.close();
+
+        // eagerly clean-up
+        testFile.delete();
     }
 
     // Test write to a negative position (bug 4698138).
--- a/test/java/nio/channels/Pipe/NonBlocking.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Pipe/NonBlocking.java	Wed Jun 23 20:19:29 2010 +0100
@@ -41,12 +41,17 @@
 
     static void test1() throws Exception {
         Pipe p = Pipe.open();
-        p.sink().configureBlocking(false);
-        if (p.sink().isBlocking())
-            throw new Exception("Sink still blocking");
-        p.source().configureBlocking(false);
-        if (p.source().isBlocking())
-            throw new Exception("Source still blocking");
+        try {
+            p.sink().configureBlocking(false);
+            if (p.sink().isBlocking())
+                throw new Exception("Sink still blocking");
+            p.source().configureBlocking(false);
+            if (p.source().isBlocking())
+                throw new Exception("Source still blocking");
+        } finally {
+            p.sink().close();
+            p.source().close();
+        }
     }
 
 }
--- a/test/java/nio/channels/Pipe/SelectPipe.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Pipe/SelectPipe.java	Wed Jun 23 20:19:29 2010 +0100
@@ -78,10 +78,12 @@
                 totalRead += bytesRead;
         } while(totalRead < 10);
 
+        sink.close();
+        source.close();
+        selector.close();
+
         for(int i=0; i<10; i++)
             if (outgoingdata.get(i) != incomingdata.get(i))
                 throw new Exception("Pipe failed");
-        sink.close();
-        source.close();
     }
 }
--- a/test/java/nio/channels/SelectionKey/AtomicAttachTest.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SelectionKey/AtomicAttachTest.java	Wed Jun 23 20:19:29 2010 +0100
@@ -58,6 +58,11 @@
         };
 
         t.join();
+
+        pipe.sink().close();
+        pipe.source().close();
+        selector.close();
+
         int count = errorCount.get();
         if (count > 0) {
             throw new RuntimeException("Error count:" + count);
--- a/test/java/nio/channels/Selector/BasicAccept.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/BasicAccept.java	Wed Jun 23 20:19:29 2010 +0100
@@ -36,49 +36,60 @@
 
 public class BasicAccept {
 
-    public static int TEST_PORT = 40170;
+    static void server(ServerSocketChannel ssc) throws Exception {
+        Selector acceptSelector = Selector.open();
+        try {
+            ssc.configureBlocking(false);
+            SelectionKey acceptKey
+                = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
+            for (;;) {
+                int n = acceptSelector.select();
+                if (Thread.interrupted())
+                    break;
+                if (n == 0)
+                    continue;
+                Set<SelectionKey> readyKeys = acceptSelector.selectedKeys();
+                Iterator<SelectionKey> i = readyKeys.iterator();
+                while (i.hasNext()) {
+                    SelectionKey sk = i.next();
+                    i.remove();
+                    ServerSocketChannel nextReady
+                        = (ServerSocketChannel)sk.channel();
+                    SocketChannel sc = nextReady.accept();
+                    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 42 });
+                    sc.write(bb);
+                    sc.close();
+                }
+            }
+        } finally {
+            acceptSelector.close();
+        }
+    }
 
-    static void server() throws Exception {
-        Selector acceptSelector = Selector.open();
-        ServerSocketChannel ssc = ServerSocketChannel.open();
-        ssc.configureBlocking(false);
-        InetAddress lh = InetAddress.getLocalHost();
-        InetSocketAddress isa
-            = new InetSocketAddress(lh, SelectorTest.TEST_PORT);
-        ssc.socket().bind(isa);
-        SelectionKey acceptKey
-            = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
-        for (;;) {
-            if (acceptSelector.select() == 0)
-                continue;
-            Set readyKeys = acceptSelector.selectedKeys();
-            Iterator i = readyKeys.iterator();
-            while (i.hasNext()) {
-                SelectionKey sk = (SelectionKey)i.next();
-                i.remove();
-                ServerSocketChannel nextReady
-                    = (ServerSocketChannel)sk.channel();
-                SocketChannel sc = nextReady.accept();
-                ByteBuffer bb = ByteBuffer.wrap(new byte[] { 42 });
-                sc.write(bb);
+    private static class Server extends TestThread {
+        final ServerSocketChannel ssc;
+        Server() throws IOException {
+            super("Server", System.err);
+            this.ssc = ServerSocketChannel.open()
+                .bind(new InetSocketAddress(0));
+        }
+        int port() {
+            return ssc.socket().getLocalPort();
+        }
+        void go() throws Exception {
+            try {
+                server(ssc);
+            } finally {
+                ssc.close();
             }
         }
     }
 
-    private static class Server extends TestThread {
-        Server() {
-            super("Server", System.err);
-        }
-        void go() throws Exception {
-            server();
-        }
-    }
-
-    static void client() throws Exception {
+    static void client(int port) throws Exception {
         // Get a connection from the server
         InetAddress lh = InetAddress.getLocalHost();
         InetSocketAddress isa
-            = new InetSocketAddress(lh, SelectorTest.TEST_PORT);
+            = new InetSocketAddress(lh, port);
         int connectFailures = 0;
         boolean result = false;
         SocketChannel sc = SocketChannel.open();
@@ -122,17 +133,17 @@
         if (bb.get(0) != 42)
             throw new RuntimeException("Read wrong byte from server");
         System.err.println("Read from server");
+        sc.close();
     }
 
     public static void main(String[] args) throws Exception {
-        if (args.length == 0) {
-            Server server = new Server();
-            server.start();
-            client();
-        } else if (args[0].equals("client")) {
-            client();
-        } else if (args[0].equals("server")) {
-            server();
+        Server server = new Server();
+        server.start();
+        try {
+            client(server.port());
+        } finally {
+            server.interrupt();
+            server.finish(2000);
         }
     }
 
--- a/test/java/nio/channels/Selector/BasicConnect.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/BasicConnect.java	Wed Jun 23 20:19:29 2010 +0100
@@ -83,10 +83,13 @@
         ByteBuffer bb2 = ByteBuffer.allocateDirect(100);
         int n = sc.read(bb2);
         bb2.flip();
+
+        sc.close();
+        connectSelector.close();
+
         if (!bb.equals(bb2))
             throw new Exception("Echoed bytes incorrect: Sent "
                                 + bb + ", got " + bb2);
-        sc.close();
     }
 
 }
--- a/test/java/nio/channels/Selector/CheckLocking.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/CheckLocking.java	Wed Jun 23 20:19:29 2010 +0100
@@ -61,5 +61,7 @@
         doSelect();
         sk.interestOps(SelectionKey.OP_READ);
         selector.wakeup();
+        sc.close();
+        selector.close();
     }
 }
--- a/test/java/nio/channels/Selector/CloseInvalidatesKeys.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/CloseInvalidatesKeys.java	Wed Jun 23 20:19:29 2010 +0100
@@ -33,12 +33,16 @@
 
     public static void main (String [] args) throws Exception {
         DatagramChannel ch = DatagramChannel.open();
-        ch.configureBlocking(false);
-        Selector sel = Selector.open();
-        SelectionKey key = ch.register(sel, SelectionKey.OP_WRITE);
-        sel.close();
-        if (key.isValid())
-            throw new Exception("Key valid after selector closed");
+        try {
+            ch.configureBlocking(false);
+            Selector sel = Selector.open();
+            SelectionKey key = ch.register(sel, SelectionKey.OP_WRITE);
+            sel.close();
+            if (key.isValid())
+                throw new Exception("Key valid after selector closed");
+        } finally {
+            ch.close();
+        }
     }
 
 }
--- a/test/java/nio/channels/Selector/CloseWhenKeyIdle.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/CloseWhenKeyIdle.java	Wed Jun 23 20:19:29 2010 +0100
@@ -111,10 +111,14 @@
         // select should block
 
         int spinCount = 0;
+        boolean failed = false;
         for (;;) {
             int n = sel.select();
-            if (n > 0)
-                throw new RuntimeException("channel should not be selected");
+            if (n > 0) {
+                System.err.println("Channel should not be selected!!!");
+                failed = true;
+                break;
+            }
 
             // wakeup
             if (wakeupDone)
@@ -123,10 +127,19 @@
             // wakeup for no reason - if it happens a few times then we have a
             // problem
             spinCount++;
-            if (spinCount >= 3)
-                throw new RuntimeException("Selector appears to be spinning");
+            if (spinCount >= 3) {
+                System.err.println("Selector appears to be spinning");
+                failed = true;
+                break;
+            }
         }
 
+        sc1.close();
+        sel.close();
+
+        if (failed)
+            throw new RuntimeException("Test failed");
+
         System.out.println("PASS");
     }
 
--- a/test/java/nio/channels/Selector/Connect.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/Connect.java	Wed Jun 23 20:19:29 2010 +0100
@@ -25,7 +25,6 @@
  * @bug 4511624
  * @summary Test Making lots of Selectors
  * @library ..
- * @run main/timeout=240 Connect
  */
 
 import java.io.*;
@@ -38,7 +37,7 @@
 public class Connect {
 
     static int success = 0;
-    static int LIMIT = 500;
+    static int LIMIT = 100;
 
     public static void main(String[] args) throws Exception {
         scaleTest();
@@ -51,29 +50,30 @@
         for (int j=0; j<LIMIT; j++) {
             SocketChannel sc = SocketChannel.open();
             sc.configureBlocking(false);
-            boolean result = sc.connect(isa);
-            if (!result) {
+            boolean connected = sc.connect(isa);
+            if (!connected) {
                 Selector RSelector = SelectorProvider.provider().openSelector();
                 SelectionKey RKey = sc.register (RSelector, SelectionKey.OP_CONNECT);
-                while (!result) {
+                while (!connected) {
                     int keysAdded = RSelector.select(100);
                     if (keysAdded > 0) {
-                        Set readyKeys = RSelector.selectedKeys();
-                        Iterator i = readyKeys.iterator();
+                        Set<SelectionKey> readyKeys = RSelector.selectedKeys();
+                        Iterator<SelectionKey> i = readyKeys.iterator();
                         while (i.hasNext()) {
-                            SelectionKey sk = (SelectionKey)i.next();
+                            SelectionKey sk = i.next();
                             SocketChannel nextReady = (SocketChannel)sk.channel();
-                            result = nextReady.finishConnect();
+                            connected = nextReady.finishConnect();
                         }
+                        readyKeys.clear();
                     }
                 }
                 RSelector.close();
             }
-            read(sc);
+            readAndClose(sc);
         }
     }
 
-    static void read(SocketChannel sc) throws Exception {
+    static void readAndClose(SocketChannel sc) throws Exception {
         ByteBuffer bb = ByteBuffer.allocateDirect(100);
         int n = 0;
         while (n == 0) // Note this is not a rigorous check for done reading
--- a/test/java/nio/channels/Selector/ConnectWrite.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/ConnectWrite.java	Wed Jun 23 20:19:29 2010 +0100
@@ -45,8 +45,8 @@
         Selector selector = SelectorProvider.provider().openSelector();
         InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
         InetSocketAddress isa = new InetSocketAddress(myAddress, port);
+        SocketChannel sc = SocketChannel.open();
         try {
-            SocketChannel sc = SocketChannel.open();
             sc.configureBlocking(false);
             SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
             boolean result = sc.connect(isa);
@@ -80,6 +80,7 @@
                 }
             }
         } finally {
+            sc.close();
             selector.close();
         }
     }
--- a/test/java/nio/channels/Selector/HelperSlowToDie.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/HelperSlowToDie.java	Wed Jun 23 20:19:29 2010 +0100
@@ -33,9 +33,15 @@
 
 public class HelperSlowToDie {
     private static final int CHANNELS_PER_THREAD = 1023;
+    private static final int TEST_ITERATIONS = 200;
     private static volatile boolean done;
 
     public static void main(String[] args) throws IOException {
+        if (!System.getProperty("os.name").startsWith("Windows")) {
+            System.out.println("Test skipped as it verifies a Windows specific bug");
+            return;
+        }
+
         Selector sel = Selector.open();
 
         // register channels
@@ -60,7 +66,7 @@
             new Thread(busy).start();
 
         // Loop changing the number of channels from 1023 to 1024 and back.
-        for (int i=0; i<1000; i++) {
+        for (int i=0; i<TEST_ITERATIONS; i++) {
             SocketChannel sc = SocketChannel.open();
             sc.configureBlocking(false);
             sc.register(sel, SelectionKey.OP_CONNECT);
@@ -71,5 +77,11 @@
 
         // terminate busy threads
         done = true;
+
+        // clean-up
+        for (int i=0; i<CHANNELS_PER_THREAD; i++) {
+            channels[i].close();
+        }
+        sel.close();
     }
 }
--- a/test/java/nio/channels/Selector/KeysReady.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/KeysReady.java	Wed Jun 23 20:19:29 2010 +0100
@@ -49,14 +49,18 @@
 
         // Prepare a selector
         Selector selector = SelectorProvider.provider().openSelector();
-        SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
-        int keysAdded = selector.select();
-        if (keysAdded > 0) {
-            keysAdded = selector.select(1000);
-            if (keysAdded > 0)
-                throw new Exception("Same key reported added twice");
+        try {
+            SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
+            int keysAdded = selector.select();
+            if (keysAdded > 0) {
+                keysAdded = selector.select(1000);
+                if (keysAdded > 0)
+                    throw new Exception("Same key reported added twice");
+            }
+        } finally {
+            selector.close();
+            sc.close();
         }
-        sc.close();
     }
 
     public static void main(String[] args) throws Exception {
--- a/test/java/nio/channels/Selector/LotsOfChannels.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/LotsOfChannels.java	Wed Jun 23 20:19:29 2010 +0100
@@ -35,19 +35,11 @@
 
 public class LotsOfChannels {
 
-    private final static int PIPES_COUNT = 1900;
+    private final static int PIPES_COUNT = 256;
     private final static int BUF_SIZE = 8192;
     private final static int LOOPS = 10;
 
     public static void main(String[] argv) throws Exception {
-
-
-        String os = System.getProperty("os.name");
-        if (!(os.equals("Windows NT")
-           || os.equals("Windows 2000")
-           || os.equals("Windows XP")))
-            return;
-
         Pipe[] pipes = new Pipe[PIPES_COUNT];
         Pipe pipe = Pipe.open();
         Pipe.SinkChannel sink = pipe.sink();
@@ -72,6 +64,13 @@
             sel.selectedKeys().clear();
             source.read(ByteBuffer.allocate(BUF_SIZE));
         }
+
+        for (int i = 0; i < PIPES_COUNT; i++ ) {
+            pipes[i].sink().close();
+            pipes[i].source().close();
+        }
+        pipe.sink().close();
+        pipe.source().close();
         sel.close();
     }
 }
--- a/test/java/nio/channels/Selector/RegAfterPreClose.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/RegAfterPreClose.java	Wed Jun 23 20:19:29 2010 +0100
@@ -35,6 +35,7 @@
 
 public class RegAfterPreClose {
 
+    static final int TEST_ITERATIONS = 300;
     static volatile boolean done;
 
     /**
@@ -96,26 +97,21 @@
             }
         };
 
-        // schedule test to run for 1 minute
-        Executors.newScheduledThreadPool(1, factory).schedule(new Runnable() {
-            public void run() {
-                done = true;
-                sel.wakeup();
-            }}, 1, TimeUnit.MINUTES);
-
         // create Executor that handles tasks that closes channels
         // "asynchronously" - this creates the conditions to provoke the bug.
-        Executor executor = Executors.newFixedThreadPool(2, factory);
+        ExecutorService executor = Executors.newFixedThreadPool(2, factory);
 
         // submit task that connects to listener
         executor.execute(new Connector(ssc.socket().getLocalPort()));
 
         // loop accepting connections until done (or an IOException is thrown)
-        while (!done) {
+        int remaining = TEST_ITERATIONS;
+        while (remaining > 0) {
             sel.select();
             if (key.isAcceptable()) {
                 SocketChannel sc = ssc.accept();
                 if (sc != null) {
+                    remaining--;
                     sc.configureBlocking(false);
                     sc.register(sel, SelectionKey.OP_READ);
                     executor.execute(new Closer(sc));
@@ -123,5 +119,8 @@
             }
             sel.selectedKeys().clear();
         }
+        done = true;
+        sel.close();
+        executor.shutdown();
     }
 }
--- a/test/java/nio/channels/Selector/SelectAndCancel.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/SelectAndCancel.java	Wed Jun 23 20:19:29 2010 +0100
@@ -31,11 +31,7 @@
 import java.net.*;
 
 public class SelectAndCancel {
-    static ServerSocketChannel ssc;
-    static Selector selector;
     static SelectionKey sk;
-    static InetSocketAddress isa;
-    public static int TEST_PORT = 40170;
 
     /*
      * CancelledKeyException is the failure symptom of 4729342
@@ -43,17 +39,17 @@
      * seen immediately when the bug is present.
      */
     public static void main(String[] args) throws Exception {
-        InetAddress lh = InetAddress.getLocalHost();
-        isa = new InetSocketAddress(lh, TEST_PORT);
-        selector = Selector.open();
-        ssc = ServerSocketChannel.open();
+        final Selector selector = Selector.open();
+        final ServerSocketChannel ssc =
+            ServerSocketChannel.open().bind(new InetSocketAddress(0));
+        final InetSocketAddress isa =
+            new InetSocketAddress(InetAddress.getLocalHost(), ssc.socket().getLocalPort());
 
         // Create and start a selector in a separate thread.
         new Thread(new Runnable() {
                 public void run() {
                     try {
                         ssc.configureBlocking(false);
-                        ssc.socket().bind(isa);
                         sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
                         selector.select();
                     } catch (IOException e) {
--- a/test/java/nio/channels/Selector/SelectorLimit.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/SelectorLimit.java	Wed Jun 23 20:19:29 2010 +0100
@@ -26,6 +26,8 @@
  * @summary Ensure that a Selector can return at least 100 selected keys
  * @author Mark Reinhold
  * @library ..
+ * @build SelectorLimit
+ * @run main/othervm SelectorLimit
  */
 
 import java.io.*;
--- a/test/java/nio/channels/Selector/SelectorTest.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/SelectorTest.java	Wed Jun 23 20:19:29 2010 +0100
@@ -57,13 +57,13 @@
      */
     public static void main(String[] args) throws Exception {
         if (args.length == 0) {
-            InetSocketAddress isa
-                = new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT);
-            Server server = new Server(isa);
+            Server server = new Server(0);
             server.start();
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) { }
+            InetSocketAddress isa
+                = new InetSocketAddress(InetAddress.getLocalHost(), server.port());
             Client client = new Client(isa);
             client.start();
             if ((server.finish(FINISH_TIME) & client.finish(FINISH_TIME)) == 0)
@@ -74,9 +74,7 @@
 
             if (args.length > 1)
                 TEST_PORT = Integer.parseInt(args[1]);
-            InetSocketAddress isa
-                = new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT);
-            Server server = new Server(isa);
+            Server server = new Server(TEST_PORT);
             server.start();
             if (server.finish(FINISH_TIME) == 0)
                 throw new Exception("Failure");
@@ -136,18 +134,22 @@
     }
 
     static class Server extends TestThread {
+        private final ServerSocketChannel ssc;
         private List socketList = new ArrayList();
         private ServerSocket ss;
         private int connectionsAccepted = 0;
         private Selector pollSelector;
         private Selector acceptSelector;
-        private InetSocketAddress isa;
         private Set pkeys;
         private Set pskeys;
 
-        Server(InetSocketAddress isa) {
+        Server(int port) throws IOException {
             super("Server", SelectorTest.log);
-            this.isa = isa;
+            this.ssc = ServerSocketChannel.open().bind(new InetSocketAddress(port));
+        }
+
+        int port() {
+            return ssc.socket().getLocalPort();
         }
 
         public void go() throws Exception {
@@ -162,11 +164,7 @@
 
             requestThread.start();
 
-            ServerSocketChannel ssc = ServerSocketChannel.open();
             ssc.configureBlocking(false);
-            ssc.socket().setReuseAddress(true);
-            ssc.socket().bind(isa);
-
             SelectionKey acceptKey = ssc.register(acceptSelector,
                                                   SelectionKey.OP_ACCEPT);
             while(connectionsAccepted < SelectorTest.NUM_CLIENTS) {
--- a/test/java/nio/channels/Selector/WakeupNow.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/WakeupNow.java	Wed Jun 23 20:19:29 2010 +0100
@@ -44,10 +44,15 @@
         p.source().configureBlocking(false);
         p.source().register(sel, SelectionKey.OP_READ);
         sel.wakeup();
+        // ensure wakeup is consumed by selectNow
+        Thread.sleep(2000);
         sel.selectNow();
         long startTime = System.currentTimeMillis();
         int n = sel.select(2000);
         long endTime = System.currentTimeMillis();
+        p.source().close();
+        p.sink().close();
+        sel.close();
         if (endTime - startTime < 1000)
             throw new RuntimeException("test failed");
     }
@@ -60,10 +65,13 @@
         Pipe p = Pipe.open();
         p.source().configureBlocking(false);
         sel.wakeup();
+        // ensure wakeup is consumed by selectNow
+        Thread.sleep(2000);
         sel.selectNow();
         long startTime = System.currentTimeMillis();
         int n = sel.select(2000);
         long endTime = System.currentTimeMillis();
+        sel.close();
         if (endTime - startTime < 1000)
             throw new RuntimeException("test failed");
     }
--- a/test/java/nio/channels/Selector/WakeupOverflow.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/WakeupOverflow.java	Wed Jun 23 20:19:29 2010 +0100
@@ -31,8 +31,12 @@
 public class WakeupOverflow {
     public static void main( String[] args ) throws Exception {
         Selector selector = Selector.open();
-        for(int i=0; i<10000; i++) {
-            selector.wakeup();
+        try {
+            for(int i=0; i<10000; i++) {
+                selector.wakeup();
+            }
+        } finally {
+            selector.close();
         }
     }
 }
--- a/test/java/nio/channels/Selector/WakeupSpeed.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/Selector/WakeupSpeed.java	Wed Jun 23 20:19:29 2010 +0100
@@ -35,16 +35,19 @@
     public static void main(String argv[]) throws Exception {
         int waitTime = 4000;
         Selector selector = Selector.open();
+        try {
+            selector.wakeup();
 
-        selector.wakeup();
+            long t1 = System.currentTimeMillis();
+            selector.select(waitTime);
+            long t2 = System.currentTimeMillis();
+            long totalTime = t2 - t1;
 
-        long t1 = System.currentTimeMillis();
-        selector.select(waitTime);
-        long t2 = System.currentTimeMillis();
-        long totalTime = t2 - t1;
-
-        if (totalTime > waitTime)
-            throw new RuntimeException("Test failed");
+            if (totalTime > waitTime)
+                throw new RuntimeException("Test failed");
+        } finally {
+            selector.close();
+        }
     }
 
 }
--- a/test/java/nio/channels/ServerSocketChannel/AcceptAddress.java	Tue Jun 22 19:18:06 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2001, 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/* @test
- * @summary test the address returned in socket from accept
- */
-
-import java.io.*;
-import java.net.*;
-import java.nio.*;
-import java.nio.channels.*;
-
-
-public class AcceptAddress {
-
-    public static void main(String[] args) throws Exception {
-        InetAddress local = InetAddress.getLocalHost();
-        InetSocketAddress isa = new InetSocketAddress(local, 5555);
-
-        ServerSocketChannel ssc;
-        ssc = ServerSocketChannel.open();
-        ssc.socket().bind(isa);
-
-        SocketChannel sc;
-        sc = SocketChannel.open();
-        sc.connect(isa);
-
-        SocketChannel sc2 = ssc.accept();
-        System.err.println("Socket connected to " + sc2);
-    }
-}
--- a/test/java/nio/channels/SocketChannel/AdaptSocket.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/AdaptSocket.java	Wed Jun 23 20:19:29 2010 +0100
@@ -78,8 +78,6 @@
                     throw x;
                 }
             }
-            if (shouldTimeout)
-                throw new Exception("Connection did not time out");
         }
         out.println("connected: " + so);
         out.println("           " + sc);
@@ -118,8 +116,6 @@
             }
             throw x;
         }
-        if (shouldTimeout)
-            throw new Exception("Read did not time out");
     }
 
     static void testRead(String hn, int timeout, boolean shouldTimeout)
--- a/test/java/nio/channels/SocketChannel/Bind.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/Bind.java	Wed Jun 23 20:19:29 2010 +0100
@@ -31,13 +31,20 @@
 
 public class Bind {
     public static void main(String[] args) throws Exception {
+        SocketChannel sc1 = SocketChannel.open();
         try {
-            SocketChannel channel1 = SocketChannel.open();
-            channel1.socket().bind(new InetSocketAddress(5555));
-            SocketChannel channel2 = SocketChannel.open();
-            channel2.socket().bind(new InetSocketAddress(5555));
+            sc1.bind(new InetSocketAddress(0));
+            int port = sc1.socket().getLocalPort();
+            SocketChannel sc2 = SocketChannel.open();
+            try {
+                sc2.bind(new InetSocketAddress(port));
+            } finally {
+               sc2.close();
+            }
         } catch (BindException be) {
             // Correct result
+        } finally {
+            sc1.close();
         }
     }
 }
--- a/test/java/nio/channels/SocketChannel/Close.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/Close.java	Wed Jun 23 20:19:29 2010 +0100
@@ -56,8 +56,12 @@
 
     static void testChannelClose() throws IOException {
         SelectionKey sk = open();
-        sk.channel().close();
-        check(sk);
+        try {
+            sk.channel().close();
+            check(sk);
+        } finally {
+            sk.selector().close();
+        }
     }
 
     public static void main(String[] args) throws Exception {
--- a/test/java/nio/channels/SocketChannel/CloseRegisteredChannel.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/CloseRegisteredChannel.java	Wed Jun 23 20:19:29 2010 +0100
@@ -55,5 +55,8 @@
         System.out.println ("Will hang here...");
         int nb = slave.read (ByteBuffer.allocate (1024));
         //System.out.println("read nb=" + nb);
+
+        selector.close();
+        server.close();
     }
 }
--- a/test/java/nio/channels/SocketChannel/CloseTimeoutChannel.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/CloseTimeoutChannel.java	Wed Jun 23 20:19:29 2010 +0100
@@ -33,11 +33,12 @@
 import java.net.*;
 
 public class CloseTimeoutChannel {
-    final static int PORT=6347;
     public static void main(String args[]) throws Exception {
+        int port = -1;
         try {
             ServerSocketChannel listener=ServerSocketChannel.open();
-            listener.socket().bind(new InetSocketAddress(PORT));
+            listener.socket().bind(new InetSocketAddress(0));
+            port = listener.socket().getLocalPort();
             AcceptorThread thread=new AcceptorThread(listener);
             thread.start();
         } catch (IOException e) {
@@ -50,7 +51,7 @@
         try {
             System.out.println("Establishing connection");
             Socket socket=SocketChannel.open(
-                new InetSocketAddress("127.0.0.1", PORT)).socket();
+                new InetSocketAddress("127.0.0.1", port)).socket();
             OutputStream out=socket.getOutputStream();
             InputStream in=socket.getInputStream();
 
@@ -98,7 +99,8 @@
                     Thread.sleep(100);
                 } catch (InterruptedException e) { }
 
-                System.out.println(INDENT+"Listening on port "+ PORT);
+                System.out.println(INDENT+"Listening on port "+
+                    _listener.socket().getLocalPort());
                 ByteBuffer buf=ByteBuffer.allocate(5);
                 Socket client=_listener.accept().socket();;
                 System.out.println(INDENT+"Accepted client");
@@ -123,6 +125,8 @@
                 client.close();
             } catch (IOException e) {
                 System.out.println(INDENT+"Error accepting!");
+            } finally {
+                try { _listener.close(); } catch (IOException ignore) { }
             }
         }
     }
--- a/test/java/nio/channels/SocketChannel/IsConnectable.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/IsConnectable.java	Wed Jun 23 20:19:29 2010 +0100
@@ -48,27 +48,31 @@
         sc.connect(isa);
 
         Selector selector = SelectorProvider.provider().openSelector();
-        SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
-        int keysAdded = selector.select();
-        if (keysAdded > 0) {
-            boolean result = sc.finishConnect();
-            if (result) {
-                keysAdded = selector.select(5000);
-                // 4750573: keysAdded should not be incremented when op is dropped
-                // from a key already in the selected key set
-                if (keysAdded > 0)
-                    throw new Exception("Test failed: 4750573 detected");
-                Set sel = selector.selectedKeys();
-                Iterator i = sel.iterator();
-                SelectionKey sk = (SelectionKey)i.next();
-                // 4737146: isConnectable should be false while connected
-                if (sk.isConnectable())
-                    throw new Exception("Test failed: 4737146 detected");
+        try {
+            SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
+            int keysAdded = selector.select();
+            if (keysAdded > 0) {
+                boolean result = sc.finishConnect();
+                if (result) {
+                    keysAdded = selector.select(5000);
+                    // 4750573: keysAdded should not be incremented when op is dropped
+                    // from a key already in the selected key set
+                    if (keysAdded > 0)
+                        throw new Exception("Test failed: 4750573 detected");
+                    Set<SelectionKey> sel = selector.selectedKeys();
+                    Iterator<SelectionKey> i = sel.iterator();
+                    SelectionKey sk = i.next();
+                    // 4737146: isConnectable should be false while connected
+                    if (sk.isConnectable())
+                        throw new Exception("Test failed: 4737146 detected");
+                }
+            } else {
+                throw new Exception("Select failed");
             }
-        } else {
-            throw new Exception("Select failed");
+        } finally {
+            sc.close();
+            selector.close();
         }
-        sc.close();
     }
 
     public static void main(String[] args) throws Exception {
--- a/test/java/nio/channels/SocketChannel/LocalAddress.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/LocalAddress.java	Wed Jun 23 20:19:29 2010 +0100
@@ -38,25 +38,33 @@
 
     static void test1() throws Exception {
         InetAddress bogus = InetAddress.getByName("0.0.0.0");
-        SocketChannel sc = SocketChannel.open();
         InetSocketAddress saddr = new InetSocketAddress(
             InetAddress.getByName(TestUtil.HOST), 23);
 
         //Test1: connect only
-        sc.connect(saddr);
-        InetAddress isa = sc.socket().getLocalAddress();
-        if (isa == null || isa.equals(bogus))
-            throw new RuntimeException("test failed");
+        SocketChannel sc = SocketChannel.open();
+        try {
+            sc.connect(saddr);
+            InetAddress ia = sc.socket().getLocalAddress();
+            if (ia == null || ia.equals(bogus))
+                throw new RuntimeException("test failed");
+        } finally {
+            sc.close();
+        }
 
         //Test2: bind and connect
         sc = SocketChannel.open();
-        sc.socket().bind(new InetSocketAddress(0));
-        if (sc.socket().getLocalPort() == 0)
-            throw new RuntimeException("test failed");
-        sc.socket().connect(saddr);
-        isa = sc.socket().getLocalAddress();
-        if (isa == null || isa.isAnyLocalAddress())
-            throw new RuntimeException("test failed");
+        try {
+            sc.socket().bind(new InetSocketAddress(0));
+            if (sc.socket().getLocalPort() == 0)
+                throw new RuntimeException("test failed");
+            sc.socket().connect(saddr);
+            InetAddress ia = sc.socket().getLocalAddress();
+            if (ia == null || ia.isAnyLocalAddress())
+                throw new RuntimeException("test failed");
+        } finally {
+            sc.close();
+        }
 
     }
 }
--- a/test/java/nio/channels/SocketChannel/SocketInheritance.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/SocketInheritance.java	Wed Jun 23 20:19:29 2010 +0100
@@ -105,7 +105,11 @@
 
         // launch the child
         String cmd = System.getProperty("java.home") + File.separator + "bin" +
-            File.separator + "java SocketInheritance -child " + port;
+            File.separator + "java";
+        String testClasses = System.getProperty("test.classes");
+        if (testClasses != null)
+            cmd += " -cp " + testClasses;
+        cmd += " SocketInheritance -child " + port;
 
         Process p = Runtime.getRuntime().exec(cmd);
 
--- a/test/java/nio/channels/SocketChannel/Trivial.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/Trivial.java	Wed Jun 23 20:19:29 2010 +0100
@@ -33,22 +33,27 @@
     public static void main(String[] args) throws Exception {
         SocketChannel sc = SocketChannel.open();
         Selector sel = Selector.open();
-        if (sc.keyFor(sel) != null)
-            throw new Exception("keyFor != null");
-        sc.configureBlocking(false);
-        SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
-        if (sc.keyFor(sel) != sk)
-            throw new Exception("keyFor returned " + sc.keyFor(sel));
-        if (sk.attachment() != args)
-            throw new Exception("attachment() returned " + sk.attachment());
-        Trivial t = new Trivial();
-        sk.attach(t);
-        if (sk.attachment() != t)
-            throw new Exception("Wrong attachment");
-        sk.isReadable();
-        sk.isWritable();
-        sk.isConnectable();
-        sk.isAcceptable();
+        try {
+            if (sc.keyFor(sel) != null)
+                throw new Exception("keyFor != null");
+            sc.configureBlocking(false);
+            SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
+            if (sc.keyFor(sel) != sk)
+                throw new Exception("keyFor returned " + sc.keyFor(sel));
+            if (sk.attachment() != args)
+                throw new Exception("attachment() returned " + sk.attachment());
+            Trivial t = new Trivial();
+            sk.attach(t);
+            if (sk.attachment() != t)
+                throw new Exception("Wrong attachment");
+            sk.isReadable();
+            sk.isWritable();
+            sk.isConnectable();
+            sk.isAcceptable();
+        } finally {
+            sel.close();
+            sc.close();
+        }
     }
 
 }
--- a/test/java/nio/channels/SocketChannel/UnboundSocketTests.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/SocketChannel/UnboundSocketTests.java	Wed Jun 23 20:19:29 2010 +0100
@@ -57,39 +57,47 @@
         System.out.println("\n-- SocketChannel --");
 
         SocketChannel sc = SocketChannel.open();
+        try {
+            check("getLocalPort()", sc.socket().getLocalPort(), -1);
+            checkIsAnyLocalAddress("getLocalAddress()",
+                sc.socket().getLocalAddress());
+            check("getLocalSocketAddress()", sc.socket().getLocalSocketAddress(), null);
 
-        check("getLocalPort()", sc.socket().getLocalPort(), -1);
-        checkIsAnyLocalAddress("getLocalAddress()",
-            sc.socket().getLocalAddress());
-        check("getLocalSocketAddress()", sc.socket().getLocalSocketAddress(), null);
-
-        check("getPort()", sc.socket().getPort(), 0);
-        check("getInetAddress()", sc.socket().getInetAddress(), null);
-        check("getRemoteSocketAddress()", sc.socket().getRemoteSocketAddress(), null);
-
+            check("getPort()", sc.socket().getPort(), 0);
+            check("getInetAddress()", sc.socket().getInetAddress(), null);
+            check("getRemoteSocketAddress()", sc.socket().getRemoteSocketAddress(), null);
+        } finally {
+            sc.close();
+        }
 
         System.out.println("\n-- ServerSocketChannel --");
 
         ServerSocketChannel ssc = ServerSocketChannel.open();
-
-        check("getLocalPort()", ssc.socket().getLocalPort(), -1);
-        check("getInetAddress()", ssc.socket().getInetAddress(), null);
-        check("getLocalSocketAddress()", ssc.socket().getLocalSocketAddress(), null);
+        try {
+            check("getLocalPort()", ssc.socket().getLocalPort(), -1);
+            check("getInetAddress()", ssc.socket().getInetAddress(), null);
+            check("getLocalSocketAddress()", ssc.socket().getLocalSocketAddress(), null);
+        } finally {
+            ssc.close();
+        }
 
         System.out.println("\n-- DatagramChannel --");
 
         DatagramChannel dc = DatagramChannel.open();
+        try {
+            // not specified
+            check("getLocalPort()", dc.socket().getLocalPort(), 0);
 
-        // not specified
-        check("getLocalPort()", dc.socket().getLocalPort(), 0);
+            checkIsAnyLocalAddress("getLocalAddress()",
+                dc.socket().getLocalAddress());
+            check("getLocalSocketAddress()", dc.socket().getLocalSocketAddress(), null);
 
-        checkIsAnyLocalAddress("getLocalAddress()",
-            dc.socket().getLocalAddress());
-        check("getLocalSocketAddress()", dc.socket().getLocalSocketAddress(), null);
-
-        check("getPort()", dc.socket().getPort(), -1);
-        check("getInetAddress()", dc.socket().getInetAddress(), null);
-        check("getRemoteSocketAddress()", dc.socket().getRemoteSocketAddress(), null);
+            check("getPort()", dc.socket().getPort(), -1);
+            check("getInetAddress()", dc.socket().getInetAddress(), null);
+            check("getRemoteSocketAddress()", dc.socket().getRemoteSocketAddress(), null);
+        } finally {
+            dc.close();
+        }
 
         if (failures > 0) {
             throw new RuntimeException(failures + " sub-tests(s) failed.");
--- a/test/java/nio/channels/etc/Shadow.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/etc/Shadow.java	Wed Jun 23 20:19:29 2010 +0100
@@ -35,7 +35,6 @@
 
 public class Shadow {
 
-    private static final int PORT = 2019;
     static PrintStream log = System.err;
 
     private static void dump(ServerSocket s) {
@@ -69,7 +68,7 @@
     public static void main(String[] args) throws Exception {
         boolean useChannels
             = ((args.length == 0) || Boolean.valueOf(args[0]).booleanValue());
-        int port = (args.length > 1 ? Integer.parseInt(args[1]) : PORT);
+        int port = (args.length > 1 ? Integer.parseInt(args[1]) : -1);
 
         // open server socket
         ServerSocket serverSocket;
@@ -86,7 +85,8 @@
         }
 
         // bind server socket to port
-        SocketAddress bindAddr = new InetSocketAddress(port);
+        SocketAddress bindAddr =
+            new InetSocketAddress((port == -1) ? 0 : port);
         serverSocket.bind(bindAddr);
         log.println("bound ServerSocket: " + serverSocket);
 
--- a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/ClosedStreams.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/ClosedStreams.java	Wed Jun 23 20:19:29 2010 +0100
@@ -26,6 +26,8 @@
  * @bug 4997227
  * @summary Calling inheritedChannel() after FileDescriptor.in was closed
  *          caused an InternalError to be thrown.
+ * @build ClosedStreams
+ * @run main/othervm ClosedStreams
  */
 
 import java.io.FileDescriptor;
--- a/test/sun/nio/ch/Basic.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/sun/nio/ch/Basic.java	Wed Jun 23 20:19:29 2010 +0100
@@ -32,5 +32,7 @@
 public class Basic {
     public static void main(String[] args) throws Exception {
         Pipe p = Pipe.open();
+        p.source().close();
+        p.sink().close();
     }
 }
--- a/test/sun/nio/ch/TempBuffer.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/sun/nio/ch/TempBuffer.java	Wed Jun 23 20:19:29 2010 +0100
@@ -54,8 +54,12 @@
                     blah.deleteOnExit();
                     TempBuffer.initTestFile(blah);
                     RandomAccessFile raf = new RandomAccessFile(blah, "rw");
-                    FileChannel fs = raf.getChannel();
-                    fs.transferTo(0, SIZE, Channels.newChannel(out));
+                    FileChannel fc = raf.getChannel();
+                    try {
+                        fc.transferTo(0, SIZE, Channels.newChannel(out));
+                    } finally {
+                        fc.close();
+                    }
                     out.flush();
                 } catch (IOException ioe) {
                     throw new RuntimeException(ioe);
@@ -69,10 +73,17 @@
         File blah = File.createTempFile("blah2", null);
         blah.deleteOnExit();
         RandomAccessFile raf = new RandomAccessFile(blah, "rw");
-        FileChannel fs = raf.getChannel();
-        raf.setLength(SIZE);
-        fs.transferFrom(Channels.newChannel(in), 0, SIZE);
-        fs.close();
+        FileChannel fc = raf.getChannel();
+        try {
+            raf.setLength(SIZE);
+            fc.transferFrom(Channels.newChannel(in), 0, SIZE);
+        } finally {
+            fc.close();
+        }
+
+        sourceChannel.close();
+        sinkChannel.close();
+        blah.delete();
     }
 
     private static void initTestFile(File blah) throws IOException {
--- a/test/sun/nio/cs/ReadZero.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/sun/nio/cs/ReadZero.java	Wed Jun 23 20:19:29 2010 +0100
@@ -43,15 +43,18 @@
                 return 0;
             }
         };
+        try {
+            is.read(new byte[1], 0, 1); // ok
+            InputStreamReader isr = new InputStreamReader(is);
 
-        is.read(new byte[1], 0, 1); // ok
-        InputStreamReader isr = new InputStreamReader(is);
-
-        try {
-            int res = isr.read(new char[1], 0, 1);
-        } catch (IOException x) {
-            System.out.println("IOException caught");
-            return;
+            try {
+                int res = isr.read(new char[1], 0, 1);
+            } catch (IOException x) {
+                System.out.println("IOException caught");
+                return;
+            }
+        } finally {
+            is.close();
         }
         throw new RuntimeException("IOException not thrown");
     }
--- a/test/sun/nio/cs/Test4206507.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/sun/nio/cs/Test4206507.java	Wed Jun 23 20:19:29 2010 +0100
@@ -32,7 +32,12 @@
 
 public class Test4206507 {
     public static void main(String[] args) throws UnsupportedEncodingException {
-        Locale.setDefault(new Locale("tr", "TR"));
-        byte[] b = "".getBytes("ISO8859-9");
+        Locale l = Locale.getDefault();
+        try {
+            Locale.setDefault(new Locale("tr", "TR"));
+            byte[] b = "".getBytes("ISO8859-9");
+        } finally {
+            Locale.setDefault(l);
+        }
     }
 }
--- a/test/sun/nio/cs/TestStringCoding.java	Tue Jun 22 19:18:06 2010 -0700
+++ b/test/sun/nio/cs/TestStringCoding.java	Wed Jun 23 20:19:29 2010 +0100
@@ -26,7 +26,7 @@
 /* @test
    @bug 6636323 6636319
    @summary Test if StringCoding and NIO result have the same de/encoding result
- * @run main/timeout=2000 TestStringCoding
+ * @run main/othervm/timeout=2000 TestStringCoding
  */
 
 import java.util.*;