changeset 2683:58626b4eedcb

Merge
author lana
date Thu, 12 Aug 2010 11:23:15 -0700
parents d0e314d59f84 3b0abcb51280
children 23f72ec0d8e8
files test/java/net/Socket/AccurateTimeout.java
diffstat 136 files changed, 2725 insertions(+), 1585 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Tue Aug 10 19:29:30 2010 +0400
+++ b/.hgtags	Thu Aug 12 11:23:15 2010 -0700
@@ -77,3 +77,5 @@
 820b4e843d5168370a3bf166d19751a3271d8575 jdk7-b100
 d58354a69011f3d3354765fa3167567c4c4a9612 jdk7-b101
 13029a61b16bec06535d4f0aa98229b358684128 jdk7-b102
+6488b70a23cc6dc4b7e00809bc503c2884bafb28 jdk7-b103
+1a92820132a0221c5bdedd42d0888c57ce4cbb34 jdk7-b104
--- a/make/common/Release.gmk	Tue Aug 10 19:29:30 2010 +0400
+++ b/make/common/Release.gmk	Thu Aug 12 11:23:15 2010 -0700
@@ -571,6 +571,16 @@
 	$(ECHO) "META-INF/services/com.sun.tools.xjc.Plugin" >> $@
 	$(ECHO) "com/sun/tools/" >> $@
 	$(ECHO) "sun/jvmstat/" >> $@
+	$(ECHO) "sun/nio/cs/ext/" >> $@
+	$(ECHO) "sun/awt/HKSCS.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GB2312$Decoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GB2312$Encoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GB2312.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GBK$Encoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GBK.class" >> $@
+	$(ECHO) "sun/awt/motif/X11KSC5601$Decoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11KSC5601$Encoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11KSC5601.class" >> $@
 	$(ECHO) "sun/rmi/rmic/" >> $@
 	$(ECHO) "sun/tools/asm/" >> $@
 	$(ECHO) "sun/tools/java/" >> $@
--- a/make/common/shared/Defs-versions.gmk	Tue Aug 10 19:29:30 2010 +0400
+++ b/make/common/shared/Defs-versions.gmk	Thu Aug 12 11:23:15 2010 -0700
@@ -191,7 +191,7 @@
 
 # Generic
 REQUIRED_ANT_VER          = 1.6.3
-REQUIRED_BOOT_VER         = 1.5
+REQUIRED_BOOT_VER         = 1.6
 REQUIRED_FREETYPE_VERSION = 2.3.0
 REQUIRED_MAKE_VER         = 3.78
 REQUIRED_UNZIP_VER        = 5.12
--- a/make/docs/Makefile	Tue Aug 10 19:29:30 2010 +0400
+++ b/make/docs/Makefile	Thu Aug 12 11:23:15 2010 -0700
@@ -47,9 +47,9 @@
 
 # Url to devdocs page
 #   Was: http://java.sun.com/javase/6/webnotes/devdocs-vs-specs.html
-DEV_DOCS_URL-5 = http://java.sun.com/j2se/1.5.0/docs
-DEV_DOCS_URL-6 = http://download.oracle.com/docs/cd/E17409_01/javase/6/docs
-DEV_DOCS_URL-7 = http://download.oracle.com/docs/cd/E17409_01/javase/7/docs
+DEV_DOCS_URL-5 = http://java.sun.com/j2se/1.5.0/docs/index.html
+DEV_DOCS_URL-6 = http://download.oracle.com/javase/6/docs/index.html
+DEV_DOCS_URL-7 = http://download.oracle.com/javase/7/docs/index.html
 DEV_DOCS_URL = $(DEV_DOCS_URL-$(JDK_MINOR_VERSION))
 
 # Url to Java Language Spec
@@ -84,6 +84,11 @@
                   $(SHARE_SRC)/../solaris/classes \
 	          $(SHARE_SRC)/../windows/classes \
 		  $(SHARE_SRC)/doc/stub
+
+# List of directories that actually exist
+ALL_EXISTING_SOURCE_DIRS := $(wildcard $(ALL_SOURCE_DIRS))
+
+# List with classpath separator between them
 EMPTY:=
 SPACE:= $(EMPTY) $(EMPTY)
 RELEASEDOCS_SOURCEPATH = \
@@ -240,7 +245,8 @@
 # Default target is same as docs target, create core api and all others it can
 #
 
-all docs: coredocs otherdocs
+all: docs
+docs: coredocs otherdocs
 
 #################################################################
 # Production Targets -- USE THESE TARGETS WHEN:
@@ -1178,9 +1184,9 @@
 #
 # Get a cache of all the directories
 
-$(DIRECTORY_CACHE): $(ALL_SOURCE_DIRS)
+$(DIRECTORY_CACHE): $(ALL_EXISTING_SOURCE_DIRS)
 	$(prep-target)
-	@for cp in $(ALL_SOURCE_DIRS) ; do 		\
+	@for cp in $(ALL_EXISTING_SOURCE_DIRS) ; do 	\
 	  $(ECHO) "$(FIND) $${cp} -type f >> $@"; 	\
 	  $(FIND) $${cp} -type f >> $@; 		\
 	done
--- a/make/java/nio/mapfile-linux	Tue Aug 10 19:29:30 2010 +0400
+++ b/make/java/nio/mapfile-linux	Thu Aug 12 11:23:15 2010 -0700
@@ -119,6 +119,7 @@
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_initIDs;
                 Java_sun_nio_ch_SocketChannelImpl_checkConnect;
+		Java_sun_nio_ch_SocketChannelImpl_sendOutOfBandData;
 		Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_accept0;
 		Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_initIDs;
 		Java_sun_nio_ch_UnixAsynchronousSocketChannelImpl_checkConnect;
--- a/make/java/nio/mapfile-solaris	Tue Aug 10 19:29:30 2010 +0400
+++ b/make/java/nio/mapfile-solaris	Thu Aug 12 11:23:15 2010 -0700
@@ -106,6 +106,7 @@
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_initIDs;
                 Java_sun_nio_ch_SocketChannelImpl_checkConnect;
+		Java_sun_nio_ch_SocketChannelImpl_sendOutOfBandData;
 		Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_accept0;
 		Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_initIDs;
 		Java_sun_nio_ch_UnixAsynchronousSocketChannelImpl_checkConnect;
--- a/make/sun/nio/cs/Makefile	Tue Aug 10 19:29:30 2010 +0400
+++ b/make/sun/nio/cs/Makefile	Thu Aug 12 11:23:15 2010 -0700
@@ -58,6 +58,25 @@
 FILES_genout_extcs = $(FILES_gen_extcs:%.java=$(GENSRCDIR)/%.java)
 
 #
+# These sun.awt charsets use sun/nio/cs/ext charsets that only exist
+# in JDK7 charsets.jar, which causes problem when build the symbol
+# table for rt.jar in Release.gmk. They are now removed from the
+# rt.jar when building jdk/jre image (in Release.gmk), so add them
+# into charsets.jar here
+#
+ifeq ($(PLATFORM), windows)
+FILES_src += \
+	sun/awt/HKSCS.java
+else
+# Solaris/Linux
+FILES_src += \
+	sun/awt/HKSCS.java \
+	sun/awt/motif/X11GB2312.java \
+	sun/awt/motif/X11GBK.java \
+	sun/awt/motif/X11KSC5601.java
+endif # PLATFORM
+
+#
 # Rules
 #
 include $(BUILDDIR)/common/Classes.gmk
--- a/src/share/classes/com/sun/jndi/dns/DnsContextFactory.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/com/sun/jndi/dns/DnsContextFactory.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2010, 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
@@ -132,7 +132,7 @@
             throw new ConfigurationException("DNS pseudo-URL required");
         }
 
-        List servers = new ArrayList();
+        List<String> servers = new ArrayList<>();
 
         for (int i = 0; i < urls.length; i++) {
             String server = urls[i].getHost();
@@ -142,7 +142,7 @@
                 // No server or port given, so look to underlying platform.
                 // ResolverConfiguration does some limited caching, so the
                 // following is reasonably efficient even if called rapid-fire.
-                List platformServers =
+                List<String> platformServers =
                     ResolverConfiguration.open().nameservers();
                 if (!platformServers.isEmpty()) {
                     servers.addAll(platformServers);
@@ -157,8 +157,7 @@
                         ? server
                         : server + ":" + port);
         }
-        return (String[]) servers.toArray(
-                                        new String[servers.size()]);
+        return servers.toArray(new String[servers.size()]);
     }
 
     /*
--- a/src/share/classes/com/sun/jndi/ldap/Connection.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/com/sun/jndi/ldap/Connection.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2010, 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
@@ -658,6 +658,11 @@
             }
         }
         if (nparent) {
+            LdapRequest ldr = pendingRequests;
+            while (ldr != null) {
+                ldr.notify();
+                ldr = ldr.next;
+            }
             parent.processConnectionClosure();
         }
     }
--- a/src/share/classes/com/sun/jndi/ldap/Filter.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/com/sun/jndi/ldap/Filter.java	Thu Aug 12 11:23:15 2010 -0700
@@ -803,8 +803,7 @@
     //
     ////////////////////////////////////////////////////////////////////////////
 
-    // private static final boolean dbg = false;
-    private static final boolean dbg = true;
+    private static final boolean dbg = false;
     private static int dbgIndent = 0;
 
     private static void dprint(String msg) {
--- a/src/share/classes/com/sun/jndi/rmi/registry/RegistryContext.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/com/sun/jndi/rmi/registry/RegistryContext.java	Thu Aug 12 11:23:15 2010 -0700
@@ -81,7 +81,7 @@
         }
 
         RMIClientSocketFactory socketFactory =
-                (RMIClientSocketFactory) env.get(SOCKET_FACTORY);
+                (RMIClientSocketFactory) environment.get(SOCKET_FACTORY);
         registry = getRegistry(host, port, socketFactory);
         this.host = host;
         this.port = port;
--- a/src/share/classes/java/lang/AutoCloseable.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/lang/AutoCloseable.java	Thu Aug 12 11:23:15 2010 -0700
@@ -41,6 +41,13 @@
      * be declared to throw more specific exceptions (or no exception
      * at all, if the close cannot fail).
      *
+     * <p>Note that unlike the {@link java.io.Closeable#close close}
+     * method of {@link java.io.Closeable}, this {@code close} method
+     * is <em>not</em> required to be idempotent.  In other words,
+     * calling this {@code close} method more than once may have some
+     * visible side effect, unlike {@code Closeable.close} which is
+     * required to have no effect if called more than once.
+     *
      * @throws Exception if this resource cannot be closed
      */
     void close() throws Exception;
--- a/src/share/classes/java/lang/Throwable.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/lang/Throwable.java	Thu Aug 12 11:23:15 2010 -0700
@@ -28,12 +28,12 @@
 import  java.util.*;
 
 /**
- * The <code>Throwable</code> class is the superclass of all errors and
+ * The {@code Throwable} class is the superclass of all errors and
  * exceptions in the Java language. Only objects that are instances of this
  * class (or one of its subclasses) are thrown by the Java Virtual Machine or
- * can be thrown by the Java <code>throw</code> statement. Similarly, only
+ * can be thrown by the Java {@code throw} statement. Similarly, only
  * this class or one of its subclasses can be the argument type in a
- * <code>catch</code> clause.
+ * {@code catch} clause.
  *
  * For the purposes of compile-time checking of exceptions, {@code
  * Throwable} and any subclass of {@code Throwable} that is not also a
@@ -73,11 +73,11 @@
  * permit the method to throw the cause directly.  For example, suppose
  * a persistent collection conforms to the {@link java.util.Collection
  * Collection} interface, and that its persistence is implemented atop
- * <tt>java.io</tt>.  Suppose the internals of the <tt>add</tt> method
+ * {@code java.io}.  Suppose the internals of the {@code add} method
  * can throw an {@link java.io.IOException IOException}.  The implementation
- * can communicate the details of the <tt>IOException</tt> to its caller
- * while conforming to the <tt>Collection</tt> interface by wrapping the
- * <tt>IOException</tt> in an appropriate unchecked exception.  (The
+ * can communicate the details of the {@code IOException} to its caller
+ * while conforming to the {@code Collection} interface by wrapping the
+ * {@code IOException} in an appropriate unchecked exception.  (The
  * specification for the persistent collection should indicate that it is
  * capable of throwing such exceptions.)
  *
@@ -86,7 +86,7 @@
  * {@link #initCause(Throwable)} method.  New throwable classes that
  * wish to allow causes to be associated with them should provide constructors
  * that take a cause and delegate (perhaps indirectly) to one of the
- * <tt>Throwable</tt> constructors that takes a cause.  For example:
+ * {@code Throwable} constructors that takes a cause.  For example:
  * <pre>
  *     try {
  *         lowLevelOp();
@@ -94,10 +94,10 @@
  *         throw new HighLevelException(le);  // Chaining-aware constructor
  *     }
  * </pre>
- * Because the <tt>initCause</tt> method is public, it allows a cause to be
+ * Because the {@code initCause} method is public, it allows a cause to be
  * associated with any throwable, even a "legacy throwable" whose
  * implementation predates the addition of the exception chaining mechanism to
- * <tt>Throwable</tt>. For example:
+ * {@code Throwable}. For example:
  * <pre>
  *     try {
  *         lowLevelOp();
@@ -121,28 +121,28 @@
  * use the standard exception chaining mechanism, while continuing to
  * implement their "legacy" chaining mechanisms for compatibility.
  *
- * <p>Further, as of release 1.4, many general purpose <tt>Throwable</tt>
+ * <p>Further, as of release 1.4, many general purpose {@code Throwable}
  * classes (for example {@link Exception}, {@link RuntimeException},
  * {@link Error}) have been retrofitted with constructors that take
  * a cause.  This was not strictly necessary, due to the existence of the
- * <tt>initCause</tt> method, but it is more convenient and expressive to
+ * {@code initCause} method, but it is more convenient and expressive to
  * delegate to a constructor that takes a cause.
  *
- * <p>By convention, class <code>Throwable</code> and its subclasses have two
+ * <p>By convention, class {@code Throwable} and its subclasses have two
  * constructors, one that takes no arguments and one that takes a
- * <code>String</code> argument that can be used to produce a detail message.
+ * {@code String} argument that can be used to produce a detail message.
  * Further, those subclasses that might likely have a cause associated with
  * them should have two more constructors, one that takes a
- * <code>Throwable</code> (the cause), and one that takes a
- * <code>String</code> (the detail message) and a <code>Throwable</code> (the
+ * {@code Throwable} (the cause), and one that takes a
+ * {@code String} (the detail message) and a {@code Throwable} (the
  * cause).
  *
  * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
  * which allows programmatic access to the stack trace information that was
  * previously available only in text form, via the various forms of the
  * {@link #printStackTrace()} method.  This information has been added to the
- * <i>serialized representation</i> of this class so <tt>getStackTrace</tt>
- * and <tt>printStackTrace</tt> will operate properly on a throwable that
+ * <i>serialized representation</i> of this class so {@code getStackTrace}
+ * and {@code printStackTrace} will operate properly on a throwable that
  * was obtained by deserialization.
  *
  * @author  unascribed
@@ -162,7 +162,7 @@
 
     /**
      * Specific details about the Throwable.  For example, for
-     * <tt>FileNotFoundException</tt>, this contains the name of
+     * {@code FileNotFoundException}, this contains the name of
      * the file that could not be found.
      *
      * @serial
@@ -212,7 +212,7 @@
     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 
     /**
-     * Constructs a new throwable with <code>null</code> as its detail message.
+     * Constructs a new throwable with {@code null} as its detail message.
      * The cause is not initialized, and may subsequently be initialized by a
      * call to {@link #initCause}.
      *
@@ -242,7 +242,7 @@
     /**
      * Constructs a new throwable with the specified detail message and
      * cause.  <p>Note that the detail message associated with
-     * <code>cause</code> is <i>not</i> automatically incorporated in
+     * {@code cause} is <i>not</i> automatically incorporated in
      * this throwable's detail message.
      *
      * <p>The {@link #fillInStackTrace()} method is called to initialize
@@ -251,7 +251,7 @@
      * @param  message the detail message (which is saved for later retrieval
      *         by the {@link #getMessage()} method).
      * @param  cause the cause (which is saved for later retrieval by the
-     *         {@link #getCause()} method).  (A <tt>null</tt> value is
+     *         {@link #getCause()} method).  (A {@code null} value is
      *         permitted, and indicates that the cause is nonexistent or
      *         unknown.)
      * @since  1.4
@@ -264,8 +264,8 @@
 
     /**
      * Constructs a new throwable with the specified cause and a detail
-     * message of <tt>(cause==null ? null : cause.toString())</tt> (which
-     * typically contains the class and detail message of <tt>cause</tt>).
+     * message of {@code (cause==null ? null : cause.toString())} (which
+     * typically contains the class and detail message of {@code cause}).
      * This constructor is useful for throwables that are little more than
      * wrappers for other throwables (for example, {@link
      * java.security.PrivilegedActionException}).
@@ -274,7 +274,7 @@
      * the stack trace data in the newly created throwable.
      *
      * @param  cause the cause (which is saved for later retrieval by the
-     *         {@link #getCause()} method).  (A <tt>null</tt> value is
+     *         {@link #getCause()} method).  (A {@code null} value is
      *         permitted, and indicates that the cause is nonexistent or
      *         unknown.)
      * @since  1.4
@@ -288,8 +288,8 @@
     /**
      * Returns the detail message string of this throwable.
      *
-     * @return  the detail message string of this <tt>Throwable</tt> instance
-     *          (which may be <tt>null</tt>).
+     * @return  the detail message string of this {@code Throwable} instance
+     *          (which may be {@code null}).
      */
     public String getMessage() {
         return detailMessage;
@@ -300,7 +300,7 @@
      * Subclasses may override this method in order to produce a
      * locale-specific message.  For subclasses that do not override this
      * method, the default implementation returns the same result as
-     * <code>getMessage()</code>.
+     * {@code getMessage()}.
      *
      * @return  The localized description of this throwable.
      * @since   JDK1.1
@@ -310,22 +310,22 @@
     }
 
     /**
-     * Returns the cause of this throwable or <code>null</code> if the
+     * Returns the cause of this throwable or {@code null} if the
      * cause is nonexistent or unknown.  (The cause is the throwable that
      * caused this throwable to get thrown.)
      *
      * <p>This implementation returns the cause that was supplied via one of
-     * the constructors requiring a <tt>Throwable</tt>, or that was set after
+     * the constructors requiring a {@code Throwable}, or that was set after
      * creation with the {@link #initCause(Throwable)} method.  While it is
      * typically unnecessary to override this method, a subclass can override
      * it to return a cause set by some other means.  This is appropriate for
      * a "legacy chained throwable" that predates the addition of chained
-     * exceptions to <tt>Throwable</tt>.  Note that it is <i>not</i>
-     * necessary to override any of the <tt>PrintStackTrace</tt> methods,
-     * all of which invoke the <tt>getCause</tt> method to determine the
+     * exceptions to {@code Throwable}.  Note that it is <i>not</i>
+     * necessary to override any of the {@code PrintStackTrace} methods,
+     * all of which invoke the {@code getCause} method to determine the
      * cause of a throwable.
      *
-     * @return  the cause of this throwable or <code>null</code> if the
+     * @return  the cause of this throwable or {@code null} if the
      *          cause is nonexistent or unknown.
      * @since 1.4
      */
@@ -345,11 +345,11 @@
      * even once.
      *
      * @param  cause the cause (which is saved for later retrieval by the
-     *         {@link #getCause()} method).  (A <tt>null</tt> value is
+     *         {@link #getCause()} method).  (A {@code null} value is
      *         permitted, and indicates that the cause is nonexistent or
      *         unknown.)
-     * @return  a reference to this <code>Throwable</code> instance.
-     * @throws IllegalArgumentException if <code>cause</code> is this
+     * @return  a reference to this {@code Throwable} instance.
+     * @throws IllegalArgumentException if {@code cause} is this
      *         throwable.  (A throwable cannot be its own cause.)
      * @throws IllegalStateException if this throwable was
      *         created with {@link #Throwable(Throwable)} or
@@ -375,7 +375,7 @@
      * <li> the result of invoking this object's {@link #getLocalizedMessage}
      *      method
      * </ul>
-     * If <tt>getLocalizedMessage</tt> returns <tt>null</tt>, then just
+     * If {@code getLocalizedMessage} returns {@code null}, then just
      * the class name is returned.
      *
      * @return a string representation of this throwable.
@@ -389,8 +389,8 @@
     /**
      * Prints this throwable and its backtrace to the
      * standard error stream. This method prints a stack trace for this
-     * <code>Throwable</code> object on the error output stream that is
-     * the value of the field <code>System.err</code>. The first line of
+     * {@code Throwable} object on the error output stream that is
+     * the value of the field {@code System.err}. The first line of
      * output contains the result of the {@link #toString()} method for
      * this object.  Remaining lines represent data previously recorded by
      * the method {@link #fillInStackTrace()}. The format of this
@@ -435,7 +435,7 @@
      *         at Junk.c(Junk.java:21)
      *         ... 3 more
      * </pre>
-     * Note the presence of lines containing the characters <tt>"..."</tt>.
+     * Note the presence of lines containing the characters {@code "..."}.
      * These lines indicate that the remainder of the stack trace for this
      * exception matches the indicated number of frames from the bottom of the
      * stack trace of the exception that was caused by this exception (the
@@ -542,14 +542,17 @@
     /**
      * Prints this throwable and its backtrace to the specified print stream.
      *
-     * @param s <code>PrintStream</code> to use for output
+     * @param s {@code PrintStream} to use for output
      */
     public void printStackTrace(PrintStream s) {
         printStackTrace(new WrappedPrintStream(s));
     }
 
     private void printStackTrace(PrintStreamOrWriter s) {
-        Set<Throwable> dejaVu = new HashSet<Throwable>();
+        // Guard against malicious overrides of Throwable.equals by
+        // using a Set with identity equality semantics.
+        Set<Throwable> dejaVu =
+            Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
         dejaVu.add(this);
 
         synchronized (s.lock()) {
@@ -616,7 +619,7 @@
      * Prints this throwable and its backtrace to the specified
      * print writer.
      *
-     * @param s <code>PrintWriter</code> to use for output
+     * @param s {@code PrintWriter} to use for output
      * @since   JDK1.1
      */
     public void printStackTrace(PrintWriter s) {
@@ -669,10 +672,10 @@
 
     /**
      * Fills in the execution stack trace. This method records within this
-     * <code>Throwable</code> object information about the current state of
+     * {@code Throwable} object information about the current state of
      * the stack frames for the current thread.
      *
-     * @return  a reference to this <code>Throwable</code> instance.
+     * @return  a reference to this {@code Throwable} instance.
      * @see     java.lang.Throwable#printStackTrace()
      */
     public synchronized native Throwable fillInStackTrace();
@@ -694,7 +697,7 @@
      * this throwable is permitted to return a zero-length array from this
      * method.  Generally speaking, the array returned by this method will
      * contain one element for every frame that would be printed by
-     * <tt>printStackTrace</tt>.
+     * {@code printStackTrace}.
      *
      * @return an array of stack trace elements representing the stack trace
      *         pertaining to this throwable.
@@ -727,14 +730,14 @@
      * read from a serialization stream.
      *
      * @param   stackTrace the stack trace elements to be associated with
-     * this <code>Throwable</code>.  The specified array is copied by this
+     * this {@code Throwable}.  The specified array is copied by this
      * call; changes in the specified array after the method invocation
-     * returns will have no affect on this <code>Throwable</code>'s stack
+     * returns will have no affect on this {@code Throwable}'s stack
      * trace.
      *
-     * @throws NullPointerException if <code>stackTrace</code> is
-     *         <code>null</code>, or if any of the elements of
-     *         <code>stackTrace</code> are <code>null</code>
+     * @throws NullPointerException if {@code stackTrace} is
+     *         {@code null}, or if any of the elements of
+     *         {@code stackTrace} are {@code null}
      *
      * @since  1.4
      */
@@ -761,8 +764,8 @@
      * package-protection for use by SharedSecrets.
      *
      * @param index index of the element to return.
-     * @throws IndexOutOfBoundsException if <tt>index &lt; 0 ||
-     *         index &gt;= getStackTraceDepth() </tt>
+     * @throws IndexOutOfBoundsException if {@code index < 0 ||
+     *         index >= getStackTraceDepth() }
      */
     native StackTraceElement getStackTraceElement(int index);
 
@@ -794,14 +797,27 @@
      * were suppressed, typically by the automatic resource management
      * statement, in order to deliver this exception.
      *
+     * <p>Note that when one exception {@linkplain
+     * #initCause(Throwable) causes} another exception, the first
+     * exception is usually caught and then the second exception is
+     * thrown in response.  In contrast, when one exception suppresses
+     * another, two exceptions are thrown in sibling code blocks, such
+     * as in a {@code try} block and in its {@code finally} block, and
+     * control flow can only continue with one exception so the second
+     * is recorded as a suppressed exception of the first.
+     *
      * @param exception the exception to be added to the list of
      *        suppressed exceptions
      * @throws NullPointerException if {@code exception} is null
+     * @throws IllegalArgumentException if {@code exception} is this
+     *         throwable; a throwable cannot suppress itself.
      * @since 1.7
      */
     public synchronized void addSuppressedException(Throwable exception) {
         if (exception == null)
             throw new NullPointerException(NULL_CAUSE_MESSAGE);
+        if (exception == this)
+            throw new IllegalArgumentException("Self-suppression not permitted");
 
         if (suppressedExceptions.size() == 0)
             suppressedExceptions = new ArrayList<Throwable>();
--- a/src/share/classes/java/nio/Bits.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/nio/Bits.java	Thu Aug 12 11:23:15 2010 -0700
@@ -596,6 +596,9 @@
         return pageSize;
     }
 
+    static int pageCount(long size) {
+        return (int)(size + (long)pageSize() - 1L) / pageSize();
+    }
 
     private static boolean unaligned;
     private static boolean unalignedKnown = false;
--- a/src/share/classes/java/nio/MappedByteBuffer.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/nio/MappedByteBuffer.java	Thu Aug 12 11:23:15 2010 -0700
@@ -25,6 +25,8 @@
 
 package java.nio;
 
+import sun.misc.Unsafe;
+
 
 /**
  * A direct byte buffer whose content is a memory-mapped region of a file.
@@ -93,6 +95,22 @@
             throw new UnsupportedOperationException();
     }
 
+    // Returns the distance (in bytes) of the buffer from the page aligned address
+    // of the mapping. Computed each time to avoid storing in every direct buffer.
+    private long mappingOffset() {
+        int ps = Bits.pageSize();
+        long offset = address % ps;
+        return (offset >= 0) ? offset : (ps + offset);
+    }
+
+    private long mappingAddress(long mappingOffset) {
+        return address - mappingOffset;
+    }
+
+    private long mappingLength(long mappingOffset) {
+        return (long)capacity() + mappingOffset;
+    }
+
     /**
      * Tells whether or not this buffer's content is resident in physical
      * memory.
@@ -115,7 +133,9 @@
         checkMapped();
         if ((address == 0) || (capacity() == 0))
             return true;
-        return isLoaded0(((DirectByteBuffer)this).address(), capacity());
+        long offset = mappingOffset();
+        long length = mappingLength(offset);
+        return isLoaded0(mappingAddress(offset), length, Bits.pageCount(length));
     }
 
     /**
@@ -132,7 +152,20 @@
         checkMapped();
         if ((address == 0) || (capacity() == 0))
             return this;
-        load0(((DirectByteBuffer)this).address(), capacity(), Bits.pageSize());
+        long offset = mappingOffset();
+        long length = mappingLength(offset);
+        load0(mappingAddress(offset), length);
+
+        // touch each page
+        Unsafe unsafe = Unsafe.getUnsafe();
+        int ps = Bits.pageSize();
+        int count = Bits.pageCount(length);
+        long a = mappingAddress(offset);
+        for (int i=0; i<count; i++) {
+            unsafe.getByte(a);
+            a += ps;
+        }
+
         return this;
     }
 
@@ -156,14 +189,15 @@
      */
     public final MappedByteBuffer force() {
         checkMapped();
-        if ((address == 0) || (capacity() == 0))
-            return this;
-        force0(((DirectByteBuffer)this).address(), capacity());
+        if ((address != 0) && (capacity() != 0)) {
+            long offset = mappingOffset();
+            force0(mappingAddress(offset), mappingLength(offset));
+        }
         return this;
     }
 
-    private native boolean isLoaded0(long address, long length);
-    private native int load0(long address, long length, int pageSize);
+    private native boolean isLoaded0(long address, long length, int pageCount);
+    private native void load0(long address, long length);
     private native void force0(long address, long length);
 
 }
--- a/src/share/classes/java/security/cert/X509CRL.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/security/cert/X509CRL.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, 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
@@ -387,7 +387,7 @@
 
     /**
      * Gets the signature algorithm name for the CRL
-     * signature algorithm. An example is the string "SHA-1/DSA".
+     * signature algorithm. An example is the string "SHA256withRSA".
      * The ASN.1 definition for this is:
      * <pre>
      * signatureAlgorithm   AlgorithmIdentifier<p>
--- a/src/share/classes/java/security/cert/X509Certificate.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/security/cert/X509Certificate.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, 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
@@ -352,7 +352,7 @@
 
     /**
      * Gets the signature algorithm name for the certificate
-     * signature algorithm. An example is the string "SHA-1/DSA".
+     * signature algorithm. An example is the string "SHA256withRSA".
      * The ASN.1 definition for this is:
      * <pre>
      * signatureAlgorithm   AlgorithmIdentifier<p>
--- a/src/share/classes/java/util/LinkedList.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/java/util/LinkedList.java	Thu Aug 12 11:23:15 2010 -0700
@@ -26,18 +26,9 @@
 package java.util;
 
 /**
- * Linked list implementation of the {@code List} interface.  Implements all
- * optional list operations, and permits all elements (including
- * {@code null}).  In addition to implementing the {@code List} interface,
- * the {@code LinkedList} class provides uniformly named methods to
- * {@code get}, {@code remove} and {@code insert} an element at the
- * beginning and end of the list.  These operations allow linked lists to be
- * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque
- * double-ended queue}.
- *
- * <p>The class implements the {@code Deque} interface, providing
- * first-in-first-out queue operations for {@code add},
- * {@code poll}, along with other stack and deque operations.
+ * Linked list implementation of the {@link List} and {@link Deque} interfaces.
+ * Implements all optional operations, and permits all elements (including
+ * {@code null}).
  *
  * <p>All of the operations perform as could be expected for a doubly-linked
  * list.  Operations that index into the list will traverse the list from
--- a/src/share/classes/sun/net/dns/ResolverConfiguration.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/net/dns/ResolverConfiguration.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, 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
@@ -26,7 +26,6 @@
 package sun.net.dns;
 
 import java.util.List;
-import java.io.IOException;
 
 /**
  * The configuration of the client resolver.
@@ -68,7 +67,7 @@
      *
      * @return list of domain names
      */
-    public abstract List searchlist();
+    public abstract List<String> searchlist();
 
     /**
      * Returns a list of name servers used for host name lookup.
@@ -78,7 +77,7 @@
      *
      * @return list of the name servers
      */
-    public abstract List nameservers();
+    public abstract List<String> nameservers();
 
 
     /**
--- a/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2010, 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
@@ -45,20 +45,21 @@
 public final class DNSNameService implements NameService {
 
     // List of domains specified by property
-    private LinkedList domainList = null;
+    private LinkedList<String> domainList = null;
 
     // JNDI-DNS URL for name servers specified via property
     private String nameProviderUrl = null;
 
     // Per-thread soft cache of the last temporary context
-    private static ThreadLocal contextRef = new ThreadLocal();
+    private static ThreadLocal<SoftReference<ThreadContext>> contextRef =
+            new ThreadLocal<>();
 
     // Simple class to encapsulate the temporary context
     private static class ThreadContext {
         private DirContext dirCtxt;
-        private List nsList;
+        private List<String> nsList;
 
-        public ThreadContext(DirContext dirCtxt, List nsList) {
+        public ThreadContext(DirContext dirCtxt, List<String> nsList) {
             this.dirCtxt = dirCtxt;
             this.nsList = nsList;
         }
@@ -67,16 +68,16 @@
             return dirCtxt;
         }
 
-        public List nameservers() {
+        public List<String> nameservers() {
             return nsList;
         }
     }
 
     // Returns a per-thread DirContext
     private DirContext getTemporaryContext() throws NamingException {
-        SoftReference ref = (SoftReference)contextRef.get();
+        SoftReference<ThreadContext> ref = contextRef.get();
         ThreadContext thrCtxt = null;
-        List nsList = null;
+        List<String> nsList = null;
 
         // if no property specified we need to obtain the list of servers
         //
@@ -87,7 +88,7 @@
         // specified then we need to check if the DNS configuration
         // has changed.
         //
-        if ((ref != null) && ((thrCtxt = (ThreadContext)ref.get()) != null)) {
+        if ((ref != null) && ((thrCtxt = ref.get()) != null)) {
             if (nameProviderUrl == null) {
                 if (!thrCtxt.nameservers().equals(nsList)) {
                     // DNS configuration has changed
@@ -98,7 +99,7 @@
 
         // new thread context needs to be created
         if (thrCtxt == null) {
-            final Hashtable<String,Object> env = new Hashtable<String,Object>();
+            final Hashtable<String,Object> env = new Hashtable<>();
             env.put("java.naming.factory.initial",
                     "com.sun.jndi.dns.DnsContextFactory");
 
@@ -119,10 +120,9 @@
             //
             DirContext dirCtxt;
             try {
-                dirCtxt = (DirContext)
-                    java.security.AccessController.doPrivileged(
-                        new java.security.PrivilegedExceptionAction() {
-                            public Object run() throws NamingException {
+                dirCtxt = java.security.AccessController.doPrivileged(
+                        new java.security.PrivilegedExceptionAction<DirContext>() {
+                            public DirContext run() throws NamingException {
                                 // Create the DNS context using NamingManager rather than using
                                 // the initial context constructor. This avoids having the initial
                                 // context constructor call itself.
@@ -130,7 +130,7 @@
                                 if (!(ctx instanceof DirContext)) {
                                     return null; // cannot create a DNS context
                                 }
-                                return ctx;
+                                return (DirContext)ctx;
                             }
                     });
             } catch (java.security.PrivilegedActionException pae) {
@@ -161,18 +161,18 @@
      *
      * @throws  UnknownHostException if lookup fails or other error.
      */
-    private ArrayList resolve(final DirContext ctx, final String name, final String[] ids,
-                              int depth) throws UnknownHostException
+    private ArrayList<String> resolve(final DirContext ctx, final String name,
+                                      final String[] ids, int depth)
+            throws UnknownHostException
     {
-        ArrayList results = new ArrayList();
+        ArrayList<String> results = new ArrayList<>();
         Attributes attrs;
 
         // do the query
         try {
-            attrs = (Attributes)
-                java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedExceptionAction() {
-                        public Object run() throws NamingException {
+            attrs = java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedExceptionAction<Attributes>() {
+                        public Attributes run() throws NamingException {
                             return ctx.getAttributes(name, ids);
                         }
                 });
@@ -181,7 +181,7 @@
         }
 
         // non-requested type returned so enumeration is empty
-        NamingEnumeration ne = attrs.getAll();
+        NamingEnumeration<? extends Attribute> ne = attrs.getAll();
         if (!ne.hasMoreElements()) {
             throw new UnknownHostException("DNS record not found");
         }
@@ -190,7 +190,7 @@
         UnknownHostException uhe = null;
         try {
             while (ne.hasMoreElements()) {
-                Attribute attr = (Attribute)ne.next();
+                Attribute attr = ne.next();
                 String attrID = attr.getID();
 
                 for (NamingEnumeration e = attr.getAll(); e.hasMoreElements();) {
@@ -251,13 +251,12 @@
             // no property specified so check host DNS resolver configured
             // with at least one nameserver in dotted notation.
             //
-            List nsList = ResolverConfiguration.open().nameservers();
-            if (nsList.size() == 0)
+            List<String> nsList = ResolverConfiguration.open().nameservers();
+            if (nsList.isEmpty()) {
                 throw new RuntimeException("no nameservers provided");
+            }
             boolean found = false;
-            Iterator i = nsList.iterator();
-            while (i.hasNext()) {
-                String addr = (String)i.next();
+            for (String addr: nsList) {
                 if (IPAddressUtil.isIPv4LiteralAddress(addr) ||
                     IPAddressUtil.isIPv6LiteralAddress(addr)) {
                     found = true;
@@ -308,8 +307,8 @@
         // suffix if the list has one entry.
 
         if (results == null) {
-            List searchList = null;
-            Iterator i;
+            List<String> searchList = null;
+            Iterator<String> i;
             boolean usingSearchList = false;
 
             if (domainList != null) {
@@ -324,7 +323,7 @@
 
             // iterator through each domain suffix
             while (i.hasNext()) {
-                String parentDomain = (String)i.next();
+                String parentDomain = i.next();
                 int start = 0;
                 while ((start = parentDomain.indexOf(".")) != -1
                        && start < parentDomain.length() -1) {
@@ -407,7 +406,7 @@
             String literalip = "";
             String[] ids = { "PTR" };
             DirContext ctx;
-            ArrayList results = null;
+            ArrayList<String> results = null;
             try {
                 ctx = getTemporaryContext();
             } catch (NamingException nx) {
@@ -420,7 +419,7 @@
                 literalip += "IN-ADDR.ARPA.";
 
                 results = resolve(ctx, literalip, ids, 0);
-                host = (String)results.get(0);
+                host = results.get(0);
             } else if (addr.length == 16) { // IPv6 Address
                 /**
                  * Because RFC 3152 changed the root domain name for reverse
@@ -437,7 +436,7 @@
 
                 try {
                     results = resolve(ctx, ip6lit, ids, 0);
-                    host = (String)results.get(0);
+                    host = results.get(0);
                 } catch (UnknownHostException e) {
                     host = null;
                 }
@@ -445,7 +444,7 @@
                     // IP6.ARPA lookup failed, let's try the older IP6.INT
                     ip6lit = literalip + "IP6.INT.";
                     results = resolve(ctx, ip6lit, ids, 0);
-                    host = (String)results.get(0);
+                    host = results.get(0);
                 }
             }
         } catch (Exception e) {
@@ -478,11 +477,10 @@
      * @return String containing the JNDI-DNS provider URL
      *         corresponding to the supplied List of nameservers.
      */
-    private static String createProviderURL(List nsList) {
-        Iterator i = nsList.iterator();
+    private static String createProviderURL(List<String> nsList) {
         StringBuffer sb = new StringBuffer();
-        while (i.hasNext()) {
-            appendIfLiteralAddress((String)i.next(), sb);
+        for (String s: nsList) {
+            appendIfLiteralAddress(s, sb);
         }
         return sb.toString();
     }
--- a/src/share/classes/sun/nio/ch/SocketAdaptor.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/nio/ch/SocketAdaptor.java	Thu Aug 12 11:23:15 2010 -0700
@@ -336,7 +336,12 @@
     }
 
     public void sendUrgentData(int data) throws IOException {
-        throw new SocketException("Urgent data not supported");
+        synchronized (sc.blockingLock()) {
+            if (!sc.isBlocking())
+                throw new IllegalBlockingModeException();
+            int n = sc.sendOutOfBandData((byte)data);
+            assert n == 1;
+        }
     }
 
     public void setOOBInline(boolean on) throws SocketException {
--- a/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Thu Aug 12 11:23:15 2010 -0700
@@ -498,6 +498,36 @@
         return write0(Util.subsequence(srcs, offset, length));
     }
 
+    // package-private
+    int sendOutOfBandData(byte b) throws IOException {
+        synchronized (writeLock) {
+            ensureWriteOpen();
+            int n = 0;
+            try {
+                begin();
+                synchronized (stateLock) {
+                    if (!isOpen())
+                        return 0;
+                    writerThread = NativeThread.current();
+                }
+                for (;;) {
+                    n = sendOutOfBandData(fd, b);
+                    if ((n == IOStatus.INTERRUPTED) && isOpen())
+                        continue;
+                    return IOStatus.normalize(n);
+                }
+            } finally {
+                writerCleanup();
+                end((n > 0) || (n == IOStatus.UNAVAILABLE));
+                synchronized (stateLock) {
+                    if ((n <= 0) && (!isOutputOpen))
+                        throw new AsynchronousCloseException();
+                }
+                assert IOStatus.check(n);
+            }
+        }
+    }
+
     protected void implConfigureBlocking(boolean block) throws IOException {
         IOUtil.configureBlocking(fd, block);
     }
@@ -957,6 +987,9 @@
                                            boolean block, boolean ready)
         throws IOException;
 
+    private static native int sendOutOfBandData(FileDescriptor fd, byte data)
+        throws IOException;
+
     static {
         Util.load();
         nd = new SocketDispatcher();
--- a/src/share/classes/sun/security/krb5/Config.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/krb5/Config.java	Thu Aug 12 11:23:15 2010 -0700
@@ -42,6 +42,8 @@
 import java.util.StringTokenizer;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
+import java.util.List;
+import sun.net.dns.ResolverConfiguration;
 import sun.security.krb5.internal.crypto.EType;
 import sun.security.krb5.internal.ktab.*;
 import sun.security.krb5.internal.Krb5;
@@ -1180,6 +1182,33 @@
         }
         // get the domain realm mapping from the configuration
         String mapRealm = PrincipalName.mapHostToRealm(hostName);
+        if (mapRealm == null) {
+            // No match. Try search and/or domain in /etc/resolv.conf
+            List<String> srchlist = ResolverConfiguration.open().searchlist();
+            for (String domain: srchlist) {
+                realm = checkRealm(domain);
+                if (realm != null) {
+                    break;
+                }
+            }
+        } else {
+            realm = checkRealm(mapRealm);
+        }
+        if (realm == null) {
+            throw new KrbException(Krb5.KRB_ERR_GENERIC,
+                                "Unable to locate Kerberos realm");
+        }
+        return realm;
+    }
+
+    /**
+     * Check if the provided realm is the correct realm
+     * @return the realm if correct, or null otherwise
+     */
+    private static String checkRealm(String mapRealm) {
+        if (DEBUG) {
+            System.out.println("getRealmFromDNS: trying " + mapRealm);
+        }
         String[] records = null;
         String newRealm = mapRealm;
         while ((records == null) && (newRealm != null)) {
@@ -1188,23 +1217,14 @@
             newRealm = Realm.parseRealmComponent(newRealm);
             // if no DNS TXT records found, try again using sub-realm
         }
-        if (records == null) {
-            // no DNS TXT records
-            throw new KrbException(Krb5.KRB_ERR_GENERIC,
-                                "Unable to locate Kerberos realm");
-        }
-        boolean found = false;
-        for (int i = 0; i < records.length; i++) {
-            if (records[i].equals(mapRealm)) {
-                found = true;
-                realm = records[i];
+        if (records != null) {
+            for (int i = 0; i < records.length; i++) {
+                if (records[i].equalsIgnoreCase(mapRealm)) {
+                    return records[i];
+                }
             }
         }
-        if (found == false) {
-            throw new KrbException(Krb5.KRB_ERR_GENERIC,
-                                "Unable to locate Kerberos realm");
-        }
-        return realm;
+        return null;
     }
 
     /**
@@ -1218,10 +1238,16 @@
         String kdcs = null;
         String[] srvs = null;
         // locate DNS SRV record using UDP
-        srvs = KrbServiceLocator.getKerberosService(realm, "_udp.");
+        if (DEBUG) {
+            System.out.println("getKDCFromDNS using UDP");
+        }
+        srvs = KrbServiceLocator.getKerberosService(realm, "_udp");
         if (srvs == null) {
             // locate DNS SRV record using TCP
-            srvs = KrbServiceLocator.getKerberosService(realm, "_tcp.");
+            if (DEBUG) {
+                System.out.println("getKDCFromDNS using UDP");
+            }
+            srvs = KrbServiceLocator.getKerberosService(realm, "_tcp");
         }
         if (srvs == null) {
             // no DNS SRV records
--- a/src/share/classes/sun/security/krb5/Credentials.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/krb5/Credentials.java	Thu Aug 12 11:23:15 2010 -0700
@@ -36,6 +36,7 @@
 import sun.security.krb5.internal.crypto.EType;
 import java.io.IOException;
 import java.util.Date;
+import java.util.Locale;
 import java.net.InetAddress;
 
 /**
@@ -287,7 +288,7 @@
             // The default ticket cache on Windows is not a file.
             String os = java.security.AccessController.doPrivileged(
                         new sun.security.action.GetPropertyAction("os.name"));
-            if (os.toUpperCase().startsWith("WINDOWS")) {
+            if (os.toUpperCase(Locale.ENGLISH).startsWith("WINDOWS")) {
                 Credentials creds = acquireDefaultCreds();
                 if (creds == null) {
                     if (DEBUG) {
--- a/src/share/classes/sun/security/pkcs/PKCS9Attribute.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/pkcs/PKCS9Attribute.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, 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
@@ -28,6 +28,7 @@
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.cert.CertificateException;
+import java.util.Locale;
 import java.util.Date;
 import java.util.Hashtable;
 import sun.security.x509.CertificateExtensions;
@@ -742,7 +743,7 @@
      * the name.
      */
     public static ObjectIdentifier getOID(String name) {
-        return NAME_OID_TABLE.get(name.toLowerCase());
+        return NAME_OID_TABLE.get(name.toLowerCase(Locale.ENGLISH));
     }
 
     /**
--- a/src/share/classes/sun/security/pkcs11/P11Cipher.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/pkcs11/P11Cipher.java	Thu Aug 12 11:23:15 2010 -0700
@@ -26,6 +26,7 @@
 
 import java.nio.ByteBuffer;
 import java.util.Arrays;
+import java.util.Locale;
 
 import java.security.*;
 import java.security.spec.*;
@@ -201,7 +202,7 @@
     }
 
     private int parseMode(String mode) throws NoSuchAlgorithmException {
-        mode = mode.toUpperCase();
+        mode = mode.toUpperCase(Locale.ENGLISH);
         int result;
         if (mode.equals("ECB")) {
             result = MODE_ECB;
@@ -222,7 +223,7 @@
             throws NoSuchPaddingException {
         paddingObj = null;
         padBuffer = null;
-        padding = padding.toUpperCase();
+        padding = padding.toUpperCase(Locale.ENGLISH);
         if (padding.equals("NOPADDING")) {
             paddingType = PAD_NONE;
         } else if (padding.equals("PKCS5PADDING")) {
--- a/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Thu Aug 12 11:23:15 2010 -0700
@@ -29,6 +29,8 @@
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.*;
 
+import java.util.Locale;
+
 import javax.crypto.*;
 import javax.crypto.spec.*;
 
@@ -110,7 +112,7 @@
 
     protected void engineSetPadding(String padding)
             throws NoSuchPaddingException {
-        String lowerPadding = padding.toLowerCase();
+        String lowerPadding = padding.toLowerCase(Locale.ENGLISH);
         if (lowerPadding.equals("pkcs1Padding")) {
             // empty
         } else {
--- a/src/share/classes/sun/security/provider/certpath/URICertStore.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/provider/certpath/URICertStore.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2010 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
@@ -52,6 +52,7 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
+import java.util.Locale;
 import sun.security.x509.AccessDescription;
 import sun.security.x509.GeneralNameInterface;
 import sun.security.x509.URIName;
@@ -162,7 +163,7 @@
         }
         this.uri = ((URICertStoreParameters) params).uri;
         // if ldap URI, use an LDAPCertStore to fetch certs and CRLs
-        if (uri.getScheme().toLowerCase().equals("ldap")) {
+        if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
             if (LDAP.helper() == null)
                 throw new NoSuchAlgorithmException("LDAP not present");
             ldap = true;
--- a/src/share/classes/sun/security/util/Debug.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/util/Debug.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2010, 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
@@ -28,6 +28,7 @@
 import java.math.BigInteger;
 import java.util.regex.Pattern;
 import java.util.regex.Matcher;
+import java.util.Locale;
 
 /**
  * A utility class for debuging.
@@ -262,7 +263,7 @@
             source = left;
 
             // convert the rest to lower-case characters
-            target.append(source.toString().toLowerCase());
+            target.append(source.toString().toLowerCase(Locale.ENGLISH));
 
             return target.toString();
         }
--- a/src/share/classes/sun/security/util/DerOutputStream.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/util/DerOutputStream.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, 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
@@ -25,17 +25,16 @@
 
 package sun.security.util;
 
-import java.io.FilterOutputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.OutputStream;
 import java.io.IOException;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.TimeZone;
-import java.util.Vector;
 import java.util.Comparator;
 import java.util.Arrays;
 import java.math.BigInteger;
+import java.util.Locale;
 
 
 /**
@@ -501,7 +500,7 @@
             pattern = "yyyyMMddHHmmss'Z'";
         }
 
-        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
+        SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
         sdf.setTimeZone(tz);
         byte[] time = (sdf.format(d)).getBytes("ISO-8859-1");
 
--- a/src/share/classes/sun/security/x509/AVA.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/x509/AVA.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, 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
@@ -1227,7 +1227,7 @@
         (String keyword, int standard, Map<String, String> extraKeywordMap)
             throws IOException {
 
-        keyword = keyword.toUpperCase();
+        keyword = keyword.toUpperCase(Locale.ENGLISH);
         if (standard == AVA.RFC2253) {
             if (keyword.startsWith(" ") || keyword.endsWith(" ")) {
                 throw new IOException("Invalid leading or trailing space " +
--- a/src/share/classes/sun/security/x509/AlgorithmId.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/x509/AlgorithmId.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, 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
@@ -553,9 +553,10 @@
                 for (Enumeration<Object> enum_ = provs[i].keys();
                      enum_.hasMoreElements(); ) {
                     String alias = (String)enum_.nextElement();
+                    String upperCaseAlias = alias.toUpperCase(Locale.ENGLISH);
                     int index;
-                    if (alias.toUpperCase().startsWith("ALG.ALIAS") &&
-                        (index=alias.toUpperCase().indexOf("OID.", 0)) != -1) {
+                    if (upperCaseAlias.startsWith("ALG.ALIAS") &&
+                            (index=upperCaseAlias.indexOf("OID.", 0)) != -1) {
                         index += "OID.".length();
                         if (index == alias.length()) {
                             // invalid alias entry
@@ -565,19 +566,26 @@
                             oidTable = new HashMap<String,ObjectIdentifier>();
                         }
                         oidString = alias.substring(index);
-                        String stdAlgName
-                            = provs[i].getProperty(alias).toUpperCase();
-                        if (oidTable.get(stdAlgName) == null) {
+                        String stdAlgName = provs[i].getProperty(alias);
+                        if (stdAlgName != null) {
+                            stdAlgName = stdAlgName.toUpperCase(Locale.ENGLISH);
+                        }
+                        if (stdAlgName != null &&
+                                oidTable.get(stdAlgName) == null) {
                             oidTable.put(stdAlgName,
                                          new ObjectIdentifier(oidString));
                         }
                     }
                 }
             }
+
+            if (oidTable == null) {
+                oidTable = new HashMap<String,ObjectIdentifier>(1);
+            }
             initOidTable = true;
         }
 
-        return oidTable.get(name.toUpperCase());
+        return oidTable.get(name.toUpperCase(Locale.ENGLISH));
     }
 
     private static ObjectIdentifier oid(int ... values) {
--- a/src/share/classes/sun/security/x509/DNSName.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/x509/DNSName.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, 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
@@ -26,6 +26,7 @@
 package sun.security.x509;
 
 import java.io.IOException;
+import java.util.Locale;
 
 import sun.security.util.*;
 
@@ -198,8 +199,9 @@
         else if (inputName.getType() != NAME_DNS)
             constraintType = NAME_DIFF_TYPE;
         else {
-            String inName = (((DNSName)inputName).getName()).toLowerCase();
-            String thisName = name.toLowerCase();
+            String inName =
+                (((DNSName)inputName).getName()).toLowerCase(Locale.ENGLISH);
+            String thisName = name.toLowerCase(Locale.ENGLISH);
             if (inName.equals(thisName))
                 constraintType = NAME_MATCH;
             else if (thisName.endsWith(inName)) {
--- a/src/share/classes/sun/security/x509/RFC822Name.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/share/classes/sun/security/x509/RFC822Name.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, 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
@@ -26,6 +26,7 @@
 package sun.security.x509;
 
 import java.io.IOException;
+import java.util.Locale;
 
 import sun.security.util.*;
 
@@ -187,8 +188,9 @@
             constraintType = NAME_DIFF_TYPE;
         } else {
             //RFC2459 specifies that case is not significant in RFC822Names
-            String inName = (((RFC822Name)inputName).getName()).toLowerCase();
-            String thisName = name.toLowerCase();
+            String inName =
+                (((RFC822Name)inputName).getName()).toLowerCase(Locale.ENGLISH);
+            String thisName = name.toLowerCase(Locale.ENGLISH);
             if (inName.equals(thisName)) {
                 constraintType = NAME_MATCH;
             } else if (thisName.endsWith(inName)) {
--- a/src/solaris/classes/sun/net/dns/ResolverConfigurationImpl.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/solaris/classes/sun/net/dns/ResolverConfigurationImpl.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, 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
@@ -56,8 +56,11 @@
     // Parse /etc/resolv.conf to get the values for a particular
     // keyword.
     //
-    private LinkedList resolvconf(String keyword, int maxperkeyword, int maxkeywords) {
-        LinkedList ll = new LinkedList();
+    private LinkedList<String> resolvconf(String keyword,
+                                          int maxperkeyword,
+                                          int maxkeywords)
+    {
+        LinkedList<String> ll = new LinkedList<>();
 
         try {
             BufferedReader in =
@@ -99,8 +102,8 @@
         return ll;
     }
 
-    private LinkedList searchlist;
-    private LinkedList nameservers;
+    private LinkedList<String> searchlist;
+    private LinkedList<String> nameservers;
 
 
     // Load DNS configuration from OS
@@ -118,9 +121,9 @@
 
         // get the name servers from /etc/resolv.conf
         nameservers =
-            (LinkedList)java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
-                    public Object run() {
+            java.security.AccessController.doPrivileged(
+                new java.security.PrivilegedAction<LinkedList<String>>() {
+                    public LinkedList<String> run() {
                         // typically MAXNS is 3 but we've picked 5 here
                         // to allow for additional servers if required.
                         return resolvconf("nameserver", 1, 5);
@@ -137,15 +140,15 @@
 
     // obtain search list or local domain
 
-    private LinkedList getSearchList() {
+    private LinkedList<String> getSearchList() {
 
-        LinkedList sl;
+        LinkedList<String> sl;
 
         // first try the search keyword in /etc/resolv.conf
 
-        sl = (LinkedList)java.security.AccessController.doPrivileged(
-                 new java.security.PrivilegedAction() {
-                    public Object run() {
+        sl = java.security.AccessController.doPrivileged(
+                 new java.security.PrivilegedAction<LinkedList<String>>() {
+                    public LinkedList<String> run() {
                         LinkedList ll;
 
                         // first try search keyword (max 6 domains)
@@ -177,10 +180,10 @@
 
         // try domain keyword in /etc/resolv.conf
 
-        sl = (LinkedList)java.security.AccessController.doPrivileged(
-                 new java.security.PrivilegedAction() {
-                    public Object run() {
-                        LinkedList ll;
+        sl = java.security.AccessController.doPrivileged(
+                 new java.security.PrivilegedAction<LinkedList<String>>() {
+                    public LinkedList<String> run() {
+                        LinkedList<String> ll;
 
                         ll = resolvconf("domain", 1, 1);
                         if (ll.size() > 0) {
@@ -197,7 +200,7 @@
         // no local domain so try fallback (RPC) domain or
         // hostname
 
-        sl = new LinkedList();
+        sl = new LinkedList<>();
         String domain = fallbackDomain0();
         if (domain != null && domain.length() > 0) {
             sl.add(domain);
@@ -213,7 +216,7 @@
         opts = new OptionsImpl();
     }
 
-    public List searchlist() {
+    public List<String> searchlist() {
         synchronized (lock) {
             loadConfig();
 
@@ -222,7 +225,7 @@
         }
     }
 
-    public List nameservers() {
+    public List<String> nameservers() {
         synchronized (lock) {
             loadConfig();
 
--- a/src/solaris/native/java/net/NetworkInterface.c	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/solaris/native/java/net/NetworkInterface.c	Thu Aug 12 11:23:15 2010 -0700
@@ -131,7 +131,7 @@
 static short   getSubnet(JNIEnv *env, int sock, const char *ifname);
 static int     getIndex(int sock, const char *ifname);
 
-static int     getFlags(JNIEnv *env, int sock, const char *ifname);
+static int     getFlags(int sock, const char *ifname);
 static int     getMacAddress(JNIEnv *env, int sock,  const char* ifname, const struct in_addr* addr, unsigned char *buf);
 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 
@@ -550,7 +550,7 @@
 
     name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
 
-    ret = getFlags(env, sock, name_utf);
+    ret = getFlags(sock, name_utf);
 
     close(sock);
     (*env)->ReleaseStringUTFChars(env, name, name_utf);
@@ -753,19 +753,27 @@
      * If IPv6 is available then enumerate IPv6 addresses.
      */
 #ifdef AF_INET6
-        sock =  openSocket(env, AF_INET6);
-        if (sock < 0 && (*env)->ExceptionOccurred(env)) {
-            freeif(ifs);
-            return NULL;
-        }
 
-        ifs = enumIPv6Interfaces(env, sock, ifs);
-        close(sock);
+        /* User can disable ipv6 expicitly by -Djava.net.preferIPv4Stack=true,
+         * so we have to call ipv6_available()
+         */
+        if (ipv6_available()) {
 
-        if ((*env)->ExceptionOccurred(env)) {
-            freeif(ifs);
-            return NULL;
-        }
+           sock =  openSocket(env, AF_INET6);
+           if (sock < 0 && (*env)->ExceptionOccurred(env)) {
+               freeif(ifs);
+               return NULL;
+           }
+
+           ifs = enumIPv6Interfaces(env, sock, ifs);
+           close(sock);
+
+           if ((*env)->ExceptionOccurred(env)) {
+              freeif(ifs);
+              return NULL;
+           }
+
+       }
 #endif
 
     return ifs;
@@ -877,7 +885,7 @@
        * the 'parent' interface with the new records.
        */
         *name_colonP = 0;
-        if (getFlags(env,sock,name) < 0) {
+        if (getFlags(sock, name) < 0) {
             // failed to access parent interface do not create parent.
             // We are a virtual interface with no parent.
             isVirtual = 1;
@@ -1249,7 +1257,7 @@
     return  if2.ifr_mtu;
 }
 
-static int getFlags(JNIEnv *env, int sock, const char *ifname) {
+static int getFlags(int sock, const char *ifname) {
   struct ifreq if2;
   int ret = -1;
 
@@ -1625,13 +1633,12 @@
 }
 
 
-static int getFlags(JNIEnv *env, int sock, const char *ifname) {
+static int getFlags(int sock, const char *ifname) {
      struct   lifreq lifr;
      memset((caddr_t)&lifr, 0, sizeof(lifr));
      strcpy((caddr_t)&(lifr.lifr_name), ifname);
 
      if (ioctl(sock, SIOCGLIFFLAGS, (char *)&lifr) < 0) {
-         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFFLAGS failed");
          return -1;
      }
 
--- a/src/solaris/native/java/nio/MappedByteBuffer.c	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/solaris/native/java/nio/MappedByteBuffer.c	Thu Aug 12 11:23:15 2010 -0700
@@ -32,14 +32,11 @@
 #include <stddef.h>
 #include <stdlib.h>
 
-
 JNIEXPORT jboolean JNICALL
-Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj,
-                                        jlong address, jlong len)
+Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, jlong address,
+                                         jlong len, jint numPages)
 {
     jboolean loaded = JNI_TRUE;
-    jint pageSize = sysconf(_SC_PAGESIZE);
-    jint numPages = (len + pageSize - 1) / pageSize;
     int result = 0;
     int i = 0;
     void *a = (void *) jlong_to_ptr(address);
@@ -55,9 +52,9 @@
     }
 
     result = mincore(a, (size_t)len, vec);
-    if (result != 0) {
+    if (result == -1) {
+        JNU_ThrowIOExceptionWithLastError(env, "mincore failed");
         free(vec);
-        JNU_ThrowIOExceptionWithLastError(env, "mincore failed");
         return JNI_FALSE;
     }
 
@@ -72,23 +69,15 @@
 }
 
 
-JNIEXPORT jint JNICALL
+JNIEXPORT void JNICALL
 Java_java_nio_MappedByteBuffer_load0(JNIEnv *env, jobject obj, jlong address,
-                                     jlong len, jint pageSize)
+                                     jlong len)
 {
-    int pageIncrement = pageSize / sizeof(int);
-    int numPages = (len + pageSize - 1) / pageSize;
-    int *ptr = (int *)jlong_to_ptr(address);
-    int i = 0;
-    int j = 0;
-    int result = madvise((caddr_t)ptr, len, MADV_WILLNEED);
-
-    /* touch every page */
-    for (i=0; i<numPages; i++) {
-        j += *((volatile int *)ptr);
-        ptr += pageIncrement;
+    char *a = (char *)jlong_to_ptr(address);
+    int result = madvise((caddr_t)a, (size_t)len, MADV_WILLNEED);
+    if (result == -1) {
+        JNU_ThrowIOExceptionWithLastError(env, "madvise failed");
     }
-    return j;
 }
 
 
@@ -96,13 +85,9 @@
 Java_java_nio_MappedByteBuffer_force0(JNIEnv *env, jobject obj, jlong address,
                                       jlong len)
 {
-    jlong pageSize = sysconf(_SC_PAGESIZE);
-    unsigned long lAddress = address;
-
-    jlong offset = lAddress % pageSize;
-    void *a = (void *) jlong_to_ptr(lAddress - offset);
-    int result = msync(a, (size_t)(len + offset), MS_SYNC);
-    if (result != 0) {
+    void* a = (void *)jlong_to_ptr(address);
+    int result = msync(a, (size_t)len, MS_SYNC);
+    if (result == -1) {
         JNU_ThrowIOExceptionWithLastError(env, "msync failed");
     }
 }
--- a/src/solaris/native/sun/nio/ch/SocketChannelImpl.c	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/solaris/native/sun/nio/ch/SocketChannelImpl.c	Thu Aug 12 11:23:15 2010 -0700
@@ -84,3 +84,11 @@
     }
     return 0;
 }
+
+JNIEXPORT jint JNICALL
+Java_sun_nio_ch_SocketChannelImpl_sendOutOfBandData(JNIEnv* env, jclass this,
+                                                    jobject fdo, jbyte b)
+{
+    int n = send(fdval(env, fdo), (const void*)&b, 1, MSG_OOB);
+    return convertReturnVal(env, n, JNI_FALSE);
+}
--- a/src/windows/classes/sun/net/dns/ResolverConfigurationImpl.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/windows/classes/sun/net/dns/ResolverConfigurationImpl.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, 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
@@ -28,7 +28,6 @@
 import java.util.List;
 import java.util.LinkedList;
 import java.util.StringTokenizer;
-import java.io.IOException;
 
 /*
  * An implementation of sun.net.ResolverConfiguration for Windows.
@@ -63,8 +62,8 @@
 
     // Parse string that consists of token delimited by space or commas
     // and return LinkedHashMap
-    private LinkedList stringToList(String str) {
-        LinkedList ll = new LinkedList();
+    private LinkedList<String> stringToList(String str) {
+        LinkedList<String> ll = new LinkedList<>();
 
         // comma and space are valid delimites
         StringTokenizer st = new StringTokenizer(str, ", ");
@@ -112,7 +111,7 @@
         opts = new OptionsImpl();
     }
 
-    public List searchlist() {
+    public List<String> searchlist() {
         synchronized (lock) {
             loadConfig();
 
@@ -121,7 +120,7 @@
         }
     }
 
-    public List nameservers() {
+    public List<String> nameservers() {
         synchronized (lock) {
             loadConfig();
 
--- a/src/windows/native/java/nio/MappedByteBuffer.c	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/windows/native/java/nio/MappedByteBuffer.c	Thu Aug 12 11:23:15 2010 -0700
@@ -31,8 +31,8 @@
 #include <stdlib.h>
 
 JNIEXPORT jboolean JNICALL
-Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj,
-                                        jlong address, jlong len)
+Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, jlong address,
+                                         jlong len, jint numPages)
 {
     jboolean loaded = JNI_FALSE;
     /* Information not available?
@@ -43,22 +43,11 @@
     return loaded;
 }
 
-JNIEXPORT jint JNICALL
+JNIEXPORT void JNICALL
 Java_java_nio_MappedByteBuffer_load0(JNIEnv *env, jobject obj, jlong address,
-                                     jlong len, jint pageSize)
+                                     jlong len)
 {
-    int *ptr = (int *) jlong_to_ptr(address);
-    int pageIncrement = pageSize / sizeof(int);
-    jlong numPages = (len + pageSize - 1) / pageSize;
-    int i = 0;
-    int j = 0;
-
-    /* touch every page */
-    for (i=0; i<numPages; i++) {
-        j += *((volatile int *)ptr);
-        ptr += pageIncrement;
-    }
-    return j;
+    // no madvise available
 }
 
 JNIEXPORT void JNICALL
--- a/src/windows/native/sun/nio/ch/SocketChannelImpl.c	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/windows/native/sun/nio/ch/SocketChannelImpl.c	Thu Aug 12 11:23:15 2010 -0700
@@ -139,3 +139,16 @@
 
     return 0;
 }
+
+JNIEXPORT jint JNICALL
+Java_sun_nio_ch_SocketChannelImpl_sendOutOfBandData(JNIEnv* env, jclass this,
+                                                    jobject fdo, jbyte b)
+{
+    int n = send(fdval(env, fdo), (const char*)&b, 1, MSG_OOB);
+    if (n == SOCKET_ERROR) {
+        handleSocketError(env, WSAGetLastError());
+        return IOS_THROWN;
+    } else {
+        return n;
+    }
+}
--- a/src/windows/native/sun/windows/awt.h	Tue Aug 10 19:29:30 2010 +0400
+++ b/src/windows/native/sun/windows/awt.h	Thu Aug 12 11:23:15 2010 -0700
@@ -310,24 +310,32 @@
  * Class to encapsulate the extraction of the java string contents
  * into a buffer and the cleanup of the buffer
  */
- class JavaStringBuffer
+class JavaStringBuffer
 {
 protected:
     LPWSTR m_pStr;
     jsize  m_dwSize;
+    LPWSTR getNonEmptyString() {
+        return (NULL==m_pStr)
+                ? L""
+                : m_pStr;
+    }
 
 public:
     JavaStringBuffer(jsize cbTCharCount) {
         m_dwSize = cbTCharCount;
-        m_pStr = (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) );
+        m_pStr = (0 == m_dwSize)
+            ? NULL
+            : (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) );
     }
 
     JavaStringBuffer(JNIEnv *env, jstring text) {
-        if (NULL == text) {
-            m_pStr = L"";
-            m_dwSize = 0;
+        m_dwSize = (NULL == text)
+            ? 0
+            : env->GetStringLength(text);
+        if (0 == m_dwSize) {
+            m_pStr = NULL;
         } else {
-            m_dwSize = env->GetStringLength(text);
             m_pStr = (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) );
             env->GetStringRegion(text, 0, m_dwSize, reinterpret_cast<jchar *>(m_pStr));
             m_pStr[m_dwSize] = 0;
@@ -341,12 +349,16 @@
 
     void Resize(jsize cbTCharCount) {
         m_dwSize = cbTCharCount;
+        //It is ok to have non-null terminated string here.
+        //The function is used only for space reservation in staff buffer for
+        //followed data copying process. And that is the reason why we ignore
+        //the special case m_dwSize==0 here.
         m_pStr = (LPWSTR)safe_Realloc(m_pStr, (m_dwSize+1)*sizeof(WCHAR) );
     }
     //we are in UNICODE now, so LPWSTR:=:LPTSTR
-    operator LPWSTR() { return m_pStr; }
-    operator LPARAM() { return (LPARAM)m_pStr; }
-    void *GetData() { return (void *)m_pStr; }
+    operator LPWSTR() { return getNonEmptyString(); }
+    operator LPARAM() { return (LPARAM)getNonEmptyString(); }
+    void *GetData() { return (void *)getNonEmptyString(); }
     jsize  GetSize() { return m_dwSize; }
 };
 
--- a/test/ProblemList.txt	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/ProblemList.txt	Thu Aug 12 11:23:15 2010 -0700
@@ -366,139 +366,6 @@
 
 # jdk_net
 
-# Suspect many of these tests auffer from using fixed ports, no concrete 
-#   evidence.
-
-# Times out on Windows X64
-sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java generic-all
-
-# Dies on Solaris 10 sparc and sparcv9, Linux  -ea -esa with 
-#   Interrupted or IO exception, maybe writing to non-unique named file?
-com/sun/net/httpserver/bugs/B6373555.java			generic-all
-
-# Fails on OpenSolaris, times out
-java/net/MulticastSocket/SetOutgoingIf.java			generic-all
-
-# Timed out on Solaris 10 X86.
-com/sun/net/httpserver/Test3.java				generic-all
-
-# Exception in test on windows
-com/sun/net/httpserver/bugs/B6373555.java		 	windows-all
-
-# One of these pollutes the samevm on Linux, too many open files, kills jtreg
-com/sun/net/httpserver/bugs/B6339483.java			generic-all
-com/sun/net/httpserver/bugs/B6341616.java			generic-all
-
-# Suspects in cascading samevm problem, solaris 11 i586 (needs othervm?)
-#   Suspect use of setHttps*()?
-com/sun/net/httpserver/SelCacheTest.java			generic-all
-com/sun/net/httpserver/Test1.java				generic-all
-com/sun/net/httpserver/Test12.java				generic-all
-com/sun/net/httpserver/Test13.java				generic-all
-com/sun/net/httpserver/Test6a.java				generic-all
-com/sun/net/httpserver/Test7a.java				generic-all
-com/sun/net/httpserver/Test8a.java				generic-all
-com/sun/net/httpserver/Test9.java				generic-all
-com/sun/net/httpserver/Test9a.java				generic-all
-
-# 10,000 connections, fails on Linux and makes tests&jtreg fail with samevm
-com/sun/net/httpserver/bugs/B6361557.java			generic-all
-
-# Address already in use with samevm? Always? Solaris sparc, probably ports
-java/net/Authenticator/B4933582.sh				generic-all
-java/net/DatagramSocket/SendSize.java				generic-all
-
-# Solaris 11: exception wrong address???
-java/net/Inet6Address/B6558853.java				generic-all
-
-# Not closing stream on file i6a1, windows samevm problem
-java/net/Inet6Address/serialize/Serialize.java			generic-all
-
-# Linux x64 fails "network unreachable"?
-java/net/ipv6tests/TcpTest.java 			 	generic-all
-
-# Linux i586, fails with unexpected output
-java/net/MulticastSocket/NoLoopbackPackets.java 	 	linux-i586
-
-# Address already in use
-java/net/DatagramSocket/DatagramTimeout.java			generic-all
-
-# Fails on windows, takes too long and fails
-#   Solaris 10 sparcv9, samevm, java.lang.Exception: Takes too long. Dead lock
-java/net/Socket/DeadlockTest.java				generic-all
-
-# Linux i586 address already in use or connection error, samevm issues
-java/net/Socket/AccurateTimeout.java			 	generic-all
-java/net/Socket/asyncClose/BrokenPipe.java		 	generic-all
-java/net/Socket/CloseAvailable.java			 	generic-all
-
-# Linux X64 address already in use, samevm issues
-java/net/Socket/LingerTest.java 			 	generic-all
-java/net/Socket/LinkLocal.java				 	generic-all
-java/net/Socket/NullHost.java				 	generic-all
-java/net/Socket/ProxyCons.java				 	generic-all
-java/net/Socket/ReadTimeout.java			 	generic-all
-
-# Linux X64 address already in use, samevm issues
-java/net/Socket/SetReceiveBufferSize.java		 	generic-all
-
-# Linux i586 address already in use or connection error, samevm issues
-java/net/Socket/setReuseAddress/Basic.java		 	generic-all
-java/net/Socket/setReuseAddress/Restart.java		 	generic-all
-
-# Linux X64 address already in use, samevm issues
-java/net/Socket/SetSoLinger.java			 	generic-all
-
-# Address already in use, windows samevm
-java/net/Socket/Timeout.java					generic-all
-
-# Linux X64 address already in use, samevm issues
-java/net/Socket/ShutdownBoth.java			 	generic-all
-java/net/Socket/SoTimeout.java				 	generic-all
-java/net/Socket/TestClose.java				 	generic-all
-java/net/Socket/UrgentDataTest.java			 	generic-all
-java/net/SocketInputStream/SocketClosedException.java	 	generic-all
-java/net/SocketInputStream/SocketTimeout.java		 	generic-all
-
-# Linux i586, address already in use or timeout, samevm issues
-java/net/URLConnection/DisconnectAfterEOF.java		 	generic-all
-java/net/URLConnection/HandleContentTypeWithAttrs.java	 	generic-all
-java/net/URLConnection/Responses.java			 	generic-all
-java/net/URLConnection/TimeoutTest.java 		 	generic-all
-java/net/URLConnection/ZeroContentLength.java		 	generic-all
-
-# Solaris 11 i586 fails with samevm, not sure why
-java/net/ResponseCache/B6181108.java				generic-all
-java/net/ResponseCache/ResponseCacheTest.java			generic-all
-java/net/URL/GetContent.java					generic-all
-java/net/URLConnection/HttpContinueStackOverflow.java		generic-all
-java/net/URLConnection/Redirect307Test.java			generic-all
-java/net/URLConnection/RedirectLimit.java			generic-all
-java/net/URLConnection/ResendPostBody.java			generic-all
-java/net/URL/OpenStream.java					generic-all
-java/net/URLClassLoader/ClassLoad.java				generic-all
-java/net/URLConnection/SetIfModifiedSince.java			generic-all
-java/net/URLConnection/URLConnectionHeaders.java		generic-all
-
-# Linux i586 Connection refused or address already in use, samevm issues
-sun/net/ftp/B6427768.java				 	generic-all
-sun/net/ftp/FtpGetContent.java				 	generic-all
-sun/net/ftp/FtpURL.java 				 	generic-all
-
-# Failed on solaris 10 i586, Exception: should have gotten HttpRetryException?
-sun/net/www/http/ChunkedOutputStream/Test.java			generic-all
-
-# Trouble cleaning up threads in samevm mode on solaris 11 i586
-sun/net/www/http/HttpClient/ProxyTest.java			generic-all
-sun/net/www/http/ChunkedInputStream/ChunkedEncodingTest.java	generic-all
-sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java	generic-all
-sun/net/www/http/HttpClient/B6726695.java			generic-all
-sun/net/www/http/HttpClient/MultiThreadTest.java		generic-all
-sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java	generic-all
-
-# Connection refused, windows samevm
-sun/net/www/protocol/http/DigestTest.java			generic-all
-
 ############################################################################
 
 # jdk_io
--- a/test/com/sun/jdi/ShellScaffold.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/jdi/ShellScaffold.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2010, 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
@@ -141,7 +141,10 @@
 cleanup()
 {
     if [ -r "$failFile" ] ; then
-        cat $failFile  >& 2
+        ls -l "$failFile" >&2
+        echo "<cleanup:_begin_failFile_contents>" >&2
+        cat "$failFile" >&2
+        echo "<cleanup:_end_failFile_contents>" >&2
     fi
 
     # Kill all processes that have our special
@@ -337,6 +340,10 @@
     failFile=$tmpFileDir/testFailed
     debuggeepidFile=$tmpFileDir/debuggeepid
     rm -f $failFile $debuggeepidFile
+    if [ -f "$failFile" ]; then
+        echo "ERROR: unable to delete existing failFile:" >&2
+        ls -l "$failFile" >&2
+    fi
 
     if [ -z "$pkg" ] ; then
         pkgSlash=
@@ -524,6 +531,10 @@
         # See 6562090. Maybe there is a way that the exit
         # can cause jdb to not get the quit.
         sleep 5
+
+        # The exit code value here doesn't matter since this function
+        # is called as part of a pipeline and it is not the last command
+        # in the pipeline.
         exit 1
     fi
     
@@ -938,6 +949,10 @@
     done
 
     if [ -r "$failFile" ] ; then
+        ls -l "$failFile" >&2
+        echo "<waitForFinish:_begin_failFile_contents>" >&2
+        cat "$failFile" >&2
+        echo "<waitForFinish:_end_failFile_contents>" >&2
         exit 1
     fi
 }
@@ -946,33 +961,45 @@
 # $3 is the number of lines to search (from the end)
 grepForString()
 {
-    # See bug 6220903.  Sometimes the jdb '> ' prompt chars
-    # get inserted into the string we are searching for 
-    # so ignore those chars.
     if [ -z "$3" ] ; then
         theCmd=cat
     else
         theCmd="tail -$3"
     fi
+
     case "$2" in 
-      *\>*)
-        # Target string contains a > so we better
-        # not ignore it
+    *\>*)
+        # Target string contains a '>' so we better not ignore it
         $theCmd $1 | $grep -s "$2"  > $devnull 2>&1
-        return $?
+        stat="$?"
         ;;
+    *)
+        # Target string does not contain a '>'.
+        # NOTE:  if $1 does not end with a new line, piping it to sed
+        # doesn't include the chars on the last line.  Detect this
+        # case, and add a new line.
+        theFile="$1"
+        if [ `tail -1 "$theFile" | wc -l | sed -e 's@ @@g'` = 0 ] ; then
+            # The target file doesn't end with a new line so we have
+            # add one to a copy of the target file so the sed command
+            # below can filter that last line.
+            cp "$theFile" "$theFile.tmp"
+            theFile="$theFile.tmp"
+            echo >> "$theFile"
+        fi
+
+        # See bug 6220903. Sometimes the jdb prompt chars ('> ') can
+        # get interleaved in the target file which can keep us from
+        # matching the target string.
+        $theCmd "$theFile" | sed -e 's@> @@g' -e 's@>@@g' \
+            | $grep -s "$2" > $devnull 2>&1
+        stat=$?
+        if [ "$theFile" != "$1" ]; then
+            # remove the copy of the target file
+            rm -f "$theFile"
+        fi
+        unset theFile
     esac
-    # Target string does not contain a >.
-    # Ignore > and '> ' in the file.
-    # NOTE:  if $1 does not end with a new line, piping it to sed doesn't include the
-    # chars on the last line.  Detect this case, and add a new line.
-    cp $1 $1.tmp
-    if [ `tail -1 $1.tmp | wc -l | sed -e 's@ @@g'` = 0 ] ; then
-        echo >> $1.tmp
-    fi
-    $theCmd $1.tmp | sed -e 's@> @@g' -e 's@>@@g' | $grep -s "$2" > $devnull 2>&1
-    stat=$?
-    rm -f $1.tmp
     return $stat
 }
 
@@ -1037,6 +1064,11 @@
         echo
         echo "--Done: test passed"
         exit 0
+    else
+        ls -l "$failFile" >&2
+        echo "<pass:_begin_failFile_contents>" >&2
+        cat "$failFile" >&2
+        echo "<pass:_end_failFile_contents>" >&2
     fi
 }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2010, 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
+ * @bug 6676075
+ * @summary RegistryContext (com.sun.jndi.url.rmi.rmiURLContext) coding problem
+ */
+
+import java.rmi.RemoteException;
+import java.rmi.registry.LocateRegistry;
+
+import com.sun.jndi.rmi.registry.*;
+
+public class ContextWithNullProperties {
+
+    public static void main(String[] args) throws Exception {
+
+        // Create registry on port 1099 if one is not already running.
+        try {
+            LocateRegistry.createRegistry(1099);
+        } catch (RemoteException e) {
+        }
+
+        System.out.println("Connecting to the default Registry...");
+        // Connect to the default Registry.
+        // Pass null as the JNDI environment properties (see final argument)
+        RegistryContext ctx = new RegistryContext(null, -1, null);
+    }
+}
--- a/test/com/sun/net/httpserver/Test1.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test1.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,17 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test1
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import java.security.cert.*;
 import javax.net.ssl.*;
 
 /* basic http/s connectivity test
--- a/test/com/sun/net/httpserver/Test11.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test11.java	Thu Aug 12 11:23:15 2010 -0700
@@ -28,7 +28,6 @@
  */
 
 import java.net.*;
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import com.sun.net.httpserver.*;
@@ -52,22 +51,25 @@
 
     public static void main (String[] args) throws Exception {
         System.out.print ("Test 11: ");
-        HttpServer server = HttpServer.create (new InetSocketAddress(0), 0);
-        HttpContext ctx = server.createContext (
-            "/foo/bar/", new Handler ()
-        );
-        ExecutorService s =  Executors.newCachedThreadPool();
-        server.setExecutor (s);
-        server.start ();
-        URL url = new URL ("http://localhost:" + server.getAddress().getPort()+
-                "/Foo/bar/test.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
-        int r = urlc.getResponseCode();
-        System.out.println ("OK");
-        s.shutdown();
-        server.stop(5);
-        if (r == 200) {
-            throw new RuntimeException ("wrong response received");
+        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
+        ExecutorService s = Executors.newCachedThreadPool();
+        try {
+            HttpContext ctx = server.createContext (
+                "/foo/bar/", new Handler ()
+            );
+            s =  Executors.newCachedThreadPool();
+            server.start ();
+            URL url = new URL ("http://localhost:" + server.getAddress().getPort()+
+                    "/Foo/bar/test.html");
+            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
+            int r = urlc.getResponseCode();
+            if (r == 200) {
+                throw new RuntimeException ("wrong response received");
+            }
+            System.out.println ("OK");
+        } finally {
+            s.shutdown();
+            server.stop(2);
         }
     }
 }
--- a/test/com/sun/net/httpserver/Test12.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test12.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,17 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test12
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import java.security.cert.*;
 import javax.net.ssl.*;
 
 /* basic http/s connectivity test
--- a/test/com/sun/net/httpserver/Test13.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test13.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,17 +24,16 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test13
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import java.security.cert.*;
+
 import javax.net.ssl.*;
 
 /* basic http/s connectivity test
--- a/test/com/sun/net/httpserver/Test6a.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test6a.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,17 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test6a
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import javax.security.auth.callback.*;
 import javax.net.ssl.*;
 
 /**
--- a/test/com/sun/net/httpserver/Test7a.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test7a.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,18 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test7a
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
-import java.util.logging.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import javax.security.auth.callback.*;
 import javax.net.ssl.*;
 
 /**
--- a/test/com/sun/net/httpserver/Test8a.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test8a.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,18 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test8a
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
-import java.util.logging.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import javax.security.auth.callback.*;
 import javax.net.ssl.*;
 
 /**
@@ -50,46 +47,50 @@
         //h.setLevel (Level.INFO);
         //log.addHandler (h);
         //log.setLevel (Level.INFO);
-        Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
-        HttpsServer server = HttpsServer.create (addr, 0);
-        HttpContext ctx = server.createContext ("/test", handler);
-        ExecutorService executor = Executors.newCachedThreadPool();
-        SSLContext ssl = new SimpleSSLContext(System.getProperty("test.src")).get();
-        server.setHttpsConfigurator(new HttpsConfigurator (ssl));
-        server.setExecutor (executor);
-        server.start ();
+        HttpsServer server = null;
+        ExecutorService executor = null;
+        try {
+            Handler handler = new Handler();
+            InetSocketAddress addr = new InetSocketAddress (0);
+            server = HttpsServer.create (addr, 0);
+            HttpContext ctx = server.createContext ("/test", handler);
+            executor = Executors.newCachedThreadPool();
+            SSLContext ssl = new SimpleSSLContext(System.getProperty("test.src")).get();
+            server.setHttpsConfigurator(new HttpsConfigurator (ssl));
+            server.setExecutor (executor);
+            server.start ();
 
-        URL url = new URL ("https://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        System.out.print ("Test8a: " );
-        HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection ();
-        urlc.setDoOutput (true);
-        urlc.setRequestMethod ("POST");
-        urlc.setHostnameVerifier (new DummyVerifier());
-        urlc.setSSLSocketFactory (ssl.getSocketFactory());
-        OutputStream os = new BufferedOutputStream (urlc.getOutputStream(), 8000);
-        for (int i=0; i<SIZE; i++) {
-            os.write (i % 250);
+            URL url = new URL ("https://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+            System.out.print ("Test8a: " );
+            HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection ();
+            urlc.setDoOutput (true);
+            urlc.setRequestMethod ("POST");
+            urlc.setHostnameVerifier (new DummyVerifier());
+            urlc.setSSLSocketFactory (ssl.getSocketFactory());
+            OutputStream os = new BufferedOutputStream (urlc.getOutputStream(), 8000);
+            for (int i=0; i<SIZE; i++) {
+                os.write (i % 250);
+            }
+            os.close();
+            int resp = urlc.getResponseCode();
+            if (resp != 200) {
+                throw new RuntimeException ("test failed response code");
+            }
+            InputStream is = urlc.getInputStream ();
+            for (int i=0; i<SIZE; i++) {
+                int f = is.read();
+                if (f != (i % 250)) {
+                    System.out.println ("Setting error(" +f +")("+i+")" );
+                    error = true;
+                    break;
+                }
+            }
+            is.close();
+        } finally {
+            delay();
+            if (server != null) server.stop(2);
+            if (executor != null) executor.shutdown();
         }
-        os.close();
-        int resp = urlc.getResponseCode();
-        if (resp != 200) {
-            throw new RuntimeException ("test failed response code");
-        }
-        InputStream is = urlc.getInputStream ();
-        for (int i=0; i<SIZE; i++) {
-            int f = is.read();
-            if (f != (i % 250)) {
-                System.out.println ("Setting error(" +f +")("+i+")" );
-                error = true;
-                break;
-            }
-        }
-        is.close();
-
-        delay();
-        server.stop(2);
-        executor.shutdown();
         if (error) {
             throw new RuntimeException ("test failed error");
         }
--- a/test/com/sun/net/httpserver/Test9.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test9.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,17 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test9
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import java.security.cert.*;
 import javax.net.ssl.*;
 
 /* Same as Test1 but requests run in parallel.
--- a/test/com/sun/net/httpserver/Test9a.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/Test9a.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,17 +24,15 @@
 /**
  * @test
  * @bug 6270015
+ * @run main/othervm Test9a
  * @summary  Light weight HTTP server
  */
 
 import com.sun.net.httpserver.*;
 
-import java.util.*;
 import java.util.concurrent.*;
 import java.io.*;
 import java.net.*;
-import java.security.*;
-import java.security.cert.*;
 import javax.net.ssl.*;
 
 /* Same as Test1 but requests run in parallel.
--- a/test/com/sun/net/httpserver/bugs/B6361557.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/bugs/B6361557.java	Thu Aug 12 11:23:15 2010 -0700
@@ -24,6 +24,7 @@
 /**
  * @test
  * @bug 6361557
+ * @run main/othervm B6361557
  * @summary  Lightweight HTTP server quickly runs out of file descriptors on Linux
  */
 
@@ -35,12 +36,9 @@
 import java.nio.*;
 import java.nio.channels.*;
 import java.net.*;
-import java.security.*;
-import java.security.cert.*;
-import javax.net.ssl.*;
 
 /**
- * The test simply opens 10,000 separate connections
+ * The test simply opens 1,000 separate connections
  * and invokes one http request on each. The client does
  * not close any sockets until after they are closed
  * by the server. This verifies the basic ability
@@ -49,6 +47,7 @@
 public class B6361557 {
 
     public static boolean error = false;
+    static final int NUM = 1000;
 
     static class Handler implements HttpHandler {
         int invocation = 1;
@@ -65,6 +64,9 @@
         }
     }
 
+    final static String request = "GET /test/foo.html HTTP/1.1\r\nContent-length: 0\r\n\r\n";
+    final static ByteBuffer requestBuf = ByteBuffer.allocate(64).put(request.getBytes());
+
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
         InetSocketAddress addr = new InetSocketAddress (0);
@@ -75,49 +77,72 @@
         server.setExecutor (executor);
         server.start ();
 
-        final int NUM = 10000;
-        ByteBuffer buf = ByteBuffer.allocate (4096);
         InetSocketAddress destaddr = new InetSocketAddress (
                 "127.0.0.1", server.getAddress().getPort()
         );
         System.out.println ("destaddr " + destaddr);
 
         Selector selector = Selector.open ();
-        int i = 0;
+        int requests = 0;
+        int responses = 0;
         while (true) {
-            i ++;
             int selres = selector.select (1);
             Set<SelectionKey> selkeys = selector.selectedKeys();
             for (SelectionKey key : selkeys) {
                 if (key.isReadable()) {
                     SocketChannel chan = (SocketChannel)key.channel();
-                    buf.clear();
+                    ByteBuffer buf = (ByteBuffer)key.attachment();
                     try {
-                        int x = chan.read (buf);
-                        if (x == -1) {
+                        int x = chan.read(buf);
+                        if (x == -1 || responseComplete(buf)) {
+                            key.attach(null);
                             chan.close();
+                            responses++;
                         }
                     } catch (IOException e) {}
                 }
             }
-            if (i< NUM) {
-                SocketChannel schan = SocketChannel.open (destaddr);
-                String cmd = "GET /test/foo.html HTTP/1.1\r\nContent-length: 0\r\n\r\n";
-                buf.rewind ();
-                buf.put (cmd.getBytes());
-                buf.flip();
+            if (requests < NUM) {
+                SocketChannel schan = SocketChannel.open(destaddr);
+                requestBuf.rewind();
                 int c = 0;
-                while (buf.remaining() > 0) {
-                    c += schan.write (buf);
+                while (requestBuf.remaining() > 0) {
+                    c += schan.write(requestBuf);
                 }
-                schan.configureBlocking (false);
-                schan.register (selector, SelectionKey.OP_READ, null);
-            } else {
+                schan.configureBlocking(false);
+                schan.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(100));
+                requests++;
+            }
+            if (responses == NUM) {
                 System.out.println ("Finished clients");
-                server.stop (1);
-                executor.shutdown ();
-                return;
+                break;
             }
         }
+        server.stop (1);
+        selector.close();
+        executor.shutdown ();
+
+    }
+
+    /* Look for CR LF CR LF */
+    static boolean responseComplete(ByteBuffer buf) {
+        int pos = buf.position();
+        buf.flip();
+        byte[] lookingFor = new byte[] {'\r', '\n', '\r', '\n' };
+        int lookingForCount = 0;
+        while (buf.hasRemaining()) {
+            byte b = buf.get();
+            if (b == lookingFor[lookingForCount]) {
+                lookingForCount++;
+                if (lookingForCount == 4) {
+                    return true;
+                }
+            } else {
+                lookingForCount = 0;
+            }
+        }
+        buf.position(pos);
+        buf.limit(buf.capacity());
+        return false;
     }
 }
--- a/test/com/sun/net/httpserver/bugs/B6373555.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/com/sun/net/httpserver/bugs/B6373555.java	Thu Aug 12 11:23:15 2010 -0700
@@ -46,7 +46,7 @@
     private static Object lock;
     static HttpServer httpServer;
     static ExecutorService pool, execs;
-    static int NUM = 4000;
+    static int NUM = 1000;
 
     public static void main(String[] args) throws Exception {
         try {
@@ -125,7 +125,7 @@
                 }
             }
             catch(Exception e) {
-                //e.printStackTrace();
+                e.printStackTrace();
                 System.out.print (".");
                 error = true;
             }
--- a/test/java/lang/Throwable/SuppressedExceptions.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/lang/Throwable/SuppressedExceptions.java	Thu Aug 12 11:23:15 2010 -0700
@@ -26,7 +26,7 @@
 
 /*
  * @test
- * @bug     6911258 6962571
+ * @bug     6911258 6962571 6963622
  * @summary Basic tests of suppressed exceptions
  * @author  Joseph D. Darcy
  */
@@ -35,11 +35,22 @@
     private static String message = "Bad suppressed exception information";
 
     public static void main(String... args) throws Exception {
+        noSelfSuppression();
         basicSupressionTest();
         serializationTest();
         selfReference();
     }
 
+    private static void noSelfSuppression() {
+        Throwable throwable = new Throwable();
+        try {
+            throwable.addSuppressedException(throwable);
+            throw new RuntimeException("IllegalArgumentException for self-suppresion not thrown.");
+        } catch (IllegalArgumentException iae) {
+            ; // Expected
+        }
+    }
+
     private static void basicSupressionTest() {
         Throwable throwable = new Throwable();
         RuntimeException suppressed = new RuntimeException("A suppressed exception.");
@@ -156,9 +167,8 @@
 
         throwable1.printStackTrace();
 
-
-        throwable1.addSuppressedException(throwable1);
         throwable1.addSuppressedException(throwable2);
+        throwable2.addSuppressedException(throwable1);
 
         throwable1.printStackTrace();
     }
--- a/test/java/net/DatagramSocket/DatagramTimeout.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/DatagramSocket/DatagramTimeout.java	Thu Aug 12 11:23:15 2010 -0700
@@ -27,25 +27,25 @@
  * @summary  test to see if timeout hangs
  * @run main/timeout=15 DatagramTimeout
  */
-import java.net.*;
-import java.io.*;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.SocketTimeoutException;
 
 public class DatagramTimeout {
-
-    public static ServerSocket sock;
-
     public static void main(String[] args) throws Exception {
         boolean success = false;
+        DatagramSocket sock = new DatagramSocket();
+
         try {
-            DatagramSocket sock;
             DatagramPacket p;
             byte[] buffer = new byte[50];
             p = new DatagramPacket(buffer, buffer.length);
-            sock = new DatagramSocket(2333);
             sock.setSoTimeout(2);
             sock.receive(p);
         } catch (SocketTimeoutException e) {
             success = true;
+        } finally {
+            sock.close();
         }
         if (!success)
             throw new RuntimeException("Socket timeout failure.");
--- a/test/java/net/DatagramSocket/SendSize.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/DatagramSocket/SendSize.java	Thu Aug 12 11:23:15 2010 -0700
@@ -32,35 +32,26 @@
  * @author Benjamin Renaud
  */
 
-import java.io.*;
-import java.net.*;
-import java.util.*;
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
 
 public class SendSize {
-
-    static final int clientPort = 8989;
-    static final int serverPort = 9999;
     static final int bufferLength = 512;
     static final int packetLength = 256;
 
     public static void main(String[] args) throws Exception {
-        new ServerThread().start();
-        new ClientThread().start();
+        DatagramSocket serverSocket = new DatagramSocket();
+        new ServerThread(serverSocket).start();
+        new ClientThread(serverSocket.getLocalPort()).start();
     }
 
-
     static class ServerThread extends Thread {
-
-        int port;
         DatagramSocket server;
 
-        ServerThread(int port) throws IOException {
-            this.port = port;
-            this.server = new DatagramSocket(port);
-        }
-
-        ServerThread() throws IOException {
-            this(SendSize.serverPort);
+        ServerThread(DatagramSocket server) {
+            this.server = server;
         }
 
         public void run() {
@@ -85,33 +76,22 @@
             } catch (Exception e) {
                 e.printStackTrace();
                 throw new RuntimeException("caugth: " + e);
+            } finally {
+                if (server != null) { server.close(); }
             }
         }
     }
 
     static class ClientThread extends Thread {
 
-        int port;
         int serverPort;
-        int bufferLength;
-        int packetLength;
-
         DatagramSocket client;
         InetAddress host;
 
-        ClientThread(int port, int serverPort,
-                     int bufferLength, int packetLength) throws IOException {
-            this.port = port;
+        ClientThread(int serverPort)throws IOException {
             this.serverPort = serverPort;
             this.host = InetAddress.getLocalHost();
-            this.bufferLength = bufferLength;
-            this.packetLength = packetLength;
-            this.client = new DatagramSocket(port, host);
-        }
-
-        ClientThread() throws IOException {
-            this(SendSize.clientPort, SendSize.serverPort,
-                 SendSize.bufferLength, SendSize.packetLength);
+            this.client = new DatagramSocket();
         }
 
         public void run() {
@@ -129,6 +109,8 @@
             } catch (Exception e) {
                 e.printStackTrace();
                 throw new RuntimeException("caught: " + e);
+            } finally {
+                if (client != null) { client.close(); }
             }
         }
     }
--- a/test/java/net/Inet6Address/B6558853.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Inet6Address/B6558853.java	Thu Aug 12 11:23:15 2010 -0700
@@ -43,6 +43,9 @@
         InetAddress dest = null;
         while (l.hasMoreElements() && dest == null) {
             NetworkInterface nif = l.nextElement();
+            if (!nif.isUp())
+                continue;
+
             for (InterfaceAddress a : nif.getInterfaceAddresses()) {
                 if (a.getAddress() instanceof Inet6Address) {
                     Inet6Address a6 = (Inet6Address) a.getAddress();
@@ -53,6 +56,7 @@
                 }
             }
         }
+        System.out.println("Using " + dest);
         if (dest != null) {
             B6558853 test = new B6558853(dest, port);
             Thread thread = new Thread(test);
--- a/test/java/net/Inet6Address/serialize/Serialize.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Inet6Address/serialize/Serialize.java	Thu Aug 12 11:23:15 2010 -0700
@@ -72,6 +72,7 @@
          File file = new File (System.getProperty("test.src"), "serial1.4.2.ser");
          ois = new ObjectInputStream(new FileInputStream(file));
          nobj = (Inet6Address) ois.readObject();
+         ois.close();
          if (!nobj.equals (InetAddress.getByName ("::1"))) {
             throw new RuntimeException ("old ::1 not deserialized right");
          }
@@ -90,6 +91,8 @@
              nobj = (Inet6Address) ois.readObject();
          } catch (NullPointerException e) {
              throw new RuntimeException("6656849 Not fixed: NullPointer when deserializing");
+         } finally {
+             ois.close();
          }
          System.out.println(nobj);
          System.out.println("All tests passed");
@@ -102,6 +105,7 @@
 
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream("i6a1.ser"));
          Inet6Address nobj = (Inet6Address) ois.readObject();
+         ois.close();
 
          if (nobj.equals(obj)) {
              return true;
--- a/test/java/net/InetAddress/CheckJNI.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/InetAddress/CheckJNI.java	Thu Aug 12 11:23:15 2010 -0700
@@ -56,6 +56,8 @@
 
         while (ifs.hasMoreElements()) {
             NetworkInterface nif = (NetworkInterface)ifs.nextElement();
+            if (!nif.isUp())
+                continue;
             Enumeration addrs = nif.getInetAddresses();
             while (addrs.hasMoreElements()) {
                 InetAddress addr = (InetAddress) addrs.nextElement();
--- a/test/java/net/MulticastSocket/SetOutgoingIf.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/MulticastSocket/SetOutgoingIf.java	Thu Aug 12 11:23:15 2010 -0700
@@ -76,6 +76,10 @@
 
                 // now determine what (if any) type of addresses are assigned to this interface
                 for (InetAddress addr : Collections.list(nic.getInetAddresses())) {
+                    if (addr.isAnyLocalAddress())
+                        continue;
+
+                    System.out.println("    addr " + addr);
                     if (addr instanceof Inet4Address) {
                         netIf.ipv4Address(true);
                     } else if (addr instanceof Inet6Address) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/net/NetworkInterface/IPv4Only.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2010, 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
+ * @bug   6964714
+ * @run main/othervm IPv4Only
+ * @summary Test the networkinterface listing with java.net.preferIPv4Stack=true.
+ */
+
+
+import java.net.*;
+import java.util.*;
+
+
+public class IPv4Only {
+    public static void main(String[] args) throws Exception {
+        System.setProperty("java.net.preferIPv4Stack","true");
+
+        Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
+        while (nifs.hasMoreElements()) {
+            NetworkInterface nif = nifs.nextElement();
+            Enumeration<InetAddress> addrs = nif.getInetAddresses();
+            while (addrs.hasMoreElements()) {
+               InetAddress hostAddr = addrs.nextElement();
+               if ( hostAddr instanceof Inet6Address ){
+                    throw new RuntimeException( "NetworkInterfaceV6List failed - found v6 address " + hostAddr.getHostAddress() );
+               }
+            }
+        }
+    }
+}
--- a/test/java/net/ResponseCache/B6181108.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/ResponseCache/B6181108.java	Thu Aug 12 11:23:15 2010 -0700
@@ -67,9 +67,10 @@
             out.flush();
 
             s.close();
-            ss.close();
         } catch (Exception e) {
             e.printStackTrace();
+        } finally {
+            try { ss.close(); } catch (IOException unused) {}
         }
     }
 
@@ -100,6 +101,7 @@
         URLConnection urlc = url.openConnection();
         int i = ((HttpURLConnection)(urlc)).getResponseCode();
         System.out.println ("response code = " + i);
+        ResponseCache.setDefault(null);
     }
 
     public static void main(String args[]) throws Exception {
--- a/test/java/net/ResponseCache/ResponseCacheTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/ResponseCache/ResponseCacheTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -30,7 +30,6 @@
 import java.net.*;
 import java.util.*;
 import java.io.*;
-import java.nio.*;
 import sun.net.www.ParseUtil;
 import javax.net.ssl.*;
 
@@ -43,11 +42,16 @@
     static URL url1;
     static URL url2;
     static String FNPrefix, OutFNPrefix;
+    static List<Closeable> streams = new ArrayList<>();
+    static List<File> files = new ArrayList<>();
+
     /*
      * Our "http" server to return a 404 */
     public void run() {
+        Socket s = null;
+        FileInputStream fis = null;
         try {
-            Socket s = ss.accept();
+            s = ss.accept();
 
             InputStream is = s.getInputStream ();
             BufferedReader r = new BufferedReader(new InputStreamReader(is));
@@ -68,7 +72,7 @@
             out.print("Content-Length: "+file2.length()+"\r\n");
             out.print("Connection: close\r\n");
             out.print("\r\n");
-            FileInputStream fis = new FileInputStream(file2);
+            fis = new FileInputStream(file2);
             byte[] buf = new byte[(int)file2.length()];
             int len;
             while ((len = fis.read(buf)) != -1) {
@@ -81,6 +85,10 @@
             ss.close();
         } catch (Exception e) {
             e.printStackTrace();
+        } finally {
+            try { ss.close(); } catch (IOException unused) {}
+            try { s.close(); } catch (IOException unused) {}
+            try { fis.close(); } catch (IOException unused) {}
         }
     }
 static class NameVerifier implements HostnameVerifier {
@@ -144,11 +152,14 @@
         // assert (headers1 == headers2 && file1 == file2.2)
         File file1 = new File(OutFNPrefix+"file1");
         File file2 = new File(OutFNPrefix+"file2.2");
+        files.add(file1);
+        files.add(file2);
         System.out.println("headers1"+headers1+"\nheaders2="+headers2);
         if (!headers1.equals(headers2) || file1.length() != file2.length()) {
             throw new RuntimeException("test failed");
         }
     }
+
     public static void main(String args[]) throws Exception {
         try {
             ResponseCache.setDefault(new MyResponseCache());
@@ -157,6 +168,12 @@
             new ResponseCacheTest();
         } finally{
             ResponseCache.setDefault(null);
+            for (Closeable c: streams) {
+                try { c.close(); } catch (IOException unused) {}
+            }
+            for (File f: files) {
+                f.delete();
+            }
         }
     }
 
@@ -184,6 +201,7 @@
         public MyCacheResponse(String filename) {
             try {
                 fis = new FileInputStream(new File(filename));
+                streams.add(fis);
                 ObjectInputStream ois = new ObjectInputStream(fis);
                 headers = (Map<String,List<String>>)ois.readObject();
             } catch (Exception ex) {
@@ -206,6 +224,8 @@
             try {
                 File file = new File(filename);
                 fos = new FileOutputStream(file);
+                streams.add(fos);
+                files.add(file);
                 ObjectOutputStream oos = new ObjectOutputStream(fos);
                 oos.writeObject(rspHeaders);
             } catch (Exception ex) {
--- a/test/java/net/ResponseCache/getResponseCode.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/ResponseCache/getResponseCode.java	Thu Aug 12 11:23:15 2010 -0700
@@ -39,6 +39,7 @@
 public class getResponseCode {
     static URL url;
     static String FNPrefix;
+    static List<Closeable> resources = new ArrayList<>();
 
     getResponseCode() throws Exception {
         url = new URL("http://localhost/file1.cache");
@@ -57,6 +58,9 @@
             new getResponseCode();
         } finally{
             ResponseCache.setDefault(null);
+            for (Closeable c : resources) {
+                try { c.close(); } catch (IOException unused) {}
+            }
         }
     }
 
@@ -77,6 +81,7 @@
         public MyResponse(String filename) {
             try {
                 fis = new FileInputStream(new File(filename));
+                resources.add(fis);
                 headers = (Map<String,List<String>>)new ObjectInputStream(fis).readObject();
             } catch (Exception ex) {
                 throw new RuntimeException(ex.getMessage());
--- a/test/java/net/Socket/AccurateTimeout.java	Tue Aug 10 19:29:30 2010 +0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,144 +0,0 @@
-/*
- * Copyright (c) 2002, 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
- * @bug 4512028
- * @summary Check the tolerance on read timeouts.
- */
-import java.net.*;
-import java.io.*;
-
-public class AccurateTimeout {
-
-    static final int TOLERANCE = 100;
-
-    static boolean skipTest() {
-        String os = System.getProperty("os.name");
-        if (os.equals("Windows 95") ||
-            os.equals("Windows 98") ||
-            os.equals("Windows Me")) {
-
-            System.out.println("Due to an OS bug timeout tolerance cannot be tested on this OS");
-            return true;
-        }
-        return false;
-    }
-
-    public static void main(String args[]) throws Exception {
-
-        if (skipTest()) {
-            return;
-        }
-
-        int failures = 0;
-        int timeout;
-
-        System.out.println("");
-        System.out.println("Testing Socket.getInputStream().read() ...");
-        System.out.println("");
-
-        ServerSocket ss = new ServerSocket(0);
-        Socket s1 = new Socket(InetAddress.getLocalHost(), ss.getLocalPort());
-        Socket s2 = ss.accept();
-
-        InputStream in = s1.getInputStream();
-
-        timeout = 100;
-        while (timeout < 2500) {
-            s1.setSoTimeout(timeout);
-
-            long startTime = System.currentTimeMillis();
-            try {
-                in.read();
-            } catch (SocketTimeoutException e) {
-            }
-            long actual = System.currentTimeMillis() - startTime;
-
-            System.out.print("excepted: " + timeout + " actual: " + actual);
-
-            if (Math.abs(actual-timeout) > TOLERANCE) {
-                System.out.print(" *** FAIL: outside tolerance");
-                failures++;
-            } else {
-                System.out.print(" PASS.");
-            }
-
-            System.out.println("");
-            timeout += 200;
-        }
-
-        s1.close();
-        s2.close();
-        ss.close();
-
-
-        // ----------
-
-
-        System.out.println("");
-        System.out.println("Testing DatagramSocket.receive ...");
-        System.out.println("");
-
-        byte b[] = new byte[8];
-        DatagramPacket p = new DatagramPacket(b, b.length);
-
-        DatagramSocket ds = new DatagramSocket();
-
-        timeout = 100;
-        while (timeout < 2500) {
-            ds.setSoTimeout(timeout);
-
-            long startTime = System.currentTimeMillis();
-            try {
-                ds.receive(p);
-            } catch (SocketTimeoutException e) {
-            }
-            long actual = System.currentTimeMillis() - startTime;
-
-            System.out.print("excepted: " + timeout + " actual: " + actual);
-
-            if (Math.abs(actual-timeout) > TOLERANCE) {
-                System.out.print(" *** FAIL: outside tolerance");
-                failures++;
-            } else {
-                System.out.print(" PASS.");
-            }
-
-            System.out.println("");
-            timeout += 200;
-        }
-
-        ds.close();
-
-        System.out.println("");
-
-        // ---------
-
-        if (failures > 0) {
-            throw new Exception("Test failed: " + failures +
-                " test(s) outside tolerance");
-        }
-
-    }
-
-}
--- a/test/java/net/Socket/CloseAvailable.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/CloseAvailable.java	Thu Aug 12 11:23:15 2010 -0700
@@ -47,6 +47,7 @@
         t.start();
 
         Socket  soc = ss.accept();
+        ss.close();
 
         DataInputStream is = new DataInputStream(soc.getInputStream());
         is.close();
@@ -64,7 +65,7 @@
     public void run() {
         try {
             Socket s = new Socket(addr, port);
-
+            s.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
--- a/test/java/net/Socket/DeadlockTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/DeadlockTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -33,29 +33,32 @@
 
 public class DeadlockTest {
     public static void main(String [] argv) throws Exception {
+        ServerSocket ss = new ServerSocket(0);
+        Socket clientSocket = new Socket();
 
-        // Start the server thread
-        Thread s1 = new Thread(new ServerThread());
-        s1.start();
+        try {
+            // Start the server thread
+            Thread s1 = new Thread(new ServerThread(ss));
+            s1.start();
 
-        // Sleep to make sure s1 has created a server socket
-        Thread.sleep(1000);
+            // Start the client thread
+            ClientThread ct = new ClientThread(clientSocket, ss.getLocalPort());
+            Thread c1 = new Thread(ct);
+            c1.start();
 
-        // Start the client thread
-        ClientThread ct = new ClientThread();
-        Thread c1 = new Thread(ct);
-        c1.start();
+            // Wait for the client thread to finish
+            c1.join(20000);
 
-        // Wait for the client thread to finish
-        c1.join(40000);
-
-        // If timeout, we assume there is a deadlock
-        if (c1.isAlive() == true) {
-            // Close the socket to force the server thread
-            // terminate too
-            s1.stop();
-            ct.getSock().close();
-            throw new Exception("Takes too long. Dead lock");
+            // If timeout, we assume there is a deadlock
+            if (c1.isAlive() == true) {
+                // Close the socket to force the server thread
+                // terminate too
+                s1.stop();
+                throw new Exception("Takes too long. Dead lock");
+            }
+        } finally {
+            ss.close();
+            clientSocket.close();
         }
     }
 }
@@ -71,8 +74,8 @@
 
     Socket sock;
 
-    public ServerThread() throws Exception {
-
+    public ServerThread(ServerSocket serverSocket) throws Exception {
+        this.server = serverSocket;
     }
 
     public void ping(int cnt) {
@@ -85,7 +88,6 @@
 
         try {
             if (Thread.currentThread().getName().startsWith("child") == false) {
-                server = new ServerSocket(4711);
                 sock  = server.accept();
 
                 new Thread(this, "child").start();
@@ -107,6 +109,7 @@
             }
 
         } catch (Throwable e) {
+            System.out.println(e);
             // If anything goes wrong, just quit.
         }
 
@@ -141,10 +144,11 @@
 
     Socket sock;
 
-    public ClientThread() throws Exception {
+    public ClientThread(Socket sock, int serverPort) throws Exception {
         try {
-            System.out.println("About to create a socket");
-            sock = new Socket(InetAddress.getLocalHost().getHostName(), 4711);
+            System.out.println("About to connect the client socket");
+            this.sock = sock;
+            this.sock.connect(new InetSocketAddress("localhost", serverPort));
             System.out.println("connected");
 
             out = new ObjectOutputStream(sock.getOutputStream());
@@ -156,10 +160,6 @@
         }
     }
 
-    public Socket getSock() {
-        return sock;
-    }
-
     private int cnt = 1;
 
     public void run() {
@@ -213,6 +213,7 @@
             System.out.println("write message done " + cnt++);
         } catch (IOException ioe) {
             // Ignore the exception
+            System.out.println(ioe);
         }
      }
 }
--- a/test/java/net/Socket/LingerTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/LingerTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -81,7 +81,7 @@
         public void run() {
             System.out.println ("Another starts");
             try {
-                Thread.currentThread().sleep(delay);
+                Thread.sleep(delay);
                 Socket s = new Socket("localhost", port);
                 synchronized (this) {
                     connected = true;
@@ -105,7 +105,6 @@
         Socket s1 = new Socket("localhost", ss.getLocalPort());
         Socket s2 = ss.accept();
 
-
         // setup conditions for untransmitted data and lengthy
             // linger interval
             s1.setSendBufferSize(128*1024);
@@ -122,14 +121,15 @@
         thr.start();
 
         // give sender time to queue the data
-            Thread.currentThread().sleep(1000);
+            Thread.sleep(1000);
 
         // close the socket asynchronously
             (new Thread(new Closer(s1))).start();
 
         // give another time to run
-            Thread.currentThread().sleep(10000);
+            Thread.sleep(10000);
 
+        ss.close();
         // check that another is done
             if (!another.connected()) {
             throw new RuntimeException("Another thread is blocked");
--- a/test/java/net/Socket/LinkLocal.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/LinkLocal.java	Thu Aug 12 11:23:15 2010 -0700
@@ -58,11 +58,10 @@
         } catch (SocketException e) {
             failed++;
             System.out.println("Test failed: " + e);
+        } finally {
+            s.close();
+            ss.close();
         }
-
-        // clean up
-        s.close();
-        ss.close();
     }
 
     static void UdpTest(InetAddress ia, boolean connected) throws Exception {
@@ -93,16 +92,16 @@
             ds1.send(p);
             System.out.println("Packet has been sent.");
 
-            ds2.setSoTimeout(1000);
+            ds2.setSoTimeout(5000);
             ds2.receive(p);
             System.out.println("Test passed - packet received.");
         } catch (SocketException e) {
             failed++;
             System.out.println("Test failed: " + e);
+        } finally {
+            ds1.close();
+            ds2.close();
         }
-
-        ds1.close();
-        ds2.close();
     }
 
     static void TestAddress(InetAddress ia) throws Exception {
@@ -138,6 +137,9 @@
             Enumeration nifs = NetworkInterface.getNetworkInterfaces();
             while (nifs.hasMoreElements()) {
                 NetworkInterface ni = (NetworkInterface)nifs.nextElement();
+                if (!ni.isUp())
+                    continue;
+
                 Enumeration addrs = ni.getInetAddresses();
                 while (addrs.hasMoreElements()) {
                     InetAddress addr = (InetAddress)addrs.nextElement();
--- a/test/java/net/Socket/ProxyCons.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/ProxyCons.java	Thu Aug 12 11:23:15 2010 -0700
@@ -39,6 +39,7 @@
         public void run () {
             try {
                 Socket s = server.accept ();
+                s.close();
                 while (!finished ()) {
                     Thread.sleep (500);
                 }
@@ -58,10 +59,9 @@
     public ProxyCons() {
     }
 
-    void test() {
+    void test() throws Exception {
+        ServerSocket ss = new ServerSocket(0);
         try {
-            ServerSocket ss = new ServerSocket();
-            ss.bind(new InetSocketAddress(0));
             Server s = new Server(ss);
             s.start();
             Socket sock = new Socket(Proxy.NO_PROXY);
@@ -70,10 +70,12 @@
             sock.close();
         } catch (java.io.IOException e) {
             throw new RuntimeException(e);
+        } finally {
+            ss.close();
         }
     }
 
-    public static void main(String[] args) {
+    public static void main(String[] args) throws Exception {
         ProxyCons c = new ProxyCons();
         c.test();
     }
--- a/test/java/net/Socket/ReadTimeout.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/ReadTimeout.java	Thu Aug 12 11:23:15 2010 -0700
@@ -44,7 +44,7 @@
     sin = InetAddress.getLocalHost();
     srv = new ServerSocket(port);
     port = srv.getLocalPort();
-    soc = new Socket(sin, port, true);
+    soc = new Socket(sin, port);
     soc1 = srv.accept();
     soc.setSoTimeout(tout);
 
@@ -53,10 +53,10 @@
       os = soc1.getOutputStream();
       is.read();
     } catch(InterruptedIOException e) {
+    } finally {
+        soc.close();
+        soc1.close();
+        srv.close();
     }
-
-    soc.close();
-    soc1.close();
-    srv.close();
   }
 }
--- a/test/java/net/Socket/SetReceiveBufferSize.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/SetReceiveBufferSize.java	Thu Aug 12 11:23:15 2010 -0700
@@ -32,29 +32,14 @@
 import java.net.ServerSocket;
 
 public class SetReceiveBufferSize {
-    class Server extends Thread {
-        private ServerSocket ss;
-        public Server(ServerSocket ss) {
-            this.ss = ss;
-        }
-
-        public void run() {
-            try {
-                ss.accept();
-            } catch (Exception e) {
-            }
-        }
-    }
-
     public static void main(String[] args) throws Exception {
         SetReceiveBufferSize s = new SetReceiveBufferSize();
     }
 
     public SetReceiveBufferSize() throws Exception {
         ServerSocket ss = new ServerSocket(0);
-        Server serv = new Server(ss);
-        serv.start();
         Socket s = new Socket("localhost", ss.getLocalPort());
+        Socket accepted = ss.accept();
         try {
             s.setReceiveBufferSize(0);
         } catch (IllegalArgumentException e) {
@@ -62,6 +47,8 @@
         } catch (Exception ex) {
         } finally {
             ss.close();
+            s.close();
+            accepted.close();
         }
         throw new RuntimeException("IllegalArgumentException not thrown!");
     }
--- a/test/java/net/Socket/SetSoLinger.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/SetSoLinger.java	Thu Aug 12 11:23:15 2010 -0700
@@ -30,36 +30,24 @@
 
 import java.net.*;
 
-public class SetSoLinger implements Runnable {
-    static ServerSocket ss;
-    static InetAddress addr;
-    static int port;
+public class SetSoLinger {
+    static final int LINGER = 65546;
 
     public static void main(String args[]) throws Exception {
-        boolean      error = true;
-        int          linger = 65546;
-        int          value = 0;
-        addr = InetAddress.getLocalHost();
-        ss = new ServerSocket(0);
-        port = ss.getLocalPort();
+        int value;
+        InetAddress addr = InetAddress.getLocalHost();
+        ServerSocket ss = new ServerSocket(0);
+        int port = ss.getLocalPort();
 
-        Thread t = new Thread(new SetSoLinger());
-        t.start();
+        Socket s = new Socket(addr, port);
         Socket soc = ss.accept();
-        soc.setSoLinger(true, linger);
+        soc.setSoLinger(true, LINGER);
         value = soc.getSoLinger();
         soc.close();
+        s.close();
+        ss.close();
 
         if(value != 65535)
             throw new RuntimeException("Failed. Value not properly reduced.");
     }
-
-    public void run() {
-        try {
-            Socket s = new Socket(addr, port);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
 }
--- a/test/java/net/Socket/ShutdownBoth.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/ShutdownBoth.java	Thu Aug 12 11:23:15 2010 -0700
@@ -36,12 +36,14 @@
         Socket s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
         Socket s2 = ss.accept();
 
-        s1.shutdownInput();
-        s1.shutdownOutput();            // failed b55
-
-        s1.close();
-        s2.close();
-        ss.close();
+        try {
+            s1.shutdownInput();
+            s1.shutdownOutput();            // failed b55
+        } finally {
+            s1.close();
+            s2.close();
+            ss.close();
+        }
     }
 
 }
--- a/test/java/net/Socket/SoTimeout.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/SoTimeout.java	Thu Aug 12 11:23:15 2010 -0700
@@ -52,9 +52,10 @@
         t.start();
 
         Socket s = serverSocket.accept();
+        serverSocket.close();
 
-        // set a 1 second timeout on the socket
-        s.setSoTimeout(1000);
+        // set a 5 second timeout on the socket
+        s.setSoTimeout(5000);
 
         s.getInputStream().read(b, 0, b.length);
         s.close();
@@ -64,7 +65,7 @@
         // this sequence should complete fairly quickly and if it
         // takes something resembling the the SoTimeout value then
         // we are probably incorrectly blocking and not waking up
-        if (waited > 500) {
+        if (waited > 2000) {
             throw new Exception("shouldn't take " + waited + " to complete");
         }
     }
--- a/test/java/net/Socket/Timeout.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/Timeout.java	Thu Aug 12 11:23:15 2010 -0700
@@ -31,18 +31,16 @@
 import java.io.*;
 
 public class Timeout {
-
-    public static ServerSocket sock;
-
     public static void main(String[] args) throws Exception {
         boolean success = false;
+        ServerSocket sock = new ServerSocket(0);
         try {
-            ServerSocket sock;
-            sock = new ServerSocket(2333);
             sock.setSoTimeout(2);
             sock.accept();
         } catch (InterruptedIOException e) {
             success = true;
+        } finally {
+            sock.close();
         }
         if (!success)
             throw new RuntimeException("Socket timeout failure.");
--- a/test/java/net/Socket/UrgentDataTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/UrgentDataTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -90,63 +90,64 @@
     }
 
     public void run () throws Exception {
-        if (isClient) {
-            client = new Socket (clHost, clPort);
-            clis = client.getInputStream();
-            clos = client.getOutputStream();
-            client.setOOBInline (true);
-            if (client.getOOBInline() != true) {
-                throw new RuntimeException ("Setting OOBINLINE failed");
-            }
-        }
-        if (isServer) {
-            server = listener.accept ();
-            sis = server.getInputStream();
-            sos = server.getOutputStream();
-        }
-        if (isClient) {
-            clos.write ("Hello".getBytes ());
-            client.sendUrgentData (100);
-            clos.write ("world".getBytes ());
-        }
-        // read Hello world from server (during which oob byte must have been dropped)
-        String s = "Helloworld";
-        if (isServer) {
-            for (int y=0; y<s.length(); y++) {
-                int c = sis.read ();
-                if (c != (int)s.charAt (y)) {
-                    throw new RuntimeException ("Unexpected character read");
+        try {
+            if (isClient) {
+                client = new Socket (clHost, clPort);
+                clis = client.getInputStream();
+                clos = client.getOutputStream();
+                client.setOOBInline (true);
+                if (client.getOOBInline() != true) {
+                    throw new RuntimeException ("Setting OOBINLINE failed");
                 }
             }
-            // Do the same from server to client
-            sos.write ("Hello".getBytes ());
-            server.sendUrgentData (101);
-            sos.write ("World".getBytes ());
-        }
-        if (isClient) {
-            // read Hello world from client (during which oob byte must have been read)
-            s="Hello";
-            for (int y=0; y<s.length(); y++) {
-                int c = clis.read ();
-                if (c != (int)s.charAt (y)) {
-                    throw new RuntimeException ("Unexpected character read");
+            if (isServer) {
+                server = listener.accept ();
+                sis = server.getInputStream();
+                sos = server.getOutputStream();
+            }
+            if (isClient) {
+                clos.write ("Hello".getBytes ());
+                client.sendUrgentData (100);
+                clos.write ("world".getBytes ());
+            }
+            // read Hello world from server (during which oob byte must have been dropped)
+            String s = "Helloworld";
+            if (isServer) {
+                for (int y=0; y<s.length(); y++) {
+                    int c = sis.read ();
+                    if (c != (int)s.charAt (y)) {
+                        throw new RuntimeException ("Unexpected character read");
+                    }
+                }
+                // Do the same from server to client
+                sos.write ("Hello".getBytes ());
+                server.sendUrgentData (101);
+                sos.write ("World".getBytes ());
+            }
+            if (isClient) {
+                // read Hello world from client (during which oob byte must have been read)
+                s="Hello";
+                for (int y=0; y<s.length(); y++) {
+                    int c = clis.read ();
+                    if (c != (int)s.charAt (y)) {
+                        throw new RuntimeException ("Unexpected character read");
+                    }
+                }
+                if (clis.read() != 101) {
+                    throw new RuntimeException ("OOB byte not received");
+                }
+                s="World";
+                for (int y=0; y<s.length(); y++) {
+                    int c = clis.read ();
+                    if (c != (int)s.charAt (y)) {
+                        throw new RuntimeException ("Unexpected character read");
+                    }
                 }
             }
-            if (clis.read() != 101) {
-                throw new RuntimeException ("OOB byte not received");
-            }
-            s="World";
-            for (int y=0; y<s.length(); y++) {
-                int c = clis.read ();
-                if (c != (int)s.charAt (y)) {
-                    throw new RuntimeException ("Unexpected character read");
-                }
-            }
+        } finally {
+            if (listener != null) listener.close();
+            if (client != null) client.close ();
+            if (server != null) server.close ();
         }
-
-        if (isClient)
-            client.close ();
-        if (isServer)
-            server.close ();
     }
 }
--- a/test/java/net/Socket/asyncClose/BrokenPipe.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/asyncClose/BrokenPipe.java	Thu Aug 12 11:23:15 2010 -0700
@@ -61,7 +61,6 @@
         try {
             client.getOutputStream().write(new byte[1000000]);
         } catch (IOException ioe) {
-
             /*
              * Check that the exception text doesn't indicate the
              * socket is closed. In tiger we should be able to
@@ -71,8 +70,9 @@
             if (text.toLowerCase().indexOf("closed") >= 0) {
                 throw ioe;
             }
+        } finally {
+            server.close();
         }
-        server.close();
     }
 
 }
--- a/test/java/net/Socket/setReuseAddress/Restart.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/Socket/setReuseAddress/Restart.java	Thu Aug 12 11:23:15 2010 -0700
@@ -39,27 +39,28 @@
      */
 
     public static void main(String args[]) throws Exception {
+        ServerSocket ss = new ServerSocket(0);
+        Socket s1 = null, s2 = null;
+        try {
+            int port = ss.getLocalPort();
 
-        InetSocketAddress isa = new InetSocketAddress(0);
-        ServerSocket ss = new ServerSocket();
-        ss.bind(isa);
+            s1 = new Socket(InetAddress.getLocalHost(), port);
+            s2 = ss.accept();
 
-        int port = ss.getLocalPort();
+            // close server socket and the accepted connection
+            ss.close();
+            s2.close();
 
-        Socket s1 = new Socket(InetAddress.getLocalHost(), port);
-        Socket s2 = ss.accept();
+            ss = new ServerSocket();
+            ss.bind( new InetSocketAddress(port) );
+            ss.close();
 
-        // close server socket and the accepted connection
-        ss.close();
-        s2.close();
-
-        boolean failed = false;
-
-        ss = new ServerSocket();
-        ss.bind( new InetSocketAddress(port) );
-        ss.close();
-
-        // close the client socket
-        s1.close();
+            // close the client socket
+            s1.close();
+        } finally {
+            if (ss != null) ss.close();
+            if (s1 != null) s1.close();
+            if (s2 != null) s2.close();
+        }
     }
 }
--- a/test/java/net/SocketInputStream/SocketClosedException.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/SocketInputStream/SocketClosedException.java	Thu Aug 12 11:23:15 2010 -0700
@@ -32,68 +32,37 @@
 import java.net.*;
 
 public class SocketClosedException {
+    static void doServerSide() throws Exception {
+        try {
+            Socket socket = serverSocket.accept();
 
-    /*
-     * Is the server ready to serve?
-     */
-    volatile static boolean serverReady = false;
+            OutputStream os = socket.getOutputStream();
 
-    /*
-     * Define the server side of the test.
-     *
-     * If the server prematurely exits, serverReady will be set to true
-     * to avoid infinite hangs.
-     */
-    static void doServerSide() throws Exception {
-        ServerSocket serverSocket = new ServerSocket(serverPort);
-        serverPort = serverSocket.getLocalPort();
-
-        /*
-         * Signal Client, we're ready for a connect.
-         */
-        serverReady = true;
-
-        Socket socket = serverSocket.accept();
-
-        InputStream is = socket.getInputStream();
-        OutputStream os = socket.getOutputStream();
-
-        os.write(85);
-        os.flush();
-        socket.close();
+            os.write(85);
+            os.flush();
+            socket.close();
+        } finally {
+            serverSocket.close();
+        }
     }
 
-    /*
-     * Define the client side of the test.
-     *
-     * If the server prematurely exits, serverReady will be set to true
-     * to avoid infinite hangs.
-     */
-    static void doClientSide() throws Exception {
+    static void doClientSide(int port) throws Exception {
+        Socket socket = new Socket("localhost", port);
+        InputStream is = socket.getInputStream();
 
-        /*
-         * Wait for server to get started.
-         */
-        while (!serverReady) {
-            Thread.sleep(5000);
-        }
-
-        Socket socket = new Socket("localhost", serverPort);
-        InputStream is = socket.getInputStream();
-        OutputStream os = socket.getOutputStream();
-
-        int read = is.read();
+        is.read();
         socket.close();
-        read = is.read();
+        is.read();
     }
 
-    static int serverPort = 0;
+    static ServerSocket serverSocket;
     static Exception serverException = null;
 
     public static void main(String[] args) throws Exception {
+        serverSocket = new ServerSocket(0);
         startServer();
         try {
-            doClientSide();
+            doClientSide(serverSocket.getLocalPort());
         } catch (SocketException e) {
             if (!e.getMessage().equalsIgnoreCase("Socket closed")) {
                 throw new Exception("Received a wrong exception message: " +
@@ -108,21 +77,14 @@
     }
 
     static void startServer() {
-        Thread serverThread = new Thread() {
+        (new Thread() {
             public void run() {
                 try {
                     doServerSide();
                 } catch (Exception e) {
-                    /*
-                     * server thread just died.
-                     * Release the client, if not active already...
-                     */
-                    System.err.println("Server died...");
-                    serverReady = true;
-                    serverException = e;
+                    e.printStackTrace();
                 }
             }
-        };
-        serverThread.start();
+        }).start();
     }
 }
--- a/test/java/net/SocketInputStream/SocketTimeout.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/SocketInputStream/SocketTimeout.java	Thu Aug 12 11:23:15 2010 -0700
@@ -31,26 +31,24 @@
 import java.io.*;
 
 public class SocketTimeout  {
+    static final int TIMEOUT = 1000;
+
     public static void main(String args[]) throws Exception {
-    InetAddress  sin = null;
+    InetAddress  sin = InetAddress.getLocalHost();
     Socket       soc = null,soc1 = null;
     InputStream  is = null;
-    OutputStream os = null;
     ServerSocket srv = null;
     int          port = 0;
-    int          tout = 1000;
 
-    sin = InetAddress.getLocalHost();
-    srv = new ServerSocket(port);
+    srv = new ServerSocket(0);
     port = srv.getLocalPort();
     soc = new Socket(sin, port);
     soc1 = srv.accept();
-    soc.setSoTimeout(tout);
-    srv.setSoTimeout(tout);
+    soc.setSoTimeout(TIMEOUT);
+    srv.setSoTimeout(TIMEOUT);
 
     try {
       is = soc.getInputStream();
-      os = soc1.getOutputStream();
       is.read();
     } catch(InterruptedIOException e) {
         try {
@@ -59,6 +57,9 @@
         } catch(NoClassDefFoundError e1) {
             throw new Exception ("SocketTimeoutException: not found");
         }
+    } finally {
+        soc.close();
+        soc1.close();
     }
 
     // now check accept
@@ -72,12 +73,14 @@
         } catch(NoClassDefFoundError e1) {
             throw new Exception ("SocketTimeoutException: not found");
         }
+    } finally {
+        srv.close();
     }
 
     // Now check DatagramSocket.receive()
 
     DatagramSocket dg = new DatagramSocket ();
-    dg.setSoTimeout (tout);
+    dg.setSoTimeout (TIMEOUT);
 
     try {
       dg.receive (new DatagramPacket (new byte [64], 64));
@@ -88,11 +91,8 @@
         } catch(NoClassDefFoundError e1) {
             throw new Exception ("SocketTimeoutException: not found");
         }
+    } finally {
+        dg.close();
     }
-
-    soc.close();
-    soc1.close();
-    srv.close();
-    dg.close();
   }
 }
--- a/test/java/net/URL/GetContent.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URL/GetContent.java	Thu Aug 12 11:23:15 2010 -0700
@@ -53,11 +53,13 @@
 
             // wait for client to read response - otherwise http
             // client get error and re-establish connection
-            Thread.currentThread().sleep(2000);
+            Thread.sleep(2000);
 
             s.close();
         } catch (Exception e) {
             e.printStackTrace();
+        } finally {
+            try { ss.close(); } catch (IOException unused) {}
         }
      }
 
@@ -81,8 +83,6 @@
              error = false;
          }
 
-         ss.close();
-
          if (error)
              throw new RuntimeException("No IOException generated.");
      }
--- a/test/java/net/URLClassLoader/ClassLoad.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLClassLoader/ClassLoad.java	Thu Aug 12 11:23:15 2010 -0700
@@ -27,20 +27,45 @@
  * @summary Test for FileNotFoundException when loading bogus class
  */
 
-import java.net.*;
-import java.io.*;
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URL;
+import java.net.URLClassLoader;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
 
 public class ClassLoad {
      public static void main(String[] args) throws Exception {
          boolean error = true;
+
+         // Start a dummy server to return 404
+         HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
+         HttpHandler handler = new HttpHandler() {
+             public void handle(HttpExchange t) throws IOException {
+                 InputStream is = t.getRequestBody();
+                 while (is.read() != -1);
+                 t.sendResponseHeaders (404, -1);
+                 t.close();
+             }
+         };
+         server.createContext("/", handler);
+         server.start();
+
+         // Client request
          try {
-             URL url = new URL(args.length >= 1 ? args[0] : "http://jini.east/");
+             URL url = new URL("http://localhost:" + server.getAddress().getPort());
              String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
              ClassLoader loader = new URLClassLoader(new URL[] { url });
+             System.out.println(url);
              Class c = loader.loadClass(name);
              System.out.println("Loaded class \"" + c.getName() + "\".");
          } catch (ClassNotFoundException ex) {
+             System.out.println(ex);
              error = false;
+         } finally {
+             server.stop(0);
          }
          if (error)
              throw new RuntimeException("No ClassNotFoundException generated");
--- a/test/java/net/URLConnection/DisconnectAfterEOF.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/DisconnectAfterEOF.java	Thu Aug 12 11:23:15 2010 -0700
@@ -56,7 +56,6 @@
                 int cl = -1;
                 int remaining = -1;
                 StringBuffer sb = new StringBuffer();
-                Random r = new Random();
                 boolean close = false;
 
                 boolean inBody = false;
@@ -239,8 +238,6 @@
     }
 
     public static void main(String args[]) throws Exception {
-        Random r = new Random();
-
         // start server
         ServerSocket ss = new ServerSocket(0);
         Server svr = new Server(ss);
@@ -273,7 +270,7 @@
         URLConnection uc1 = doRequest(uri);
         doResponse(uc1);
 
-        Thread.currentThread().sleep(2000);
+        Thread.sleep(2000);
 
         URLConnection uc2 = doRequest(uri);
 
--- a/test/java/net/URLConnection/HandleContentTypeWithAttrs.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/HandleContentTypeWithAttrs.java	Thu Aug 12 11:23:15 2010 -0700
@@ -111,9 +111,8 @@
             } catch(Exception e) {
                 System.out.print("Server failure\n");
                 e.printStackTrace();
-                try {
-                    serverSocket.close();
-                } catch(IOException e2) {}
+            } finally {
+                try { serverSocket.close(); } catch(IOException unused) {}
             }
         } else {
             try {
@@ -127,10 +126,9 @@
             } catch(Exception e) {
                 // System.out.print("Service handler failure\n");
                 // e.printStackTrace();
+            } finally {
+                try { close(); }  catch(IOException unused) {}
             }
-            try {
-                close();
-            } catch(IOException e2) {}
         }
     }
 
--- a/test/java/net/URLConnection/HttpContinueStackOverflow.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/HttpContinueStackOverflow.java	Thu Aug 12 11:23:15 2010 -0700
@@ -30,7 +30,7 @@
  */
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
+import java.io.IOException;
 import java.io.PrintStream;
 import java.net.ServerSocket;
 import java.net.Socket;
@@ -41,61 +41,56 @@
 
     static class Server implements Runnable {
         int port;
+        ServerSocket serverSock ;
 
-        Server(int port) {
-            this.port = port;
+        Server() throws IOException {
+            serverSock = new ServerSocket(0);
+        }
+
+        int getLocalPort() {
+            return serverSock.getLocalPort();
         }
 
         public void run() {
+            Socket sock = null;
             try {
-                /* bind to port and wait for connection */
-                ServerSocket serverSock = new ServerSocket(     port );
                 serverSock.setSoTimeout(10000);
-                Socket sock = serverSock.accept();
+                sock = serverSock.accept();
 
                 /* setup streams and read http request */
                 BufferedReader in = new BufferedReader(
                     new InputStreamReader(sock.getInputStream()));
                 PrintStream out = new PrintStream( sock.getOutputStream() );
-                String request = in.readLine();
+                in.readLine();
 
                 /* send continue followed by invalid response */
                 out.println("HTTP/1.1 100 Continue\r");
                 out.println("\r");
                 out.println("junk junk junk");
                 out.flush();
-
-                sock.close();
             } catch (Exception e) {
                 e.printStackTrace();
+            } finally {
+                try { serverSock.close(); } catch (IOException unused) {}
+                try { sock.close(); } catch (IOException unused) {}
             }
         }
     }
 
-    HttpContinueStackOverflow(int port) throws Exception {
+    HttpContinueStackOverflow() throws Exception {
         /* create the server */
-        Server s = new Server(port);
-        Thread thr = new Thread(s);
-        thr.start();
-
-        /* wait for server to bind to port */
-        try {
-            Thread.currentThread().sleep(2000);
-        } catch (Exception e) { }
+        Server s = new Server();
+        (new Thread(s)).start();
 
         /* connect to server, connect to server and get response code */
-        URL url = new URL("http", "localhost", port, "anything.html");
+        URL url = new URL("http", "localhost", s.getLocalPort(), "anything.html");
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
-        int respCode = conn.getResponseCode();
+        conn.getResponseCode();
         System.out.println("TEST PASSED");
     }
 
     public static void main(String args[]) throws Exception {
-        int port = 4090;
-        if (args.length > 0) {
-            port = Integer.parseInt(args[0]);
-        }
         System.out.println("Testing 100-Continue");
-        new HttpContinueStackOverflow(port);
+        new HttpContinueStackOverflow();
     }
 }
--- a/test/java/net/URLConnection/Redirect307Test.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/Redirect307Test.java	Thu Aug 12 11:23:15 2010 -0700
@@ -37,11 +37,11 @@
     OutputStream os;
     int port;
 
-    String reply1 = "HTTP/1.1 307 Temporary Redirect\r\n" +
+    String reply1Part1 = "HTTP/1.1 307 Temporary Redirect\r\n" +
         "Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
         "Server: Apache/1.3.14 (Unix)\r\n" +
         "Location: http://localhost:";
-    String reply2 = "/redirected.html\r\n" +
+    String reply1Part2 = "/redirected.html\r\n" +
         "Connection: close\r\n" +
         "Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
         "<html>Hello</html>";
@@ -49,9 +49,10 @@
     RedirServer (ServerSocket y) {
         s = y;
         port = s.getLocalPort();
+        System.out.println("Server created listening on " + port);
     }
 
-    String reply3 = "HTTP/1.1 200 Ok\r\n" +
+    String reply2 = "HTTP/1.1 200 Ok\r\n" +
         "Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
         "Server: Apache/1.3.14 (Unix)\r\n" +
         "Connection: close\r\n" +
@@ -64,16 +65,24 @@
             is = s1.getInputStream ();
             os = s1.getOutputStream ();
             is.read ();
-            String reply = reply1 + port + reply2;
+            String reply = reply1Part1 + port + reply1Part2;
             os.write (reply.getBytes());
+            os.close();
             /* wait for redirected connection */
             s.setSoTimeout (5000);
             s1 = s.accept ();
+            is = s1.getInputStream ();
             os = s1.getOutputStream ();
-            os.write (reply3.getBytes());
+            is.read();
+            os.write (reply2.getBytes());
+            os.close();
         }
         catch (Exception e) {
             /* Just need thread to terminate */
+            System.out.println("Server: caught " + e);
+            e.printStackTrace();
+        } finally {
+            try { s.close(); } catch (IOException unused) {}
         }
     }
 };
@@ -84,10 +93,7 @@
     public static final int DELAY = 10;
 
     public static void main(String[] args) throws Exception {
-        int nLoops = 1;
-        int nSize = 10;
-        int port, n =0;
-        byte b[] = new byte[nSize];
+        int port;
         RedirServer server;
         ServerSocket sock;
 
@@ -119,7 +125,8 @@
             }
         }
         catch(IOException e) {
-            throw new RuntimeException ("Exception caught");
+            e.printStackTrace();
+            throw new RuntimeException ("Exception caught + " + e);
         }
     }
 }
--- a/test/java/net/URLConnection/RedirectLimit.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/RedirectLimit.java	Thu Aug 12 11:23:15 2010 -0700
@@ -76,15 +76,19 @@
                 is.read ();
                 String reply = reply1 + port + "/redirect" + i + reply2;
                 os.write (reply.getBytes());
+                os.close();
             }
             s1 = s.accept ();
             is = s1.getInputStream ();
             os = s1.getOutputStream ();
             is.read ();
             os.write (reply3.getBytes());
+            os.close();
         }
         catch (Exception e) {
             /* Just need thread to terminate */
+        } finally {
+            try { s.close(); } catch (IOException unused) {}
         }
     }
 };
--- a/test/java/net/URLConnection/ResendPostBody.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/ResendPostBody.java	Thu Aug 12 11:23:15 2010 -0700
@@ -109,8 +109,11 @@
                 while (!finished()) {
                     Thread.sleep (1000);
                 }
+                out.close();
             } catch (Exception e) {
                 System.err.println ("Server Exception: " + e);
+            } finally {
+                try { server.close(); } catch (IOException unused) {}
             }
         }
     }
@@ -134,7 +137,7 @@
 
     public void execute () throws Exception {
 
-     byte b[] = "X=ABCDEFGHZZZ".getBytes();
+        byte b[] = "X=ABCDEFGHZZZ".getBytes();
 
         ss = new ServerSocket (0);
         server = new Server (ss);
@@ -163,8 +166,9 @@
         /* Read the response */
 
         int resp = conURL.getResponseCode ();
+        server.setFinished (true);
+
         if (resp != 200)
             throw new RuntimeException ("Response code was not 200: " + resp);
-      server.setFinished (true);
   }
 }
--- a/test/java/net/URLConnection/SetIfModifiedSince.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/SetIfModifiedSince.java	Thu Aug 12 11:23:15 2010 -0700
@@ -23,7 +23,7 @@
 
 /* @test
  * @bug 4397096
- * @run main SetIfModifiedSince
+ * @run main/othervm SetIfModifiedSince
  * @summary setIfModifiedSince() of HttpURLConnection sets invalid date of default locale
  */
 
--- a/test/java/net/URLConnection/TimeoutTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/TimeoutTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -43,8 +43,9 @@
             try {
                 Socket s = server.accept ();
                 while (!finished ()) {
-                    Thread.sleep (2000);
+                    Thread.sleep (1000);
                 }
+                s.close();
             } catch (Exception e) {
             }
         }
@@ -70,9 +71,12 @@
             URL url = new URL ("http://127.0.0.1:"+ss.getLocalPort());
             URLConnection urlc = url.openConnection ();
             InputStream is = urlc.getInputStream ();
+            throw new RuntimeException("Should have received timeout");
         } catch (SocketTimeoutException e) {
-            s.done ();
             return;
+        } finally {
+            s.done();
+            ss.close();
         }
     }
 }
--- a/test/java/net/URLConnection/URLConnectionHeaders.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/URLConnectionHeaders.java	Thu Aug 12 11:23:15 2010 -0700
@@ -70,8 +70,10 @@
                 w.newLine();
                 w.flush();
                 s.close ();
-                srv.close (); // or else the HTTPURLConnection will retry
-            } catch (IOException e) { e.printStackTrace();}
+            } catch (IOException e) { e.printStackTrace();
+            } finally {
+                try { srv.close(); } catch (IOException unused) {}
+            }
         }
     }
 
--- a/test/java/net/URLConnection/ZeroContentLength.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/URLConnection/ZeroContentLength.java	Thu Aug 12 11:23:15 2010 -0700
@@ -58,6 +58,14 @@
         contentLength = cl;
     }
 
+    static synchronized String getResponse() {
+        return response;
+    }
+
+    static synchronized int getContentLength() {
+        return contentLength;
+    }
+
     /*
      * Worker thread to service single connection - can service
      * multiple http requests on same connection.
@@ -71,25 +79,44 @@
             this.id = id;
         }
 
+        final int CR = '\r';
+        final int LF = '\n';
+
         public void run() {
             try {
 
                 s.setSoTimeout(2000);
-                int max = 100;
+                int max = 20; // there should only be 20 connections
+                InputStream in = new BufferedInputStream(s.getInputStream());
 
                 for (;;) {
-
-                    // read entire request from client
-                    byte b[] = new byte[100];
-                    InputStream in = s.getInputStream();
-                    int n, total=0;
+                    // read entire request from client, until CR LF CR LF
+                    int c, total=0;
 
                     try {
-                        do {
-                            n = in.read(b);
-                            if (n > 0) total += n;
-                        } while (n > 0);
-                    } catch (SocketTimeoutException e) { }
+                        while ((c = in.read()) > 0) {
+                            total++;
+                            if (c == CR) {
+                                if ((c = in.read()) > 0) {
+                                    total++;
+                                    if (c == LF) {
+                                        if ((c = in.read()) > 0) {
+                                            total++;
+                                            if (c == CR) {
+                                                if ((c = in.read()) > 0) {
+                                                    total++;
+                                                    if (c == LF) {
+                                                        break;
+                                                    }
+                                                }
+                                            }
+                                        }
+                                    }
+                                }
+                            }
+
+                        }
+                    } catch (SocketTimeoutException e) {}
 
                     debug("worker " + id +
                         ": Read request from client " +
@@ -105,19 +132,20 @@
                                         new BufferedOutputStream(
                                                 s.getOutputStream() ));
 
-                    out.print("HTTP/1.1 " + response + "\r\n");
-                    if (contentLength >= 0) {
-                        out.print("Content-Length: " + contentLength +
+                    out.print("HTTP/1.1 " + getResponse() + "\r\n");
+                    int clen = getContentLength();
+                    if (clen >= 0) {
+                        out.print("Content-Length: " + clen +
                                     "\r\n");
                     }
                     out.print("\r\n");
-                    for (int i=0; i<contentLength; i++) {
+                    for (int i=0; i<clen; i++) {
                         out.write( (byte)'.' );
                     }
                     out.flush();
 
                     debug("worked " + id +
-                        ": Sent response to client, length: " + contentLength);
+                        ": Sent response to client, length: " + clen);
 
                     if (--max == 0) {
                         s.close();
--- a/test/java/net/ipv6tests/B6521014.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/ipv6tests/B6521014.java	Thu Aug 12 11:23:15 2010 -0700
@@ -58,6 +58,8 @@
         Enumeration e = NetworkInterface.getNetworkInterfaces();
         while (e.hasMoreElements()) {
             NetworkInterface ifc = (NetworkInterface) e.nextElement();
+            if (!ifc.isUp())
+                continue;
             Enumeration addrs = ifc.getInetAddresses();
             while (addrs.hasMoreElements()) {
                 InetAddress a = (InetAddress)addrs.nextElement();
--- a/test/java/net/ipv6tests/TcpTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/ipv6tests/TcpTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -38,7 +38,6 @@
     static InetAddress ia4any;
     static InetAddress ia6any;
     static Inet6Address ia6addr;
-    static InetAddress ia6bad; /* a global 6to4 IPv6 address, which cant be connected to */
     static Inet4Address ia4addr;
 
     static {
@@ -47,14 +46,6 @@
         try {
             ia4any = InetAddress.getByName ("0.0.0.0");
             ia6any = InetAddress.getByName ("::0");
-            if (ia6addr != null) {
-                int scope = ia6addr.getScopeId();
-                if (scope != 0) {
-                    ia6bad = InetAddress.getByName ("fe80::1:2:3:4:5:6%"+scope);
-                }
-            } else {
-                ia6bad = InetAddress.getByName ("fe80::1:2:3:4:5:6");
-            }
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -69,7 +60,6 @@
         dprintln ("Local Addresses");
         dprintln (ia4addr.toString());
         dprintln (ia6addr.toString());
-        dprintln ("Bad address: " + ia6bad);
         test1 (0);
         test1 (5100);
         test2();
@@ -224,19 +214,6 @@
         c1.close (); c2.close();
         s1.close (); s2.close();
 
-        /* check if connect() timesout when connecting to unknown dest. */
-
-        c1 = new Socket();
-        t1 = System.currentTimeMillis();
-        InetSocketAddress ad1 = new InetSocketAddress (ia6bad, 2500);
-        try {
-            c1.connect (ad1, 5000);
-            throw new RuntimeException ("timeout exception was expected");
-        } catch (SocketTimeoutException e) {
-            t1 = System.currentTimeMillis() - t1;
-            checkTime (t1, 5000);
-        } catch (NoRouteToHostException e1) {
-        }
         System.out.println ("Test3: OK");
     }
 
--- a/test/java/net/ipv6tests/Tests.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/net/ipv6tests/Tests.java	Thu Aug 12 11:23:15 2010 -0700
@@ -134,11 +134,11 @@
         }
     }
 
-    /* check the time got is within 20% of the time expected */
+    /* check the time got is within 50% of the time expected */
     public static void checkTime (long got, long expected) {
         dprintln ("checkTime: got " + got + " expected " + expected);
-        long upper = expected + (expected / 5);
-        long lower = expected - (expected / 5);
+        long upper = expected + (expected / 2);
+        long lower = expected - (expected / 2);
         if (got > upper || got < lower) {
             throw new RuntimeException ("checkTime failed: got " + got + " expected " + expected);
         }
--- a/test/java/nio/MappedByteBuffer/Basic.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/nio/MappedByteBuffer/Basic.java	Thu Aug 12 11:23:15 2010 -0700
@@ -22,7 +22,7 @@
  */
 
 /* @test
- * @bug 4462336
+ * @bug 4462336 6799037
  * @summary Simple MappedByteBuffer tests
  * @run main/othervm Basic
  */
@@ -52,6 +52,12 @@
         mbb.force();
         if (!mbb.isReadOnly())
             throw new RuntimeException("Incorrect isReadOnly");
+
+        // repeat with unaligned position in file
+        mbb = fc.map(FileChannel.MapMode.READ_ONLY, 1, 10);
+        mbb.load();
+        mbb.isLoaded();
+        mbb.force();
         fc.close();
         fis.close();
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/nio/MappedByteBuffer/Truncate.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2010, 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
+ * @bug 6934977
+ * @summary Test MappedByteBuffer operations after mapped bye buffer becomes
+ *   inaccessible
+ * @run main/othervm Truncate
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.concurrent.Callable;
+
+public class Truncate {
+
+    static final long INITIAL_FILE_SIZE   = 32000L;
+    static final long TRUNCATED_FILE_SIZE =   512L;
+
+    public static void main(String[] args) throws Exception {
+        File blah = File.createTempFile("blah", null);
+        blah.deleteOnExit();
+
+        final FileChannel fc = new RandomAccessFile(blah, "rw").getChannel();
+        fc.position(INITIAL_FILE_SIZE).write(ByteBuffer.wrap("THE END".getBytes()));
+        final MappedByteBuffer mbb =
+            fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
+        boolean truncated;
+        try {
+            fc.truncate(TRUNCATED_FILE_SIZE);
+            truncated = true;
+        } catch (IOException ioe) {
+            // probably on Windows where a file cannot be truncated when
+            // there is a file mapping.
+            truncated = false;
+        }
+        if (truncated) {
+            // Test 1: access region that is no longer accessible
+            execute(new Callable<Void>() {
+                public Void call() {
+                    mbb.get((int)TRUNCATED_FILE_SIZE + 1);
+                    mbb.put((int)TRUNCATED_FILE_SIZE + 2, (byte)123);
+                    return null;
+                }
+            });
+            // Test 2: load buffer into memory
+            execute(new Callable<Void>() {
+                public Void call() throws IOException {
+                    mbb.load();
+                    return null;
+                }
+            });
+        }
+        fc.close();
+    }
+
+    // Runs the given task in its own thread. If operating correcting the
+    // the thread will terminate with an InternalError as the mapped buffer
+    // is inaccessible.
+    static void execute(final Callable<?> c) {
+        Runnable r = new Runnable() {
+            public void run() {
+                try {
+                    Object ignore = c.call();
+                } catch (Exception ignore) {
+                }
+            }
+        };
+        Thread t = new Thread(r);
+        t.start();
+        try { t.join(); } catch (InterruptedException ignore) { }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/nio/channels/SocketChannel/OutOfBand.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2010, 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 socket adapter sendUrgentData method
+ * @bug 6963907
+ */
+
+import java.net.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.io.IOException;
+import java.util.Random;
+
+public class OutOfBand {
+
+    private static final Random rand = new Random();
+
+    public static void main(String[] args) throws Exception {
+        ServerSocketChannel ssc = null;
+        SocketChannel sc1 = null;
+        SocketChannel sc2 = null;
+
+        try {
+
+            // establish loopback connection
+            ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));
+            InetAddress lh = InetAddress.getLocalHost();
+            SocketAddress remote =
+                new InetSocketAddress(lh, ssc.socket().getLocalPort());
+            sc1 = SocketChannel.open(remote);
+            sc2 = ssc.accept();
+
+            // enable SO_OOBLINE on server side
+            sc2.socket().setOOBInline(true);
+
+            // run tests
+            test1(sc1, sc2);
+            test2(sc1, sc2);
+            test3(sc1, sc2);
+            test4(sc1);
+
+        } finally {
+            if (sc1 != null) sc1.close();
+            if (sc2 != null) sc2.close();
+            if (ssc != null) ssc.close();
+        }
+    }
+
+    /**
+     * Basic test to check that OOB/TCP urgent byte is received.
+     */
+    static void test1(SocketChannel client, SocketChannel server)
+        throws Exception
+    {
+        assert server.socket().getOOBInline();
+        ByteBuffer bb = ByteBuffer.allocate(100);
+        for (int i=0; i<1000; i++) {
+            int b1 = -127 + rand.nextInt(384);
+            client.socket().sendUrgentData(b1);
+
+            bb.clear();
+            if (server.read(bb) != 1)
+                throw new RuntimeException("One byte expected");
+            bb.flip();
+            byte b2 = bb.get();
+            if ((byte)b1 != b2)
+                throw new RuntimeException("Unexpected byte");
+        }
+    }
+
+    /**
+     * Basic test to check that OOB/TCP urgent byte is received, maybe with
+     * OOB mark changing.
+     */
+    static void test2(final SocketChannel client, SocketChannel server)
+        throws Exception
+    {
+        assert server.socket().getOOBInline();
+        Runnable sender = new Runnable() {
+            public void run() {
+                try {
+                    for (int i=0; i<256; i++)
+                        client.socket().sendUrgentData(i);
+                } catch (IOException ioe) {
+                    ioe.printStackTrace();
+                }
+            }
+        };
+        Thread thr = new Thread(sender);
+        thr.start();
+
+        ByteBuffer bb = ByteBuffer.allocate(256);
+        while (bb.hasRemaining()) {
+            if (server.read(bb) < 0)
+                throw new RuntimeException("Unexpected EOF");
+        }
+        bb.flip();
+        byte expect = 0;
+        while (bb.hasRemaining()) {
+            if (bb.get() != expect)
+                throw new RuntimeException("Unexpected byte");
+            expect++;
+        }
+
+        thr.join();
+    }
+
+    /**
+     * Test that is close to some real world examples where an urgent byte is
+     * used to "cancel" a long running query or transaction on the server.
+     */
+    static void test3(SocketChannel client, final SocketChannel server)
+        throws Exception
+    {
+        final int STOP = rand.nextInt(256);
+
+        assert server.socket().getOOBInline();
+        Runnable reader = new Runnable() {
+            public void run() {
+                ByteBuffer bb = ByteBuffer.allocate(100);
+                try {
+                    int n = server.read(bb);
+                    if (n != 1) {
+                        String msg = (n < 0) ? "Unexpected EOF" :
+                                               "One byte expected";
+                        throw new RuntimeException(msg);
+                    }
+                    bb.flip();
+                    if (bb.get() != (byte)STOP)
+                        throw new RuntimeException("Unexpected byte");
+                    bb.flip();
+                    server.write(bb);
+                } catch (IOException ioe) {
+                    ioe.printStackTrace();
+                }
+
+            }
+        };
+
+        Thread thr = new Thread(reader);
+        thr.start();
+
+        // "stop" server
+        client.socket().sendUrgentData(STOP);
+
+        // wait for server reply
+        ByteBuffer bb = ByteBuffer.allocate(100);
+        int n = client.read(bb);
+        if (n != 1)
+            throw new RuntimeException("Unexpected number of bytes");
+        bb.flip();
+        if (bb.get() != (byte)STOP)
+            throw new RuntimeException("Unexpected reply");
+
+        thr.join();
+    }
+
+    static void test4(SocketChannel sc) throws IOException {
+        boolean blocking = sc.isBlocking();
+        sc.configureBlocking(false);
+        try {
+            sc.socket().sendUrgentData(0);
+            throw new RuntimeException("IllegalBlockingModeException expected");
+        } catch (IllegalBlockingModeException x) {
+            // expected
+        } finally {
+            sc.configureBlocking(blocking);
+        }
+    }
+}
--- a/test/java/util/logging/AnonLoggerWeakRefLeak.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/util/logging/AnonLoggerWeakRefLeak.java	Thu Aug 12 11:23:15 2010 -0700
@@ -23,24 +23,32 @@
 
 import java.util.logging.*;
 
-public class AnonLoggerWeakRefLeak {
-    public static int DEFAULT_LOOP_TIME = 60;  // time is in seconds
+public class AnonLoggerWeakRefLeak extends SimpleApplication {
+    // The test driver script will allow this program to run until we
+    // reach DEFAULT_LOOP_TIME or a decrease in instance counts is
+    // observed. For this particular WeakReference leak, the count
+    // was always observed to be increasing so if we get a decreasing
+    // count, then the leak is fixed in the bits being tested.
+    // Two minutes has been enough time to observe a decrease in
+    // fixed bits on overloaded systems, but the test will likely
+    // finish more quickly.
+    public static int DEFAULT_LOOP_TIME = 120;  // time is in seconds
 
-    public static void main(String[] args) {
+    // execute the AnonLoggerWeakRefLeak app work
+    public void doMyAppWork(String[] args) throws Exception {
         int loop_time = 0;
         int max_loop_time = DEFAULT_LOOP_TIME;
 
-        if (args.length == 0) {
+        // args[0] is the port-file
+        if (args.length < 2) {
             System.out.println("INFO: using default time of "
                 + max_loop_time + " seconds.");
         } else {
             try {
-                max_loop_time = Integer.parseInt(args[0]);
+                max_loop_time = Integer.parseInt(args[1]);
             } catch (NumberFormatException nfe) {
-                System.err.println("Error: '" + args[0]
+                throw new RuntimeException("Error: '" + args[1]
                     + "': is not a valid seconds value.");
-                System.err.println("Usage: AnonLoggerWeakRefLeak [seconds]");
-                System.exit(1);
             }
         }
 
@@ -73,4 +81,12 @@
 
         System.out.println("INFO: final loop count = " + count);
     }
+
+    public static void main(String[] args) throws Exception {
+        AnonLoggerWeakRefLeak myApp = new AnonLoggerWeakRefLeak();
+
+        SimpleApplication.setMyApp(myApp);
+
+        SimpleApplication.main(args);
+    }
 }
--- a/test/java/util/logging/AnonLoggerWeakRefLeak.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/util/logging/AnonLoggerWeakRefLeak.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,3 +1,5 @@
+#!/bin/sh
+
 #
 # Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -23,76 +25,24 @@
 
 # @test
 # @bug 6942989
-# @ignore until 6964018 is fixed
 # @summary Check for WeakReference leak in anonymous Logger objects
 # @author Daniel D. Daugherty
 #
-# @run build AnonLoggerWeakRefLeak
-# @run shell/timeout=180 AnonLoggerWeakRefLeak.sh
+# @library ../../../sun/tools/common
+# @build SimpleApplication ShutdownSimpleApplication
+# @build AnonLoggerWeakRefLeak
+# @run shell/timeout=240 AnonLoggerWeakRefLeak.sh
 
-# The timeout is: 2 minutes for infrastructure and 1 minute for the test
+# The timeout is: 2 minutes for infrastructure and 2 minutes for the test
 #
 
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
+. ${TESTSRC}/../../../sun/tools/common/CommonSetup.sh
+. ${TESTSRC}/../../../sun/tools/common/ApplicationSetup.sh
 
-if [ "${TESTSRC}" = "" ]
-then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-
-JAVA="${TESTJAVA}"/bin/java
-JMAP="${TESTJAVA}"/bin/jmap
-JPS="${TESTJAVA}"/bin/jps
-
-set -eu
 
 TEST_NAME="AnonLoggerWeakRefLeak"
 TARGET_CLASS="java\.lang\.ref\.WeakReference"
 
-is_cygwin=false
-is_mks=false
-is_windows=false
-
-case `uname -s` in
-CYGWIN*)
-    is_cygwin=true
-    is_windows=true
-    ;;
-Windows_*)
-    is_mks=true
-    is_windows=true
-    ;;
-*)
-    ;;
-esac
-
-
-# wrapper for grep
-#
-grep_cmd() {
-    set +e
-    if $is_windows; then
-        # need dos2unix to get rid of CTRL-M chars from java output
-        dos2unix | grep "$@"
-        status="$?"
-    else
-        grep "$@"
-        status="$?"
-    fi
-    set -e
-}
-
 
 # MAIN begins here
 #
@@ -105,62 +55,64 @@
 # see if this version of jmap supports the '-histo:live' option
 jmap_option="-histo:live"
 set +e
-"${JMAP}" "$jmap_option" 0 > "$TEST_NAME.jmap" 2>&1
-grep '^Usage: ' "$TEST_NAME.jmap" > /dev/null 2>&1
+"${JMAP}" 2>&1 | grep ':live' > /dev/null 2>&1
 status="$?"
 set -e
-if [ "$status" = 0 ]; then
-    echo "INFO: switching jmap option from '$jmap_option'\c"
-    jmap_option="-histo"
-    echo " to '$jmap_option'."
+if [ "$status" != 0 ]; then
+    # usage message doesn't show ':live' option
+
+    if $isWindows; then
+        # If SA isn't present, then jmap gives a different usage message
+        # that doesn't show the ':live' option. However, that's a bug that
+        # is covered by 6971851 so we try using the option just to be sure.
+        # For some reason, this problem has only been seen on OpenJDK6 on
+        # Windows. Not sure why.
+        set +e
+        # Note: Don't copy this code to try probing process 0 on Linux; it
+        # will kill the process group in strange ways.
+        "${JMAP}" "$jmap_option" 0 2>&1 | grep 'Usage' > /dev/null 2>&1
+        status="$?"
+        set -e
+        if [ "$status" = 0 ]; then
+            # Usage message generated so flag the problem.
+            status=1
+        else
+            # No usage message so clear the flag.
+            status=0
+        fi
+    fi
+
+    if [ "$status" != 0 ]; then
+        echo "ERROR: 'jmap $jmap_option' is not supported so this test"
+        echo "ERROR: cannot work reliably. Aborting!"
+        exit 2
+    fi
 fi
 
-"${JAVA}" ${TESTVMOPTS} -classpath "${TESTCLASSES}" \
-    "$TEST_NAME" $seconds > "$TEST_NAME.log" 2>&1 &
-test_pid="$!"
-echo "INFO: starting $TEST_NAME as pid = $test_pid"
+# Start application and use TEST_NAME.port for coordination
+startApplication "$TEST_NAME" "$TEST_NAME.port" $seconds
 
-# wait for test program to get going
-count=0
-while [ "$count" -lt 30 ]; do
-    sleep 2
-    grep_cmd '^INFO: call count = 0$' < "$TEST_NAME.log" > /dev/null 2>&1
-    if [ "$status" = 0 ]; then
-        break
-    fi
-    count=`expr $count + 1`
-done
-
-if [ "$count" -ge 30 ]; then
-    echo "ERROR: $TEST_NAME failed to get going." >&2
-    echo "INFO: killing $test_pid"
-    kill "$test_pid"
-    exit 1
-elif [ "$count" -gt 1 ]; then
-    echo "INFO: $TEST_NAME took $count loops to start."
-fi
-
-if $is_cygwin; then
-    # We need the Windows pid for jmap and not the Cygwin pid.
-    # Note: '\t' works on Cygwin, but doesn't seem to work on Solaris.
-    jmap_pid=`"${JPS}"| grep_cmd "[ \t]$TEST_NAME$" | sed 's/[ \t].*//'`
-    if [ -z "$jmap_pid" ]; then
-        echo "FAIL: jps could not map Cygwin pid to Windows pid." >&2
-        echo "INFO: killing $test_pid"
-        kill "$test_pid"
-        exit 2
-    fi
-    echo "INFO: pid = $test_pid maps to Windows pid = $jmap_pid"
-else
-    jmap_pid="$test_pid"
-fi
+finished_early=false
 
 decreasing_cnt=0
 increasing_cnt=0
 loop_cnt=0
 prev_instance_cnt=0
 
+MAX_JMAP_TRY_CNT=10
+jmap_retry_cnt=0
+loop_cnt_on_retry=0
+
 while true; do
+    # see if the target process has finished its run and bail if it has
+    set +e
+    grep "^INFO: final loop count = " "$appOutput" > /dev/null 2>&1
+    status="$?"
+    set -e
+    if [ "$status" = 0 ]; then
+        break
+    fi
+
     # Output format for 'jmap -histo' in JDK1.5.0:
     #
     #     <#bytes> <#instances> <class_name>
@@ -170,38 +122,70 @@
     #     <num>: <#instances> <#bytes> <class_name>
     #
     set +e
-    "${JMAP}" "$jmap_option" "$jmap_pid" > "$TEST_NAME.jmap" 2>&1
+    "${JMAP}" "$jmap_option" "$appJavaPid" > "$TEST_NAME.jmap" 2>&1
     status="$?"
     set -e
 
     if [ "$status" != 0 ]; then
         echo "INFO: jmap exited with exit code = $status"
-        if [ "$loop_cnt" = 0 ]; then
-            echo "INFO: on the first iteration so no samples were taken."
-            echo "INFO: start of jmap output:"
-            cat "$TEST_NAME.jmap"
-            echo "INFO: end of jmap output."
+
+        # There are intermittent jmap failures; see 6498448.
+        #
+        # So far the following have been observed in a jmap call
+        # that was not in a race with target process termination:
+        #
+        # (Solaris specific, 2nd sample)
+        # <pid>: Unable to open door: target process not responding or HotSpot VM not loaded
+        # The -F option can be used when the target process is not responding
+        #
+        # (on Solaris so far)
+        # java.io.IOException
+        #
+        # (on Solaris so far, 1st sample)
+        # <pid>: Permission denied
+        #
+        sed 's/^/INFO: /' "$TEST_NAME.jmap"
+
+        if [ "$loop_cnt" = "$loop_cnt_on_retry" ]; then
+            # loop count hasn't changed
+            jmap_retry_cnt=`expr $jmap_retry_cnt + 1`
+        else
+            # loop count has changed so remember it
+            jmap_retry_cnt=1
+            loop_cnt_on_retry="$loop_cnt"
+        fi
+
+        # This is '-ge' because we have the original attempt plus
+        # MAX_JMAP_TRY_CNT - 1 retries.
+        if [ "$jmap_retry_cnt" -ge "$MAX_JMAP_TRY_CNT" ]; then
+            echo "INFO: jmap failed $MAX_JMAP_TRY_CNT times in a row" \
+                "without making any progress."
             echo "FAIL: jmap is unable to take any samples." >&2
-            echo "INFO: killing $test_pid"
-            kill "$test_pid"
+            killApplication
             exit 2
         fi
-        echo "INFO: The likely reason is that $TEST_NAME has finished running."
-        break
+
+        # short delay and try again
+        # Note: sleep 1 didn't help with "<pid>: Permission denied"
+        sleep 2
+        echo "INFO: retrying jmap (retry=$jmap_retry_cnt, loop=$loop_cnt)."
+        continue
     fi
 
-    instance_cnt=`grep_cmd "[ 	]$TARGET_CLASS$" \
-        < "$TEST_NAME.jmap" \
+    set +e
+    instance_cnt=`grep "${PATTERN_WS}${TARGET_CLASS}${PATTERN_EOL}" \
+        "$TEST_NAME.jmap" \
         | sed '
             # strip leading whitespace; does nothing in JDK1.5.0
-            s/^[ 	][ 	]*//
+            s/^'"${PATTERN_WS}${PATTERN_WS}"'*//
             # strip <#bytes> in JDK1.5.0; does nothing otherwise
-            s/^[1-9][0-9]*[ 	][ 	]*//
+            s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*//
             # strip <num>: field; does nothing in JDK1.5.0
-            s/^[1-9][0-9]*:[ 	][ 	]*//
+            s/^[1-9][0-9]*:'"${PATTERN_WS}${PATTERN_WS}"'*//
             # strip <class_name> field
-            s/[ 	].*//
+            s/'"${PATTERN_WS}"'.*//
             '`
+    set -e
     if [ -z "$instance_cnt" ]; then
         echo "INFO: instance count is unexpectedly empty"
         if [ "$loop_cnt" = 0 ]; then
@@ -211,8 +195,7 @@
             cat "$TEST_NAME.jmap"
             echo "INFO: end of jmap output."
             echo "FAIL: cannot find the instance count value." >&2
-            echo "INFO: killing $test_pid"
-            kill "$test_pid"
+            killApplication
             exit 2
         fi
     else
@@ -221,7 +204,17 @@
         if [ "$instance_cnt" -gt "$prev_instance_cnt" ]; then
             increasing_cnt=`expr $increasing_cnt + 1`
         else
+            # actually decreasing or the same
             decreasing_cnt=`expr $decreasing_cnt + 1`
+
+            # For this particular WeakReference leak, the count was
+            # always observed to be increasing so if we get a decreasing
+            # or the same count, then the leak is fixed in the bits
+            # being tested.
+            echo "INFO: finishing early due to non-increasing instance count."
+            finished_early=true
+            killApplication
+            break
         fi
         prev_instance_cnt="$instance_cnt"
     fi
@@ -232,8 +225,22 @@
     loop_cnt=`expr $loop_cnt + 1`
 done
 
+if [ $finished_early = false ]; then
+    stopApplication "$TEST_NAME.port"
+    waitForApplication
+fi
+
+echo "INFO: $TEST_NAME has finished running."
 echo "INFO: increasing_cnt = $increasing_cnt"
 echo "INFO: decreasing_cnt = $decreasing_cnt"
+if [ "$jmap_retry_cnt" -gt 0 ]; then
+    echo "INFO: jmap_retry_cnt = $jmap_retry_cnt (in $loop_cnt iterations)"
+fi
+
+if [ "$loop_cnt" = 0 ]; then
+    echo "FAIL: jmap is unable to take any samples." >&2
+    exit 2
+fi
 
 echo "INFO: The instance count of" `eval echo $TARGET_CLASS` "objects"
 if [ "$decreasing_cnt" = 0 ]; then
@@ -242,6 +249,6 @@
     exit 2
 fi
 
-echo "INFO: is both increasing and decreasing."
+echo "INFO: is not always increasing."
 echo "PASS: This indicates that there is not a memory leak."
 exit 0
--- a/test/java/util/logging/LoggerWeakRefLeak.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/util/logging/LoggerWeakRefLeak.java	Thu Aug 12 11:23:15 2010 -0700
@@ -23,27 +23,32 @@
 
 import java.util.logging.*;
 
-public class LoggerWeakRefLeak {
-    // AnonLoggerWeakRefLeak checks for one weak reference leak.
-    // LoggerWeakRefLeak checks for two weak reference leaks so
-    // this test runs twice as long, by default.
+public class LoggerWeakRefLeak extends SimpleApplication {
+    // The test driver script will allow this program to run until we
+    // reach DEFAULT_LOOP_TIME or a decrease in instance counts is
+    // observed. For these particular WeakReference leaks, the count
+    // was always observed to be increasing so if we get a decreasing
+    // count, then the leaks are fixed in the bits being tested.
+    // Two minutes has been enough time to observe a decrease in
+    // fixed bits on overloaded systems, but the test will likely
+    // finish more quickly.
     public static int DEFAULT_LOOP_TIME = 120;  // time is in seconds
 
-    public static void main(String[] args) {
+    // execute the LoggerWeakRefLeak app work
+    public void doMyAppWork(String[] args) throws Exception {
         int loop_time = 0;
         int max_loop_time = DEFAULT_LOOP_TIME;
 
-        if (args.length == 0) {
+        // args[0] is the port-file
+        if (args.length < 2) {
             System.out.println("INFO: using default time of "
                 + max_loop_time + " seconds.");
         } else {
             try {
-                max_loop_time = Integer.parseInt(args[0]);
+                max_loop_time = Integer.parseInt(args[1]);
             } catch (NumberFormatException nfe) {
-                System.err.println("Error: '" + args[0]
+                throw new RuntimeException("Error: '" + args[1]
                     + "': is not a valid seconds value.");
-                System.err.println("Usage: LoggerWeakRefLeak [seconds]");
-                System.exit(1);
             }
         }
 
@@ -86,4 +91,12 @@
 
         System.out.println("INFO: final loop count = " + count);
     }
+
+    public static void main(String[] args) throws Exception {
+        AnonLoggerWeakRefLeak myApp = new AnonLoggerWeakRefLeak();
+
+        SimpleApplication.setMyApp(myApp);
+
+        SimpleApplication.main(args);
+    }
 }
--- a/test/java/util/logging/LoggerWeakRefLeak.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/java/util/logging/LoggerWeakRefLeak.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,3 +1,5 @@
+#!/bin/sh
+
 #
 # Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -23,76 +25,24 @@
 
 # @test
 # @bug 6942989
-# @ignore until 6964018 is fixed
 # @summary Check for WeakReference leak in Logger objects
 # @author Daniel D. Daugherty
 #
-# @run build LoggerWeakRefLeak
+# @library ../../../sun/tools/common
+# @build SimpleApplication ShutdownSimpleApplication
+# @build LoggerWeakRefLeak
 # @run shell/timeout=240 LoggerWeakRefLeak.sh
 
-# The timeout is: 2 minutes for infrastructure and 1 minute for the test
+# The timeout is: 2 minutes for infrastructure and 2 minutes for the test
 #
 
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
+. ${TESTSRC}/../../../sun/tools/common/CommonSetup.sh
+. ${TESTSRC}/../../../sun/tools/common/ApplicationSetup.sh
 
-if [ "${TESTSRC}" = "" ]
-then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-
-JAVA="${TESTJAVA}"/bin/java
-JMAP="${TESTJAVA}"/bin/jmap
-JPS="${TESTJAVA}"/bin/jps
-
-set -eu
 
 TEST_NAME="LoggerWeakRefLeak"
 TARGET_CLASS="java\.lang\.ref\.WeakReference"
 
-is_cygwin=false
-is_mks=false
-is_windows=false
-
-case `uname -s` in
-CYGWIN*)
-    is_cygwin=true
-    is_windows=true
-    ;;
-Windows_*)
-    is_mks=true
-    is_windows=true
-    ;;
-*)
-    ;;
-esac
-
-
-# wrapper for grep
-#
-grep_cmd() {
-    set +e
-    if $is_windows; then
-        # need dos2unix to get rid of CTRL-M chars from java output
-        dos2unix | grep "$@"
-        status="$?"
-    else
-        grep "$@"
-        status="$?"
-    fi
-    set -e
-}
-
 
 # MAIN begins here
 #
@@ -105,62 +55,64 @@
 # see if this version of jmap supports the '-histo:live' option
 jmap_option="-histo:live"
 set +e
-"${JMAP}" "$jmap_option" 0 > "$TEST_NAME.jmap" 2>&1
-grep '^Usage: ' "$TEST_NAME.jmap" > /dev/null 2>&1
+"${JMAP}" 2>&1 | grep ':live' > /dev/null 2>&1
 status="$?"
 set -e
-if [ "$status" = 0 ]; then
-    echo "INFO: switching jmap option from '$jmap_option'\c"
-    jmap_option="-histo"
-    echo " to '$jmap_option'."
+if [ "$status" != 0 ]; then
+    # usage message doesn't show ':live' option
+
+    if $isWindows; then
+        # If SA isn't present, then jmap gives a different usage message
+        # that doesn't show the ':live' option. However, that's a bug that
+        # is covered by 6971851 so we try using the option just to be sure.
+        # For some reason, this problem has only been seen on OpenJDK6 on
+        # Windows. Not sure why.
+        set +e
+        # Note: Don't copy this code to try probing process 0 on Linux; it
+        # will kill the process group in strange ways.
+        "${JMAP}" "$jmap_option" 0 2>&1 | grep 'Usage' > /dev/null 2>&1
+        status="$?"
+        set -e
+        if [ "$status" = 0 ]; then
+            # Usage message generated so flag the problem.
+            status=1
+        else
+            # No usage message so clear the flag.
+            status=0
+        fi
+    fi
+
+    if [ "$status" != 0 ]; then
+        echo "ERROR: 'jmap $jmap_option' is not supported so this test"
+        echo "ERROR: cannot work reliably. Aborting!"
+        exit 2
+    fi
 fi
 
-"${JAVA}" ${TESTVMOPTS} -classpath "${TESTCLASSES}" \
-    "$TEST_NAME" $seconds > "$TEST_NAME.log" 2>&1 &
-test_pid="$!"
-echo "INFO: starting $TEST_NAME as pid = $test_pid"
+# Start application and use TEST_NAME.port for coordination
+startApplication "$TEST_NAME" "$TEST_NAME.port" $seconds
 
-# wait for test program to get going
-count=0
-while [ "$count" -lt 30 ]; do
-    sleep 2
-    grep_cmd '^INFO: call count = 0$' < "$TEST_NAME.log" > /dev/null 2>&1
-    if [ "$status" = 0 ]; then
-        break
-    fi
-    count=`expr $count + 1`
-done
-
-if [ "$count" -ge 30 ]; then
-    echo "ERROR: $TEST_NAME failed to get going." >&2
-    echo "INFO: killing $test_pid"
-    kill "$test_pid"
-    exit 1
-elif [ "$count" -gt 1 ]; then
-    echo "INFO: $TEST_NAME took $count loops to start."
-fi
-
-if $is_cygwin; then
-    # We need the Windows pid for jmap and not the Cygwin pid.
-    # Note: '\t' works on Cygwin, but doesn't seem to work on Solaris.
-    jmap_pid=`"${JPS}"| grep_cmd "[ \t]$TEST_NAME$" | sed 's/[ \t].*//'`
-    if [ -z "$jmap_pid" ]; then
-        echo "FAIL: jps could not map Cygwin pid to Windows pid." >&2
-        echo "INFO: killing $test_pid"
-        kill "$test_pid"
-        exit 2
-    fi
-    echo "INFO: pid = $test_pid maps to Windows pid = $jmap_pid"
-else
-    jmap_pid="$test_pid"
-fi
+finished_early=false
 
 decreasing_cnt=0
 increasing_cnt=0
 loop_cnt=0
 prev_instance_cnt=0
 
+MAX_JMAP_TRY_CNT=10
+jmap_retry_cnt=0
+loop_cnt_on_retry=0
+
 while true; do
+    # see if the target process has finished its run and bail if it has
+    set +e
+    grep "^INFO: final loop count = " "$appOutput" > /dev/null 2>&1
+    status="$?"
+    set -e
+    if [ "$status" = 0 ]; then
+        break
+    fi
+
     # Output format for 'jmap -histo' in JDK1.5.0:
     #
     #     <#bytes> <#instances> <class_name>
@@ -170,38 +122,70 @@
     #     <num>: <#instances> <#bytes> <class_name>
     #
     set +e
-    "${JMAP}" "$jmap_option" "$jmap_pid" > "$TEST_NAME.jmap" 2>&1
+    "${JMAP}" "$jmap_option" "$appJavaPid" > "$TEST_NAME.jmap" 2>&1
     status="$?"
     set -e
 
     if [ "$status" != 0 ]; then
         echo "INFO: jmap exited with exit code = $status"
-        if [ "$loop_cnt" = 0 ]; then
-            echo "INFO: on the first iteration so no samples were taken."
-            echo "INFO: start of jmap output:"
-            cat "$TEST_NAME.jmap"
-            echo "INFO: end of jmap output."
+
+        # There are intermittent jmap failures; see 6498448.
+        #
+        # So far the following have been observed in a jmap call
+        # that was not in a race with target process termination:
+        #
+        # (Solaris specific, 2nd sample)
+        # <pid>: Unable to open door: target process not responding or HotSpot VM not loaded
+        # The -F option can be used when the target process is not responding
+        #
+        # (on Solaris so far)
+        # java.io.IOException
+        #
+        # (on Solaris so far, 1st sample)
+        # <pid>: Permission denied
+        #
+        sed 's/^/INFO: /' "$TEST_NAME.jmap"
+
+        if [ "$loop_cnt" = "$loop_cnt_on_retry" ]; then
+            # loop count hasn't changed
+            jmap_retry_cnt=`expr $jmap_retry_cnt + 1`
+        else
+            # loop count has changed so remember it
+            jmap_retry_cnt=1
+            loop_cnt_on_retry="$loop_cnt"
+        fi
+
+        # This is '-ge' because we have the original attempt plus
+        # MAX_JMAP_TRY_CNT - 1 retries.
+        if [ "$jmap_retry_cnt" -ge "$MAX_JMAP_TRY_CNT" ]; then
+            echo "INFO: jmap failed $MAX_JMAP_TRY_CNT times in a row" \
+                "without making any progress."
             echo "FAIL: jmap is unable to take any samples." >&2
-            echo "INFO: killing $test_pid"
-            kill "$test_pid"
+            killApplication
             exit 2
         fi
-        echo "INFO: The likely reason is that $TEST_NAME has finished running."
-        break
+
+        # short delay and try again
+        # Note: sleep 1 didn't help with "<pid>: Permission denied"
+        sleep 2
+        echo "INFO: retrying jmap (retry=$jmap_retry_cnt, loop=$loop_cnt)."
+        continue
     fi
 
-    instance_cnt=`grep_cmd "[ 	]$TARGET_CLASS$" \
-        < "$TEST_NAME.jmap" \
+    set +e
+    instance_cnt=`grep "${PATTERN_WS}${TARGET_CLASS}${PATTERN_EOL}" \
+        "$TEST_NAME.jmap" \
         | sed '
             # strip leading whitespace; does nothing in JDK1.5.0
-            s/^[ 	][ 	]*//
+            s/^'"${PATTERN_WS}${PATTERN_WS}"'*//
             # strip <#bytes> in JDK1.5.0; does nothing otherwise
-            s/^[1-9][0-9]*[ 	][ 	]*//
+            s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*//
             # strip <num>: field; does nothing in JDK1.5.0
-            s/^[1-9][0-9]*:[ 	][ 	]*//
+            s/^[1-9][0-9]*:'"${PATTERN_WS}${PATTERN_WS}"'*//
             # strip <class_name> field
-            s/[ 	].*//
+            s/'"${PATTERN_WS}"'.*//
             '`
+    set -e
     if [ -z "$instance_cnt" ]; then
         echo "INFO: instance count is unexpectedly empty"
         if [ "$loop_cnt" = 0 ]; then
@@ -211,8 +195,7 @@
             cat "$TEST_NAME.jmap"
             echo "INFO: end of jmap output."
             echo "FAIL: cannot find the instance count value." >&2
-            echo "INFO: killing $test_pid"
-            kill "$test_pid"
+            killApplication
             exit 2
         fi
     else
@@ -221,7 +204,17 @@
         if [ "$instance_cnt" -gt "$prev_instance_cnt" ]; then
             increasing_cnt=`expr $increasing_cnt + 1`
         else
+            # actually decreasing or the same
             decreasing_cnt=`expr $decreasing_cnt + 1`
+
+            # For these particular WeakReference leaks, the count was
+            # always observed to be increasing so if we get a decreasing
+            # or the same count, then the leaks are fixed in the bits
+            # being tested.
+            echo "INFO: finishing early due to non-increasing instance count."
+            finished_early=true
+            killApplication
+            break
         fi
         prev_instance_cnt="$instance_cnt"
     fi
@@ -232,8 +225,22 @@
     loop_cnt=`expr $loop_cnt + 1`
 done
 
+if [ $finished_early = false ]; then
+    stopApplication "$TEST_NAME.port"
+    waitForApplication
+fi
+
+echo "INFO: $TEST_NAME has finished running."
 echo "INFO: increasing_cnt = $increasing_cnt"
 echo "INFO: decreasing_cnt = $decreasing_cnt"
+if [ "$jmap_retry_cnt" -gt 0 ]; then
+    echo "INFO: jmap_retry_cnt = $jmap_retry_cnt (in $loop_cnt iterations)"
+fi
+
+if [ "$loop_cnt" = 0 ]; then
+    echo "FAIL: jmap is unable to take any samples." >&2
+    exit 2
+fi
 
 echo "INFO: The instance count of" `eval echo $TARGET_CLASS` "objects"
 if [ "$decreasing_cnt" = 0 ]; then
@@ -242,6 +249,6 @@
     exit 2
 fi
 
-echo "INFO: is both increasing and decreasing."
+echo "INFO: is not always increasing."
 echo "PASS: This indicates that there is not a memory leak."
 exit 0
--- a/test/sun/net/ftp/FtpGetContent.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/ftp/FtpGetContent.java	Thu Aug 12 11:23:15 2010 -0700
@@ -391,6 +391,10 @@
             done = true;
         }
 
+        synchronized boolean done() {
+            return done;
+        }
+
         synchronized public void setPortEnabled(boolean ok) {
             portEnabled = ok;
         }
@@ -431,12 +435,13 @@
         public void run() {
             try {
                 Socket client;
-                while (!done) {
+                while (!done()) {
                     client = server.accept();
                     (new FtpServerHandler(client)).start();
                 }
-                server.close();
             } catch(Exception e) {
+            } finally {
+                try { server.close(); } catch (IOException unused) {}
             }
         }
     }
@@ -463,18 +468,13 @@
                 bytesRead = stream.read(buffer);
             }
             stream.close();
-            server.terminate();
-            server.interrupt();
             if (totalBytes != filesize)
                 throw new RuntimeException("wrong file size!");
         } catch (IOException e) {
-            try {
-                server.terminate();
-                server.interrupt();
-            } catch (Exception e2) {
-            }
             throw new RuntimeException(e.getMessage());
+        } finally {
+            server.terminate();
+            server.server.close();
         }
     }
-
 }
--- a/test/sun/net/ftp/FtpURL.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/ftp/FtpURL.java	Thu Aug 12 11:23:15 2010 -0700
@@ -438,8 +438,9 @@
                     client = server.accept();
                     (new FtpServerHandler(client)).run();
                 }
-                server.close();
             } catch(Exception e) {
+            } finally {
+                try { server.close(); } catch (IOException unused) {}
             }
         }
     }
@@ -448,10 +449,9 @@
     }
 
     public FtpURL() throws Exception {
-        FtpServer server = null;
+        FtpServer server = new FtpServer(0);
         BufferedReader in = null;
         try {
-            server = new FtpServer(0);
             server.start();
             int port = server.getPort();
 
@@ -497,17 +497,14 @@
                 throw new RuntimeException("Incorrect filename received");
             if (! "/usr".equals(server.pwd()))
                 throw new RuntimeException("Incorrect pwd received");
-            in.close();
             // We're done!
 
         } catch (Exception e) {
-            try {
-                in.close();
-                server.terminate();
-                server.interrupt();
-            } catch(Exception ex) {
-            }
             throw new RuntimeException("FTP support error: " + e.getMessage());
+        } finally {
+            try { in.close(); } catch (IOException unused) {}
+            server.terminate();
+            server.server.close();
         }
     }
 }
--- a/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -30,9 +30,7 @@
  * @summary ChunkedEncoding unit test; MeteredStream/ProgressData problem
  */
 
-import java.io.*;
 import java.net.*;
-import java.security.*;
 import java.util.BitSet;
 import sun.net.ProgressMeteringPolicy;
 import sun.net.ProgressMonitor;
@@ -42,8 +40,10 @@
 public class ChunkedEncodingWithProgressMonitorTest {
     public static void main (String[] args) throws Exception {
         ProgressMonitor.setMeteringPolicy(new MyProgressMeteringPolicy());
-        ProgressMonitor.getDefault().addProgressListener(new MyProgressListener());
+        ProgressListener listener = new MyProgressListener();
+        ProgressMonitor.getDefault().addProgressListener(listener);
         ChunkedEncodingTest.test();
+        ProgressMonitor.getDefault().removeProgressListener(listener);
 
         if (flag.cardinality() != 3) {
             throw new RuntimeException("All three methods in ProgressListener"+
--- a/test/sun/net/www/http/ChunkedOutputStream/Test.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/ChunkedOutputStream/Test.java	Thu Aug 12 11:23:15 2010 -0700
@@ -34,7 +34,7 @@
 
 public class Test implements HttpHandler {
 
-    static int count = 0;
+    static volatile int count = 0;
 
     static final String str1 = "Helloworld1234567890abcdefghijklmnopqrstuvwxyz"+
                                 "1234567890abcdefkjsdlkjflkjsldkfjlsdkjflkj"+
@@ -46,9 +46,9 @@
     public void handle(HttpExchange exchange) {
         String reqbody;
         try {
-            switch (count) {
-            case 0: /* test1 -- keeps conn alive */
-            case 1: /* test2 -- closes conn */
+            switch (exchange.getRequestURI().toString()) {
+            case "/test/test1": /* test1 -- keeps conn alive */
+            case "/test/test2": /* test2 -- closes conn */
                 printRequestURI(exchange);
                 reqbody = read(exchange.getRequestBody());
                 if (!reqbody.equals(str1)) {
@@ -72,7 +72,7 @@
                     resHeaders.set("Connection", "close");
                 }
                 break;
-            case 2: /* test 3 */
+            case "/test/test3": /* test 3 */
                 printRequestURI(exchange);
                 reqbody = read(exchange.getRequestBody());
 
@@ -93,19 +93,19 @@
                 exchange.sendResponseHeaders(200, reqbody.length());
                 write(exchange.getResponseBody(), reqbody);
                 break;
-            case 3: /* test 4 */
-            case 4: /* test 5 */
+            case "/test/test4": /* test 4 */
+            case "/test/test5": /* test 5 */
                 printRequestURI(exchange);
                 break;
-            case 5: /* test 6 */
+            case "/test/test6": /* test 6 */
                 printRequestURI(exchange);
                 resHeaders = exchange.getResponseHeaders() ;
                 resHeaders.set("Location", "http://foo.bar/");
                 resHeaders.set("Connection", "close");
                 exchange.sendResponseHeaders(307, 0);
                 break;
-            case 6: /* test 7 */
-            case 7: /* test 8 */
+            case "/test/test7": /* test 7 */
+            case "/test/test8": /* test 8 */
                 printRequestURI(exchange);
                 reqbody = read(exchange.getRequestBody());
                 if (reqbody != null && !"".equals(reqbody)) {
@@ -116,7 +116,7 @@
                 resHeaders.set("Connection", "close");
                 exchange.sendResponseHeaders(200, 0);
                 break;
-            case 8: /* test 9 */
+            case "/test/test9": /* test 9 */
                 printRequestURI(exchange);
                 reqbody = read(exchange.getRequestBody());
                 if (!reqbody.equals(str1)) {
@@ -134,7 +134,7 @@
                 exchange.sendResponseHeaders(200, reqbody.length());
                 write(exchange.getResponseBody(), reqbody);
                 break;
-            case 9: /* test10 */
+            case "/test/test10": /* test10 */
                 printRequestURI(exchange);
                 InputStream is = exchange.getRequestBody();
                 String s = read (is, str1.length());
@@ -158,7 +158,7 @@
                     exchange.sendResponseHeaders(200, 0);
                 }
                 break;
-            case 10: /* test11 */
+            case "/test/test11": /* test11 */
                 printRequestURI(exchange);
                 is = exchange.getRequestBody();
                 s = read (is, str1.length());
@@ -182,7 +182,7 @@
                     exchange.sendResponseHeaders(200, 0);
                 }
                 break;
-            case 11: /* test12 */
+            case "/test/test12": /* test12 */
                 printRequestURI(exchange);
                 is = exchange.getRequestBody();
 
@@ -203,8 +203,8 @@
                 }
                 break;
             }
+            count ++;
             exchange.close();
-            count ++;
         } catch (IOException e) {
             e.printStackTrace();
         }
--- a/test/sun/net/www/http/HttpClient/B6726695.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/HttpClient/B6726695.java	Thu Aug 12 11:23:15 2010 -0700
@@ -147,6 +147,8 @@
             serverIgnore(s);
         } catch (IOException e) {
             e.printStackTrace();
+        } finally {
+            try { server.close(); } catch (IOException unused) {}
         }
     }
 
--- a/test/sun/net/www/http/HttpClient/MultiThreadTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/HttpClient/MultiThreadTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -100,11 +100,12 @@
             }
         } catch (Exception e) {
             throw new RuntimeException (e.getMessage());
-        }
-        synchronized (threadlock) {
-            threadCounter --;
-            if (threadCounter == 0) {
-                threadlock.notifyAll();
+        } finally {
+            synchronized (threadlock) {
+                threadCounter --;
+                if (threadCounter == 0) {
+                    threadlock.notifyAll();
+                }
             }
         }
     }
--- a/test/sun/net/www/http/HttpClient/ProxyTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/HttpClient/ProxyTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -47,7 +47,7 @@
     private class HttpProxyServer extends Thread {
         private ServerSocket    server;
         private int port;
-        private boolean done = false;
+        private volatile boolean done = false;
         private String askedUrl;
 
         /**
@@ -125,12 +125,8 @@
             }
         }
 
-        public HttpProxyServer(int port) {
-            this.port = port;
-        }
-
-        public HttpProxyServer() {
-            this(0);
+        public HttpProxyServer() throws IOException {
+            server = new ServerSocket(0);
         }
 
         public int getPort() {
@@ -148,51 +144,49 @@
          */
         synchronized public void terminate() {
             done = true;
+            try { server.close(); } catch (IOException unused) {}
         }
 
         public void run() {
             try {
-                server = new ServerSocket(port);
                 Socket client;
                 while (!done) {
                     client = server.accept();
                     (new HttpProxyHandler(client)).start();
                 }
-                server.close();
             } catch (Exception e) {
+            } finally {
+                try { server.close(); } catch (IOException unused) {}
             }
         }
     }
 
-    public static void main(String[] args) {
+    public static void main(String[] args) throws Exception {
         ProxyTest test = new ProxyTest();
     }
 
-    public ProxyTest() {
+    public ProxyTest() throws Exception {
+        BufferedReader in = null;
         String testURL = "ftp://anonymous:password@myhost.mydomain/index.html";
         HttpProxyServer server = new HttpProxyServer();
         try {
-        server.start();
-        int port = 0;
-        while (port == 0) {
-            Thread.sleep(500);
-            port = server.getPort();
-        }
+            server.start();
+            int port = server.getPort();
 
-        System.setProperty("ftp.proxyHost","localhost");
-        System.setProperty("ftp.proxyPort", String.valueOf(port));
-        URL url = new URL(testURL);
-        InputStream ins = url.openStream();
-        BufferedReader in = new BufferedReader(new InputStreamReader(ins));
-        String line;
-        do {
-            line = in.readLine();
-        } while (line != null);
-        in.close();
-        server.terminate();
-        server.interrupt();
+            Proxy ftpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", port));
+            URL url = new URL(testURL);
+            InputStream ins = (url.openConnection(ftpProxy)).getInputStream();
+            in = new BufferedReader(new InputStreamReader(ins));
+            String line;
+            do {
+                line = in.readLine();
+            } while (line != null);
+            in.close();
         } catch (Exception e) {
             e.printStackTrace();
+        } finally {
+            server.terminate();
+            try { in.close(); } catch (IOException unused) {}
         }
         /*
          * If the URLs don't match, we've got a bug!
--- a/test/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java	Thu Aug 12 11:23:15 2010 -0700
@@ -91,9 +91,10 @@
                 out.flush();
 
                 s.close();
-                server.close();
             } catch (Exception e) {
                 e.printStackTrace();
+            } finally {
+                try { server.close(); } catch (IOException unused) {}
             }
         }
     }
@@ -118,6 +119,8 @@
         if (grp.activeCount() > 0) {
             throw new RuntimeException("Keep-alive thread started in wrong thread group");
         }
+
+        grp.destroy();
     }
 
 }
--- a/test/sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java	Thu Aug 12 11:23:15 2010 -0700
@@ -43,10 +43,6 @@
             srv = s;
         }
 
-        Socket getSocket () {
-            return (s);
-        }
-
         public void run() {
             try {
                 s = srv.accept ();
@@ -57,7 +53,7 @@
                     is.read();
                 }
                 OutputStreamWriter ow =
-                    new OutputStreamWriter(s.getOutputStream());
+                    new OutputStreamWriter((os = s.getOutputStream()));
                 ow.write("HTTP/1.0 200 OK\n");
 
                 // Note: The client expects 10 bytes.
@@ -71,19 +67,16 @@
                 // Note: The (buggy) server only sends 9 bytes.
                 ow.write("123456789");
                 ow.flush();
-                ow.close();
             } catch (Exception e) {
+            } finally {
+                try {if (os != null) { os.close(); }} catch (IOException e) {}
             }
         }
     }
 
-    /*
-     *
-     */
-
-    public static void main (String[] args) {
+    public static void main (String[] args) throws Exception {
+        ServerSocket serversocket = new ServerSocket (0);
         try {
-            ServerSocket serversocket = new ServerSocket (0);
             int port = serversocket.getLocalPort ();
             XServer server = new XServer (serversocket);
             server.start ();
@@ -100,11 +93,12 @@
                 }
             }
             is.close();
-            server.getSocket().close ();
         } catch (IOException e) {
             return;
         } catch (NullPointerException e) {
             throw new RuntimeException (e);
+        } finally {
+            if (serversocket != null) serversocket.close();
         }
     }
 }
--- a/test/sun/net/www/httptest/HttpServer.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/httptest/HttpServer.java	Thu Aug 12 11:23:15 2010 -0700
@@ -188,6 +188,7 @@
                             sock.configureBlocking (false);
                             sock.register (selector, SelectionKey.OP_READ);
                             nconn ++;
+                            System.out.println("SERVER: new connection. chan[" + sock + "]");
                             if (nconn == maxconn) {
                                 /* deregister */
                                 listenerKey.cancel ();
@@ -197,7 +198,9 @@
                             if (key.isReadable()) {
                                 boolean closed;
                                 SocketChannel chan = (SocketChannel) key.channel();
+                                System.out.println("SERVER: connection readable. chan[" + chan + "]");
                                 if (key.attachment() != null) {
+                                    System.out.println("Server: comsume");
                                     closed = consume (chan);
                                 } else {
                                     closed = read (chan, key);
@@ -375,6 +378,7 @@
 
         synchronized void orderlyCloseChannel (SelectionKey key) throws IOException {
             SocketChannel ch = (SocketChannel)key.channel ();
+            System.out.println("SERVER: orderlyCloseChannel chan[" + ch + "]");
             ch.socket().shutdownOutput();
             key.attach (this);
             clist.add (key);
@@ -382,6 +386,8 @@
 
         synchronized void abortiveCloseChannel (SelectionKey key) throws IOException {
             SocketChannel ch = (SocketChannel)key.channel ();
+            System.out.println("SERVER: abortiveCloseChannel chan[" + ch + "]");
+
             Socket s = ch.socket ();
             s.setSoLinger (true, 0);
             ch.close();
--- a/test/sun/net/www/protocol/http/DigestTest.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/net/www/protocol/http/DigestTest.java	Thu Aug 12 11:23:15 2010 -0700
@@ -95,10 +95,11 @@
                 os.write (reply.getBytes());
                 Thread.sleep (2000);
                 s1.close ();
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             System.out.println (e);
             e.printStackTrace();
+        } finally {
+            try { s.close(); } catch (IOException unused) {}
         }
     }
 
@@ -204,15 +205,12 @@
 
 
     public static void main(String[] args) throws Exception {
-        int nLoops = 1;
-        int nSize = 10;
-        int port, n =0;
-        byte b[] = new byte[nSize];
+        int port;
         DigestServer server;
         ServerSocket sock;
 
         try {
-            sock = new ServerSocket (5000);
+            sock = new ServerSocket (0);
             port = sock.getLocalPort ();
         }
         catch (Exception e) {
@@ -225,21 +223,18 @@
         boolean passed = false;
 
         try  {
-
             Authenticator.setDefault (new MyAuthenticator ());
             String s = "http://localhost:" + port + DigestServer.uri;
             URL url = new URL(s);
             java.net.URLConnection conURL =  url.openConnection();
 
             InputStream in = conURL.getInputStream();
-            int c;
-            while ((c = in.read ()) != -1) {
-            }
+            while (in.read () != -1) {}
             in.close ();
-        }
-        catch(ProtocolException e) {
+        } catch(ProtocolException e) {
             passed = true;
         }
+
         if (!passed) {
             throw new RuntimeException ("Expected a ProtocolException from wrong password");
         }
--- a/test/sun/security/krb5/ConfPlusProp.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/security/krb5/ConfPlusProp.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2010, 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
@@ -24,6 +24,7 @@
  * @test
  * @bug 6857795
  * @bug 6858589
+ * @bug 6972005
  * @summary krb5.conf ignored if system properties on realm and kdc are provided
  */
 
@@ -96,7 +97,8 @@
             System.setProperty("java.security.krb5.conf", "i-am-not-a file");
             refresh();
 
-            checkDefaultRealm(null);
+            // Default realm might come from DNS
+            //checkDefaultRealm(null);
             check("R1", null);
             check("R2", null);
             check("R3", null);
--- a/test/sun/security/krb5/confplusprop.conf	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/security/krb5/confplusprop.conf	Thu Aug 12 11:23:15 2010 -0700
@@ -1,6 +1,7 @@
 [libdefaults]
 default_realm = R1
 forwardable = well
+dns_lookup_realm = false
 
 [realms]
 R1 = {
--- a/test/sun/security/krb5/confplusprop2.conf	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/security/krb5/confplusprop2.conf	Thu Aug 12 11:23:15 2010 -0700
@@ -1,3 +1,6 @@
+[libdefaults]
+dns_lookup_realm = false
+
 [realms]
 R1 = {
    kdc = k12
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/util/DerOutputStream/LocaleInTime.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2010, 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
+ * @bug 6670889
+ * @summary Keystore created under Hindi Locale causing ArrayIndexOutOfBoundsException
+ * @run main/othervm -Duser.language=hi -Duser.region=IN LocaleInTime
+ */
+
+import java.util.Date;
+import sun.security.util.DerOutputStream;
+import sun.security.util.DerValue;
+
+public class LocaleInTime {
+    public static void main(String args[]) throws Exception {
+        DerOutputStream out = new DerOutputStream();
+        out.putUTCTime(new Date());
+        DerValue val = new DerValue(out.toByteArray());
+        System.out.println(val.getUTCTime());
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/x509/AlgorithmId/TurkishRegion.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2010, 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
+ * @bug 6867345
+ * @summary Turkish regional options cause NPE in
+ *     sun.security.x509.AlgorithmId.algOID
+ * @run main/othervm -Duser.language=tr -Duser.region=TR TurkishRegion
+ * @author Xuelei Fan
+ */
+
+import sun.security.x509.*;
+
+public class TurkishRegion {
+
+    public static void main(String[] args) throws Exception {
+        AlgorithmId algId = AlgorithmId.get("PBEWITHMD5ANDDES");
+    }
+}
--- a/test/sun/tools/common/ApplicationSetup.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/common/ApplicationSetup.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -24,54 +24,187 @@
 #
 
 
-# Support function to start and stop a given application
+# Support functions to start, stop, wait for or kill a given SimpleApplication
 
-# Starts a given application as background process, usage:
-#   startApplication <class> [args...]
+# Starts a given app as background process, usage:
+#   startApplication <class> port-file [args...]
 #
-# Waits for application to print something to indicate it is running
-# (and initialized). Output is directed to ${TESTCLASSES}/Application.out.
-# Sets $pid to be the process-id of the application.
-
+# The following variables are set:
+#
+# appJavaPid  - application's Java pid
+# appOtherPid - pid associated with the app other than appJavaPid
+# appPidList  - all pids associated with the app
+# appOutput   - file containing stdout and stderr from the app
+#
+# Waits for at least one line of output from the app to indicate
+# that it is up and running.
+#
 startApplication()
 {
-  OUTPUTFILE=${TESTCLASSES}/Application.out
-  ${JAVA} $1 $2 $3 $4 $5 $6 > ${OUTPUTFILE} &
-  pid="$!"
-                                                                                                     
-  # MKS creates an intermediate shell to launch ${JAVA} so
-  # ${pid} is not the actual pid. We have put in a small sleep
-  # to give the intermediate shell process time to launch the
-  # "java" process.
-  if [ "$OS" = "Windows" ]; then
-    sleep 2
-    if [ "${isCygwin}" = "true" ] ; then
-      realpid=`ps -p ${pid} | tail -1 | awk '{print $4;}'`
-    else
-      realpid=`ps -o pid,ppid,comm|grep ${pid}|grep "java"|cut -c1-6`
-    fi
-    pid=${realpid}
-  fi
-                                                                                                     
-  echo "Waiting for Application to initialize..."
-  attempts=0
+  appOutput="${TESTCLASSES}/Application.out"
+
+  ${JAVA} -classpath "${TESTCLASSES}" "$@" > "$appOutput" 2>&1 &
+  appJavaPid="$!"
+  appOtherPid=
+  appPidList="$appJavaPid"
+
+  echo "INFO: waiting for $1 to initialize..."
+  _cnt=0
   while true; do
+    # if the app doesn't start then the JavaTest/JTREG timeout will
+    # kick in so this isn't really a endless loop
     sleep 1
-    out=`tail -1 ${OUTPUTFILE}`
-    if [ ! -z "$out" ]; then
+    out=`tail -1 "$appOutput"`
+    if [ -n "$out" ]; then
+      # we got some output from the app so it's running
       break
     fi
-    attempts=`expr $attempts + 1`
-    echo "Waiting $attempts second(s) ..."
+    _cnt=`expr $_cnt + 1`
+    echo "INFO: waited $_cnt second(s) ..."
   done
+  unset _cnt
 
-  echo "Application is process $pid"
+  if $isWindows; then
+    # Windows requires special handling
+    appOtherPid="$appJavaPid"
+
+    if $isCygwin; then
+      appJavaPid=`ps -p "$appOtherPid" \
+        | sed -n '
+          # See if $appOtherPid is in PID column; there are sometimes
+          # non-blanks in column 1 (I and S observed so far)
+          /^.'"${PATTERN_WS}${PATTERN_WS}*${appOtherPid}${PATTERN_WS}"'/{
+            # strip PID column
+            s/^.'"${PATTERN_WS}${PATTERN_WS}*${appOtherPid}${PATTERN_WS}${PATTERN_WS}"'*//
+            # strip PPID column
+            s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*//
+            # strip PGID column
+            s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*//
+            # strip everything after WINPID column
+            s/'"${PATTERN_WS}"'.*//
+            p
+            q
+          }
+        '`
+      echo "INFO: Cygwin pid=$appOtherPid maps to Windows pid=$appJavaPid"
+    else
+      # show PID, PPID and COMM columns only
+      appJavaPid=`ps -o pid,ppid,comm \
+        | sed -n '
+          # see if appOtherPid is in either PID or PPID columns
+          /'"${PATTERN_WS}${appOtherPid}${PATTERN_WS}"'/{
+            # see if this is a java command
+            /java'"${PATTERN_EOL}"'/{
+              # strip leading white space
+              s/^'"${PATTERN_WS}${PATTERN_WS}"'*//
+              # strip everything after the first word
+              s/'"${PATTERN_WS}"'.*//
+              # print the pid and we are done
+              p
+              q
+            }
+          }
+        '`
+      echo "INFO: MKS shell pid=$appOtherPid; Java pid=$appJavaPid"
+    fi
+
+    if [ -z "$appJavaPid" ]; then
+      echo "ERROR: could not find app's Java pid." >&2
+      killApplication
+      exit 2
+    fi
+    appPidList="$appOtherPid $appJavaPid"
+  fi
+
+  echo "INFO: $1 is process $appJavaPid"
+  echo "INFO: $1 output is in $appOutput"
 }
 
-# Stops an application by invoking the given class and argument, usage:
-#   stopApplication <class> <argument>
+
+# Stops a simple application by invoking ShutdownSimpleApplication
+# class with a specific port-file, usage:
+#   stopApplication port-file
+#
+# Note: When this function returns, the SimpleApplication (or a subclass)
+# may still be running because the application has not yet reached the
+# shutdown check.
+#
 stopApplication()
 {
-  $JAVA -classpath "${TESTCLASSES}" $1 $2
+  $JAVA -classpath "${TESTCLASSES}" ShutdownSimpleApplication $1
 }
 
+
+# Wait for a simple application to stop running.
+#
+waitForApplication() {
+  if [ $isWindows = false ]; then
+    # non-Windows is easy; just one process
+    echo "INFO: waiting for $appJavaPid"
+    set +e
+    wait "$appJavaPid"
+    set -e
+
+  elif $isCygwin; then
+    # Cygwin pid and not the Windows pid
+    echo "INFO: waiting for $appOtherPid"
+    set +e
+    wait "$appOtherPid"
+    set -e
+
+  else # implied isMKS
+    # MKS has intermediate shell and Java process
+    echo "INFO: waiting for $appJavaPid"
+
+    # appJavaPid can be empty if pid search in startApplication() failed
+    if [ -n "$appJavaPid" ]; then
+      # only need to wait for the Java process
+      set +e
+      wait "$appJavaPid"
+      set -e
+    fi
+  fi
+}
+
+
+# Kills a simple application by sending a SIGTERM to the appropriate
+# process(es); on Windows SIGQUIT (-9) is used.
+#
+killApplication()
+{
+  if [ $isWindows = false ]; then
+    # non-Windows is easy; just one process
+    echo "INFO: killing $appJavaPid"
+    set +e
+    kill -TERM "$appJavaPid"  # try a polite SIGTERM first
+    sleep 2
+    # send SIGQUIT (-9) just in case SIGTERM didn't do it
+    # but don't show any complaints
+    kill -QUIT "$appJavaPid" > /dev/null 2>&1
+    wait "$appJavaPid"
+    set -e
+
+  elif $isCygwin; then
+    # Cygwin pid and not the Windows pid
+    echo "INFO: killing $appOtherPid"
+    set +e
+    kill -9 "$appOtherPid"
+    wait "$appOtherPid"
+    set -e
+
+  else # implied isMKS
+    # MKS has intermediate shell and Java process
+    echo "INFO: killing $appPidList"
+    set +e
+    kill -9 $appPidList
+    set -e
+
+    # appJavaPid can be empty if pid search in startApplication() failed
+    if [ -n "$appJavaPid" ]; then
+      # only need to wait for the Java process
+      set +e
+      wait "$appJavaPid"
+      set -e
+    fi
+  fi
+}
--- a/test/sun/tools/common/CommonSetup.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/common/CommonSetup.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -24,56 +24,94 @@
 #
 
 
-# Common setup for tool tests. 
+# Common setup for tool tests and other tests that use jtools.
 # Checks that TESTJAVA, TESTSRC, and TESTCLASSES environment variables are set.
-# Creates the following for use by the tool tests
-#   JAVA     java launcher
-#   JSTACK   jstack utility
-#   JMAP     jmap utility
-#   JINFO    jinfo utility
-#   JHAT     jhat utility
-#   PS       path separator (";" or ":")
-#   OS       operating system 
+#
+# Creates the following constants for use by the caller:
+#   JAVA        - java launcher
+#   JHAT        - jhat utility
+#   JINFO       - jinfo utility
+#   JMAP        - jmap utility
+#   JPS         - jps utility
+#   JSTACK      - jstack utility
+#   OS          - operating system name
+#   PATTERN_EOL - grep or sed end-of-line pattern
+#   PATTERN_WS  - grep or sed whitespace pattern
+#   PS          - path separator (";" or ":")
+#
+# Sets the following variables:
+#
+#   isCygwin  - true if environment is Cygwin
+#   isMKS     - true if environment is MKS
+#   isLinux   - true if OS is Linux
+#   isSolaris - true if OS is Solaris
+#   isWindows - true if OS is Windows
 
 
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+if [ -z "${TESTJAVA}" ]; then
+  echo "ERROR: TESTJAVA not set.  Test cannot execute.  Failed."
   exit 1
 fi
-                                                                                                     
-if [ "${TESTSRC}" = "" ]
-then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
+
+if [ -z "${TESTSRC}" ]; then
+  echo "ERROR: TESTSRC not set.  Test cannot execute.  Failed."
   exit 1
 fi
-                                                                                                     
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+
+if [ -z "${TESTCLASSES}" ]; then
+  echo "ERROR: TESTCLASSES not set.  Test cannot execute.  Failed."
   exit 1
 fi
-                                                                                                     
+
+# only enable these after checking the expected incoming env variables
+set -eu
+
 JAVA="${TESTJAVA}/bin/java"
+JHAT="${TESTJAVA}/bin/jhat"
+JINFO="${TESTJAVA}/bin/jinfo"
+JMAP="${TESTJAVA}/bin/jmap"
+JPS="${TESTJAVA}/bin/jps"
 JSTACK="${TESTJAVA}/bin/jstack"
-JMAP="${TESTJAVA}/bin/jmap"
-JINFO="${TESTJAVA}/bin/jinfo"
-JHAT="${TESTJAVA}/bin/jhat"
+
+isCygwin=false
+isMKS=false
+isLinux=false
+isSolaris=false
+isUnknownOS=false
+isWindows=false
 
 OS=`uname -s`
 
+# start with some UNIX like defaults
+PATTERN_EOL='$'
+# blank and tab
+PATTERN_WS='[ 	]'
+PS=":"
+
 case "$OS" in
+  CYGWIN* )
+    OS="Windows"
+    PATTERN_EOL='[
]*$'
+    # blank and tab
+    PATTERN_WS='[ \t]'
+    isCygwin=true
+    isWindows=true
+    ;;
+  Linux )
+    OS="Linux"
+    isLinux=true
+    ;;
+  SunOS )
+    OS="Solaris"
+    isSolaris=true
+    ;;
   Windows* )
+    OS="Windows"
+    PATTERN_EOL='[
]*$'
     PS=";"
-    OS="Windows"
-    ;;
-  CYGWIN* )
-    PS=";"
-    OS="Windows"
-    isCygwin=true
+    isWindows=true
     ;;
   * )
-    PS=":"
+    isUnknownOS=true
     ;;
 esac
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/tools/common/CommonTests.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,314 @@
+#!/bin/sh
+
+#
+# Copyright (c) 2010, 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
+# @bug 6964018
+# @summary Unit test for common tools infrastructure.
+#
+# @build SimpleApplication SleeperApplication ShutdownSimpleApplication
+# @run shell CommonTests.sh
+
+. ${TESTSRC}/CommonSetup.sh
+. ${TESTSRC}/ApplicationSetup.sh
+
+# hope for the best:
+status=0
+
+
+# Test program path constants from CommonSetup.sh:
+#
+for name in JAVA JHAT JINFO JMAP JPS JSTACK; do
+    eval value=$`echo $name`
+
+    echo "INFO: $name=$value"
+    if [ -x "$value" ]; then
+        echo "INFO: '$value' is executable."
+    else
+        echo "ERROR: '$value' is not executable." >&2
+        status=1
+    fi
+done
+
+
+# Display flag values from CommonSetup.sh:
+#
+for name in isCygwin isMKS isLinux isSolaris isUnknownOS isWindows; do
+    eval value=$`echo $name`
+    echo "INFO: flag $name=$value"
+done
+
+
+# Test OS constant from CommonSetup.sh:
+#
+if [ -z "$OS" ]; then
+    echo "ERROR: OS constant cannot be empty." >&2
+    status=1
+fi
+
+
+# Display the PATTERN_EOL value:
+#
+echo "INFO: PATTERN_EOL="`echo "$PATTERN_EOL" | od -c`
+
+
+# Test PATTERN_EOL with 'grep' for a regular line.
+#
+TESTOUT="${TESTCLASSES}/testout.grep_reg_line_eol"
+set +e
+echo 'regular line' | grep "line${PATTERN_EOL}" > "$TESTOUT"
+set -e
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: PATTERN_EOL works for regular line with grep."
+else
+    echo "ERROR: PATTERN_EOL does not work for regular line with grep." >&2
+    status=1
+fi
+
+
+if $isWindows; then
+    # Test PATTERN_EOL with 'grep' for a CR line.
+    #
+    TESTOUT="${TESTCLASSES}/testout.grep_cr_line_eol"
+    set +e
+    echo 'CR line
' | grep "line${PATTERN_EOL}" > "$TESTOUT"
+    set -e
+    if [ -s "$TESTOUT" ]; then
+        echo "INFO: PATTERN_EOL works for CR line with grep."
+    else
+        echo "ERROR: PATTERN_EOL does not work for CR line with grep." >&2
+        status=1
+    fi
+fi
+
+
+# Test PATTERN_EOL with 'sed' for a regular line.
+#
+TESTOUT="${TESTCLASSES}/testout.sed_reg_line_eol"
+echo 'regular line' | sed -n "/line${PATTERN_EOL}/p" > "$TESTOUT"
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: PATTERN_EOL works for regular line with sed."
+else
+    echo "ERROR: PATTERN_EOL does not work for regular line with sed." >&2
+    status=1
+fi
+
+
+if $isWindows; then
+    # Test PATTERN_EOL with 'sed' for a CR line.
+    #
+    TESTOUT="${TESTCLASSES}/testout.sed_cr_line_eol"
+    echo 'CR line
' | sed -n "/line${PATTERN_EOL}/p" > "$TESTOUT"
+    if [ -s "$TESTOUT" ]; then
+        echo "INFO: PATTERN_EOL works for CR line with sed."
+    else
+        echo "ERROR: PATTERN_EOL does not work for CR line with sed." >&2
+        status=1
+    fi
+fi
+
+
+# Display the PATTERN_WS value:
+#
+echo "INFO: PATTERN_WS="`echo "$PATTERN_WS" | od -c`
+
+
+# Test PATTERN_WS with 'grep' for a blank.
+#
+TESTOUT="${TESTCLASSES}/testout.grep_blank"
+set +e
+echo 'blank: ' | grep "$PATTERN_WS" > "$TESTOUT"
+set -e
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: PATTERN_WS works for blanks with grep."
+else
+    echo "ERROR: PATTERN_WS does not work for blanks with grep." >&2
+    status=1
+fi
+
+
+# Test PATTERN_WS with 'grep' for a tab.
+#
+TESTOUT="${TESTCLASSES}/testout.grep_tab"
+set +e
+echo 'tab:	' | grep "$PATTERN_WS" > "$TESTOUT"
+set -e
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: PATTERN_WS works for tabs with grep."
+else
+    echo "ERROR: PATTERN_WS does not work for tabs with grep." >&2
+    status=1
+fi
+
+
+# Test PATTERN_WS with 'sed' for a blank.
+#
+TESTOUT="${TESTCLASSES}/testout.sed_blank"
+echo 'blank: ' | sed -n "/$PATTERN_WS/p" > "$TESTOUT"
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: PATTERN_WS works for blanks with sed."
+else
+    echo "ERROR: PATTERN_WS does not work for blanks with sed." >&2
+    status=1
+fi
+
+
+# Test PATTERN_WS with 'sed' for a tab.
+#
+TESTOUT="${TESTCLASSES}/testout.sed_tab"
+echo 'tab:	' | sed -n "/$PATTERN_WS/p" > "$TESTOUT"
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: PATTERN_WS works for tabs with sed."
+else
+    echo "ERROR: PATTERN_WS does not work for tabs with sed." >&2
+    status=1
+fi
+
+
+# Test startApplication and use PORTFILE for coordination
+# The app sleeps for 30 seconds.
+#
+PORTFILE="${TESTCLASSES}"/shutdown.port
+startApplication SleeperApplication "${PORTFILE}" 30
+
+
+# Test appJavaPid in "ps" cmd output.
+#
+TESTOUT="${TESTCLASSES}/testout.ps_app"
+set +e
+if $isCygwin; then
+    # On Cygwin, appJavaPid is the Windows pid for the Java process
+    # and appOtherPid is the Cygwin pid for the Java process.
+    ps -p "$appOtherPid" \
+        | grep "${PATTERN_WS}${appJavaPid}${PATTERN_WS}" > "$TESTOUT"
+else
+    # output only pid and comm columns to avoid mismatches
+    ps -eo pid,comm \
+        | grep "^${PATTERN_WS}*${appJavaPid}${PATTERN_WS}" > "$TESTOUT"
+fi
+set -e
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: begin appJavaPid=$appJavaPid in 'ps' cmd output:"
+    cat "$TESTOUT"
+    echo "INFO: end appJavaPid=$appJavaPid in 'ps' cmd output."
+else
+    echo "ERROR: 'ps' cmd should show appJavaPid=$appJavaPid." >&2
+    status=1
+fi
+
+if [ -n "$appOtherPid" ]; then
+    # Test appOtherPid in "ps" cmd output, if we have one.
+    #
+    TESTOUT="${TESTCLASSES}/testout.ps_other"
+    set +e
+    if $isCygwin; then
+        ps -p "$appOtherPid" \
+            | grep "${PATTERN_WS}${appOtherPid}${PATTERN_WS}" > "$TESTOUT"
+    else
+        # output only pid and comm columns to avoid mismatches
+        ps -eo pid,comm \
+            | grep "^${PATTERN_WS}*${appOtherPid}${PATTERN_WS}" > "$TESTOUT"
+    fi
+    set -e
+    if [ -s "$TESTOUT" ]; then
+        echo "INFO: begin appOtherPid=$appOtherPid in 'ps' cmd output:"
+        cat "$TESTOUT"
+        echo "INFO: end appOtherPid=$appOtherPid in 'ps' cmd output."
+    else
+        echo "ERROR: 'ps' cmd should show appOtherPid=$appOtherPid." >&2
+        status=1
+    fi
+fi
+
+
+# Test stopApplication and PORTFILE for coordination
+#
+stopApplication "${PORTFILE}"
+
+
+# Test application still running after stopApplication.
+#
+# stopApplication just lets the app know that it can stop, but the
+# app might still be doing work. This test just demonstrates that
+# fact and doesn't fail if the app is already done.
+#
+TESTOUT="${TESTCLASSES}/testout.after_stop"
+set +e
+if $isCygwin; then
+    # On Cygwin, appJavaPid is the Windows pid for the Java process
+    # and appOtherPid is the Cygwin pid for the Java process.
+    ps -p "$appOtherPid" \
+        | grep "${PATTERN_WS}${appJavaPid}${PATTERN_WS}" > "$TESTOUT"
+else
+    # output only pid and comm columns to avoid mismatches
+    ps -eo pid,comm \
+        | grep "^${PATTERN_WS}*${appJavaPid}${PATTERN_WS}" > "$TESTOUT"
+fi
+set -e
+if [ -s "$TESTOUT" ]; then
+    echo "INFO: it is okay for appJavaPid=$appJavaPid to still be running" \
+        "after stopApplication() is called."
+    echo "INFO: begin 'after_stop' output:"
+    cat "$TESTOUT"
+    echo "INFO: end 'after_stop' output."
+fi
+
+
+# Test waitForApplication
+#
+# The app might already be gone so this function shouldn't generate
+# a fatal error in either call.
+#
+waitForApplication
+
+if [ $isWindows = false ]; then
+    # Windows can recycle pids quickly so we can't use this test there
+    TESTOUT="${TESTCLASSES}/testout.after_kill"
+    set +e
+    # output only pid and comm columns to avoid mismatches
+    ps -eo pid,comm \
+        | grep "^${PATTERN_WS}*${appJavaPid}${PATTERN_WS}" > "$TESTOUT"
+    set -e
+    if [ -s "$TESTOUT" ]; then
+        echo "ERROR: 'ps' cmd should not show appJavaPid." >&2
+        echo "ERROR: begin 'after_kill' output:" >&2
+        cat "$TESTOUT" >&2
+        echo "ERROR: end 'after_kill' output." >&2
+        status=1
+    else
+        echo "INFO: 'ps' cmd does not show appJavaPid after" \
+            "waitForApplication() is called."
+    fi
+fi
+
+
+# Test killApplication
+#
+# The app is already be gone so this function shouldn't generate
+# a fatal error.
+#
+killApplication
+
+exit $status
--- a/test/sun/tools/common/ShutdownSimpleApplication.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/common/ShutdownSimpleApplication.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, 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
@@ -22,10 +22,13 @@
  */
 
 /*
+ * Used to shutdown SimpleApplication (or a subclass). The argument to
+ * this class is the name of a file that contains the TCP port number
+ * on which SimpleApplication (or a subclass) is listening.
  *
- *
- * Used to shutdown SimpleApplication. The argument to this class is
- * the TCP port number where SimpleApplication is listening.
+ * Note: When this program returns, the SimpleApplication (or a subclass)
+ * may still be running because the application has not yet reached the
+ * shutdown check.
  */
 import java.net.Socket;
 import java.net.InetSocketAddress;
@@ -35,6 +38,11 @@
 public class ShutdownSimpleApplication {
     public static void main(String args[]) throws Exception {
 
+        if (args.length != 1) {
+            throw new RuntimeException("Usage: ShutdownSimpleApplication" +
+                " port-file");
+        }
+
         // read the (TCP) port number from the given file
 
         File f = new File(args[0]);
@@ -42,21 +50,27 @@
         byte b[] = new byte[8];
         int n = fis.read(b);
         if (n < 1) {
-            throw new RuntimeException("Empty file");
+            throw new RuntimeException("Empty port-file");
         }
         fis.close();
 
         String str = new String(b, 0, n, "UTF-8");
-        System.out.println("Port number of application is: " + str);
+        System.out.println("INFO: Port number of SimpleApplication: " + str);
         int port = Integer.parseInt(str);
 
         // Now connect to the port (which will shutdown application)
 
-        System.out.println("Connecting to port " + port +
-            " to shutdown Application ...");
+        System.out.println("INFO: Connecting to port " + port +
+            " to shutdown SimpleApplication ...");
+        System.out.flush();
 
         Socket s = new Socket();
         s.connect( new InetSocketAddress(port) );
         s.close();
+
+        System.out.println("INFO: done connecting to SimpleApplication.");
+        System.out.flush();
+
+        System.exit(0);
     }
 }
--- a/test/sun/tools/common/SimpleApplication.java	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/common/SimpleApplication.java	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, 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
@@ -22,10 +22,12 @@
  */
 
 /*
+ * A simple application used by unit tests. The first argument to this
+ * class is the name of a file to which a TCP port number can be written.
  *
- *
- * A simple application used for tool unit tests. It does nothing else
- * bind to a TCP port and wait for a shutdown message.
+ * By default, this class does nothing other than bind to a TCP port,
+ * write the TCP port number to a file, and wait for an incoming connection
+ * in order to complete the application shutdown protocol.
  */
 import java.net.Socket;
 import java.net.ServerSocket;
@@ -33,25 +35,86 @@
 import java.io.FileOutputStream;
 
 public class SimpleApplication {
-    public static void main(String args[]) throws Exception {
+    private static SimpleApplication myApp;      // simple app or a subclass
+    private static String            myAppName;  // simple app name
+    private static int               myPort;     // coordination port #
+    private static ServerSocket      mySS;       // coordination socket
+
+    // protected so a subclass can extend it; not public so creation is
+    // limited.
+    protected SimpleApplication() {
+        // save simple app (or subclass) name for messages
+        myAppName = getClass().getName();
+    }
+
+    // return the simple application (or a subclass)
+    final public static SimpleApplication getMyApp() {
+        return myApp;
+    }
+
+    // set the simple application (for use by a subclass)
+    final public static void setMyApp(SimpleApplication _myApp) {
+        myApp = _myApp;
+    }
+
+    // execute the application finish protocol
+    final public void doMyAppFinish(String[] args) throws Exception {
+        System.out.println("INFO: " + myAppName + " is waiting on port: " +
+            myPort);
+        System.out.flush();
+
+        // wait for test harness to connect
+        Socket s = mySS.accept();
+        s.close();
+        mySS.close();
+
+        System.out.println("INFO: " + myAppName + " is shutting down.");
+        System.out.flush();
+    }
+
+    // execute the application start protocol
+    final public void doMyAppStart(String[] args) throws Exception {
+        if (args.length < 1) {
+            throw new RuntimeException("Usage: " + myAppName +
+                " port-file [arg(s)]");
+        }
+
         // bind to a random port
-        ServerSocket ss = new ServerSocket(0);
-        int port = ss.getLocalPort();
+        mySS = new ServerSocket(0);
+        myPort = mySS.getLocalPort();
 
         // Write the port number to the given file
         File f = new File(args[0]);
         FileOutputStream fos = new FileOutputStream(f);
-        fos.write( Integer.toString(port).getBytes("UTF-8") );
+        fos.write( Integer.toString(myPort).getBytes("UTF-8") );
         fos.close();
 
-        System.out.println("Application waiting on port: " + port);
+        System.out.println("INFO: " + myAppName + " created socket on port: " +
+            myPort);
+        System.out.flush();
+    }
+
+    // execute the app work (subclass can override this)
+    public void doMyAppWork(String[] args) throws Exception {
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (myApp == null) {
+            // create myApp since a subclass hasn't done so
+            myApp = new SimpleApplication();
+        }
+
+        myApp.doMyAppStart(args);   // do the app start protocol
+
+        System.out.println("INFO: " + myAppName + " is calling doMyAppWork()");
+        System.out.flush();
+        myApp.doMyAppWork(args);    // do the app work
+        System.out.println("INFO: " + myAppName + " returned from" +
+            " doMyAppWork()");
         System.out.flush();
 
-        // wait for test harness to connect
-        Socket s = ss.accept();
-        s.close();
-        ss.close();
+        myApp.doMyAppFinish(args);  // do the app finish protocol
 
-        System.out.println("Application shutdown.");
+        System.exit(0);
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/tools/common/SleeperApplication.java	Thu Aug 12 11:23:15 2010 -0700
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2010, 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.
+ */
+
+/*
+ * An example subclass of SimpleApplication that illustrates how to
+ * override the doMyAppWork() method.
+ */
+
+public class SleeperApplication extends SimpleApplication {
+    public static int DEFAULT_SLEEP_TIME = 60;  // time is in seconds
+
+    // execute the sleeper app work
+    public void doMyAppWork(String[] args) throws Exception {
+        int sleep_time = DEFAULT_SLEEP_TIME;
+
+        // args[0] is the port-file
+        if (args.length < 2) {
+            System.out.println("INFO: using default sleep time of "
+                + sleep_time + " seconds.");
+        } else {
+            try {
+                sleep_time = Integer.parseInt(args[1]);
+            } catch (NumberFormatException nfe) {
+                throw new RuntimeException("Error: '" + args[1] +
+                    "': is not a valid seconds value.");
+            }
+        }
+
+        Thread.sleep(sleep_time * 1000);  // our "work" is to sleep
+    }
+
+    public static void main(String[] args) throws Exception {
+        SleeperApplication myApp = new SleeperApplication();
+
+        SimpleApplication.setMyApp(myApp);
+
+        SimpleApplication.main(args);
+    }
+}
--- a/test/sun/tools/jhat/ParseTest.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jhat/ParseTest.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2010, 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
@@ -32,7 +32,11 @@
 # @run shell ParseTest.sh
 
 . ${TESTSRC}/../common/CommonSetup.sh
-. ${TESTSRC}/../common/ApplicationSetup.sh
+
+# all return statuses are checked in this test
+set +e
+
+failed=0
 
 DUMPFILE="minimal.bin"
 
--- a/test/sun/tools/jinfo/Basic.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jinfo/Basic.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2010, 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
@@ -35,53 +35,57 @@
 . ${TESTSRC}/../common/CommonSetup.sh
 . ${TESTSRC}/../common/ApplicationSetup.sh
 
-# Start application (send output to shutdown.port)
+# Start application and use PORTFILE for coordination
 PORTFILE="${TESTCLASSES}"/shutdown.port
-startApplication \
-    -classpath "${TESTCLASSES}" SimpleApplication "${PORTFILE}"
+startApplication SimpleApplication "${PORTFILE}"
+
+# all return statuses are checked in this test
+set +e
 
 failed=0
 
-if [ "$OS" != "Windows" ]; then
+if [ $isWindows = false ]; then
     # -sysprops option
-    ${JINFO} -sysprops $pid
+    ${JINFO} -sysprops $appJavaPid
     if [ $? != 0 ]; then failed=1; fi
 
     # -flags option
-    ${JINFO} -flags $pid
+    ${JINFO} -flags $appJavaPid
     if [ $? != 0 ]; then failed=1; fi
 
     # no option
-    ${JINFO} $pid
+    ${JINFO} $appJavaPid
     if [ $? != 0 ]; then failed=1; fi
 
 fi
 
 
 # -flag option
-${JINFO} -flag +PrintGC $pid
+${JINFO} -flag +PrintGC $appJavaPid
 if [ $? != 0 ]; then failed=1; fi 
 
-${JINFO} -flag -PrintGC $pid
+${JINFO} -flag -PrintGC $appJavaPid
 if [ $? != 0 ]; then failed=1; fi
 
-${JINFO} -flag PrintGC $pid
+${JINFO} -flag PrintGC $appJavaPid
 if [ $? != 0 ]; then failed=1; fi
 
-if [ "$OS" = "SunOS" ]; then
+if $isSolaris; then
 
-    ${JINFO} -flag +ExtendedDTraceProbes $pid
+    ${JINFO} -flag +ExtendedDTraceProbes $appJavaPid
     if [ $? != 0 ]; then failed=1; fi
 
-    ${JINFO} -flag -ExtendedDTraceProbes $pid
+    ${JINFO} -flag -ExtendedDTraceProbes $appJavaPid
     if [ $? != 0 ]; then failed=1; fi
 
-    ${JINFO} -flag ExtendedDTraceProbes $pid
+    ${JINFO} -flag ExtendedDTraceProbes $appJavaPid
     if [ $? != 0 ]; then failed=1; fi
 
 fi
 
-stopApplication ShutdownSimpleApplication "${PORTFILE}"
+set -e
+
+stopApplication "${PORTFILE}"
+waitForApplication
 
 exit $failed
-
--- a/test/sun/tools/jmap/Basic.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jmap/Basic.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -35,24 +35,25 @@
 . ${TESTSRC}/../common/CommonSetup.sh
 . ${TESTSRC}/../common/ApplicationSetup.sh
 
-# Start application (send output to shutdown.port)
+# Start application and use PORTFILE for coordination
 PORTFILE="${TESTCLASSES}"/shutdown.port
-startApplication \
-    -classpath "${TESTCLASSES}" SimpleApplication "${PORTFILE}"
+startApplication SimpleApplication "${PORTFILE}"
+
+# all return statuses are checked in this test
+set +e
 
 failed=0
 
 # -histo[:live] option
-${JMAP} -histo $pid
+${JMAP} -histo $appJavaPid
 if [ $? != 0 ]; then failed=1; fi
 
-${JMAP} -histo:live $pid
+${JMAP} -histo:live $appJavaPid
 if [ $? != 0 ]; then failed=1; fi
 
 # -dump option
-p=`expr $pid`
-DUMPFILE="java_pid${p}.hprof"
-${JMAP} -dump:format=b,file=${DUMPFILE} $pid
+DUMPFILE="java_pid${appJavaPid}.hprof"
+${JMAP} -dump:format=b,file=${DUMPFILE} $appJavaPid
 if [ $? != 0 ]; then failed=1; fi
 
 # check that heap dump is parsable
@@ -63,7 +64,7 @@
 rm ${DUMPFILE}
 
 # -dump:live option
-${JMAP} -dump:live,format=b,file=${DUMPFILE} $pid
+${JMAP} -dump:live,format=b,file=${DUMPFILE} $appJavaPid
 if [ $? != 0 ]; then failed=1; fi
 
 # check that heap dump is parsable
@@ -71,9 +72,11 @@
 if [ $? != 0 ]; then failed=1; fi
 
 # dump file is large so remove it
-rm ${DUMPFILE}
+rm -f ${DUMPFILE}
 
-stopApplication ShutdownSimpleApplication "${PORTFILE}"
+set -e
+
+stopApplication "${PORTFILE}"
+waitForApplication
 
 exit $failed
-
--- a/test/sun/tools/jrunscript/common.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jrunscript/common.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -43,10 +43,20 @@
     Windows_*)
         PS=";"
         FS="\\"
+        # MKS diff deals with trailing CRs automatically
+        golden_diff="diff"
+        ;;
+    CYGWIN*)
+        PS=":"
+        FS="/"
+        # Cygwin diff needs to be told to ignore trailing CRs
+        golden_diff="diff --strip-trailing-cr"
         ;;
     *)
         PS=":"
         FS="/"
+        # Assume any other platform doesn't have the trailing CR stuff
+        golden_diff="diff"
         ;;
     esac
 
--- a/test/sun/tools/jrunscript/jrunscript-eTest.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jrunscript/jrunscript-eTest.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -42,7 +42,7 @@
 rm -f jrunscript-eTest.out 2>/dev/null
 ${JRUNSCRIPT} -e "println('hello')" > jrunscript-eTest.out 2>&1
 
-diff jrunscript-eTest.out ${TESTSRC}/dash-e.out
+$golden_diff jrunscript-eTest.out ${TESTSRC}/dash-e.out
 if [ $? != 0 ]
 then
   echo "Output of jrunscript -e differ from expected output. Failed."
@@ -55,7 +55,7 @@
 rm -f jrunscript-eTest.out 2>/dev/null
 ${JRUNSCRIPT} -l js -e "println('hello')" > jrunscript-eTest.out 2>&1
 
-diff jrunscript-eTest.out ${TESTSRC}/dash-e.out
+$golden_diff jrunscript-eTest.out ${TESTSRC}/dash-e.out
 if [ $? != 0 ]
 then
   echo "Output of jrunscript -e differ from expected output. Failed."
--- a/test/sun/tools/jrunscript/jrunscript-fTest.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jrunscript/jrunscript-fTest.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -42,7 +42,7 @@
 rm -f jrunscript-fTest.out 2>/dev/null
 ${JRUNSCRIPT} -f ${TESTSRC}/hello.js > jrunscript-fTest.out 2>&1
 
-diff jrunscript-fTest.out ${TESTSRC}/dash-f.out
+$golden_diff jrunscript-fTest.out ${TESTSRC}/dash-f.out
 if [ $? != 0 ]
 then
   echo "Output of jrunscript -f differ from expected output. Failed."
@@ -56,7 +56,7 @@
 rm -f jrunscript-fTest.out 2>/dev/null
 ${JRUNSCRIPT} -l js -f ${TESTSRC}/hello.js > jrunscript-fTest.out 2>&1
 
-diff jrunscript-fTest.out ${TESTSRC}/dash-f.out
+$golden_diff jrunscript-fTest.out ${TESTSRC}/dash-f.out
 if [ $? != 0 ]
 then
   echo "Output of jrunscript -f differ from expected output. Failed."
--- a/test/sun/tools/jrunscript/jrunscriptTest.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jrunscript/jrunscriptTest.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -49,7 +49,7 @@
 new java.lang.Runnable() { run: function() { println('I am runnable'); }}.run();
 EOF
 
-diff jrunscriptTest.out ${TESTSRC}/repl.out
+$golden_diff jrunscriptTest.out ${TESTSRC}/repl.out
 if [ $? != 0 ]
 then
   echo "Output of jrunscript session differ from expected output. Failed."
@@ -67,7 +67,7 @@
 new java.lang.Runnable() { run: function() { println('I am runnable'); }}.run();
 EOF
 
-diff jrunscriptTest.out ${TESTSRC}/repl.out
+$golden_diff jrunscriptTest.out ${TESTSRC}/repl.out
 if [ $? != 0 ]
 then
   echo "Output of jrunscript -l js differ from expected output. Failed."
--- a/test/sun/tools/jstack/Basic.sh	Tue Aug 10 19:29:30 2010 +0400
+++ b/test/sun/tools/jstack/Basic.sh	Thu Aug 12 11:23:15 2010 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2010, 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
@@ -35,22 +35,26 @@
 . ${TESTSRC}/../common/CommonSetup.sh
 . ${TESTSRC}/../common/ApplicationSetup.sh
 
-# Start application (send output to shutdown.port)
+# Start application and use PORTFILE for coordination
 PORTFILE="${TESTCLASSES}"/shutdown.port
-startApplication \
-    -classpath "${TESTCLASSES}" SimpleApplication "${PORTFILE}"
+startApplication SimpleApplication "${PORTFILE}"
+
+# all return statuses are checked in this test
+set +e
 
 failed=0
 
 # normal
-$JSTACK $pid 2>&1
+$JSTACK $appJavaPid 2>&1
 if [ $? != 0 ]; then failed=1; fi
 
 # long
-$JSTACK -l $pid 2>&1
+$JSTACK -l $appJavaPid 2>&1
 if [ $? != 0 ]; then failed=1; fi
 
-stopApplication ShutdownSimpleApplication "${PORTFILE}"
+set -e
+
+stopApplication "${PORTFILE}"
+waitForApplication
  
 exit $failed
-