changeset 206:4a06c0b6fdef

Merge
author yan
date Fri, 28 Mar 2008 03:06:00 -0700
parents 6e2a17c648a4 0f955581dc0b
children ada64880c5d0
files
diffstat 328 files changed, 13301 insertions(+), 6343 deletions(-) [+]
line wrap: on
line diff
--- a/make/common/Defs-linux.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/Defs-linux.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -50,13 +50,13 @@
 CC_DEPEND_FILTER = $(SED) -e 's!$*\.$(OBJECT_SUFFIX)!$(dir $@)& $(dir $@)$*.$(DEPEND_SUFFIX)!g'
 
 ifndef PLATFORM_SRC
-  PLATFORM_SRC = $(JDK_TOPDIR)/src/solaris
+  PLATFORM_SRC = $(BUILDDIR)/../src/solaris
 endif # PLATFORM_SRC
 
 # Platform specific closed sources
 ifndef OPENJDK
   ifndef CLOSED_PLATFORM_SRC
-    CLOSED_PLATFORM_SRC = $(JDK_TOPDIR)/src/closed/solaris
+    CLOSED_PLATFORM_SRC = $(BUILDDIR)/../src/closed/solaris
   endif
 endif
 
--- a/make/common/Defs-solaris.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/Defs-solaris.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -45,13 +45,13 @@
 include $(JDK_MAKE_SHARED_DIR)/Defs.gmk
 
 ifndef PLATFORM_SRC
-PLATFORM_SRC = $(JDK_TOPDIR)/src/solaris
+PLATFORM_SRC = $(BUILDDIR)/../src/solaris
 endif # PLATFORM_SRC
 
 # Platform specific closed sources
 ifndef OPENJDK
   ifndef CLOSED_PLATFORM_SRC
-    CLOSED_PLATFORM_SRC = $(JDK_TOPDIR)/src/closed/solaris
+    CLOSED_PLATFORM_SRC = $(BUILDDIR)/../src/closed/solaris
   endif
 endif
 
--- a/make/common/Defs-windows.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/Defs-windows.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -51,13 +51,13 @@
 endif # LIB_LOCATION
 
 ifndef PLATFORM_SRC
-  PLATFORM_SRC  = $(JDK_TOPDIR)/src/windows
+  PLATFORM_SRC  = $(BUILDDIR)/../src/windows
 endif # PLATFORM_SRC
 
 # Platform specific closed sources
 ifndef OPENJDK
   ifndef CLOSED_PLATFORM_SRC
-    CLOSED_PLATFORM_SRC  = $(JDK_TOPDIR)/src/closed/windows
+    CLOSED_PLATFORM_SRC  = $(BUILDDIR)/../src/closed/windows
   endif
 endif
 
@@ -367,7 +367,7 @@
 endif
 
 # Settings for the VERSIONINFO tap on windows. 
-VERSIONINFO_RESOURCE = $(JDK_TOPDIR)/src/windows/resource/version.rc
+VERSIONINFO_RESOURCE = $(BUILDDIR)/../src/windows/resource/version.rc
 
 ifneq ($(JDK_BUILD_NUMBER),)
  COOKED_BUILD_NUMBER = $(shell $(ECHO) $(JDK_BUILD_NUMBER) | $(SED) -e 's/^b//' -e 's/^0//')
--- a/make/common/Defs.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/Defs.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -41,7 +41,15 @@
 SUN_MAKE_TEST:sh = echo "ERROR: PLEASE USE GNU VERSION OF MAKE"; exit 33
 
 ifndef JDK_TOPDIR
-  JDK_TOPDIR=$(BUILDDIR)/..
+  ifdef BUILDDIR
+    JDK_TOPDIR=$(BUILDDIR)/..
+  else
+    JDK_TOPDIR:=$(error "ERROR: Cannot define top of jdk repository")
+  endif
+endif
+ifndef BUILDDIR
+  # Hack, due to deploy repository using this file.
+  BUILDDIR=$(JDK_TOPDIR)/make
 endif
 ifndef JDK_MAKE_SHARED_DIR
   JDK_MAKE_SHARED_DIR=$(JDK_TOPDIR)/make/common/shared
@@ -59,13 +67,13 @@
 # there yet.
 #
 ifndef SHARE_SRC
-  SHARE_SRC    = $(JDK_TOPDIR)/src/share
+  SHARE_SRC    = $(BUILDDIR)/../src/share
 endif
 
 # Files that cannot be included in the OpenJDK distribution are
 # collected under a parent directory which contains just those files.
 ifndef CLOSED_SRC
-  CLOSED_SRC  = $(JDK_TOPDIR)/src/closed
+  CLOSED_SRC  = $(BUILDDIR)/../src/closed
 endif
 
 # If we have no closed directory, force it to an openjdk build
@@ -170,14 +178,6 @@
   endif
 endif # OPENJDK
 
-# Default output directory
-ifdef OPENJDK
-_OUTPUTDIR=$(JDK_TOPDIR)/build/$(PLATFORM)-$(ARCH)$(OPENJDK_SUFFIX)
-else
-_OUTPUTDIR=$(JDK_TOPDIR)/build/$(PLATFORM)-$(ARCH)
-endif
-
-
 #
 # Get platform definitions
 #
--- a/make/common/shared/Defs-control.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/shared/Defs-control.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -36,7 +36,7 @@
 endif
 
 ifndef CONTROL_TOPDIR
-  CONTROL_TOPDIR=$(TOPDIR)/control
+  CONTROL_TOPDIR=$(TOPDIR)
 endif
 ifndef HOTSPOT_TOPDIR
   HOTSPOT_TOPDIR=$(TOPDIR)/hotspot
@@ -70,7 +70,8 @@
 include $(JDK_MAKE_SHARED_DIR)/Platform.gmk
 
 # Default output directory
-_OUTPUTDIR=$(CONTROL_TOPDIR)/build/$(PLATFORM)-$(ARCH)
+BUILD_PARENT_DIRECTORY=$(TOPDIR)
+_OUTPUTDIR=$(TOPDIR)/build/$(PLATFORM)-$(ARCH)
 
 # Get platform specific settings
 include $(JDK_MAKE_SHARED_DIR)/Defs.gmk
--- a/make/common/shared/Defs.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/shared/Defs.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -55,7 +55,10 @@
 
 # Simple pwd path
 define PwdPath
-$(shell cd $1 2> $(DEV_NULL) && pwd)
+$(shell $(CD) $1 2> $(DEV_NULL) && $(PWD))
+endef
+define AbsPwdPathCheck
+$(shell $(CD) .. 2> $(DEV_NULL) && $(CD) $1 2> $(DEV_NULL) && $(PWD))
 endef
 
 # Checks an ALT value for spaces (should be one word), 
@@ -422,23 +425,54 @@
 CACERTS_FILE:=$(call AltCheckValue,CACERTS_FILE)
 
 # OUTPUTDIR: Location of all output for the build
-_BACKUP_OUTPUTDIR = $(TEMP_DISK)/$(USER)/jdk-outputdir
 ifdef ALT_OUTPUTDIR
-  _POSSIBLE_OUTPUTDIR =$(subst \,/,$(ALT_OUTPUTDIR))
+  OUTPUTDIR:=$(subst \,/,$(ALT_OUTPUTDIR))
+  # Assumes this is absolute (checks later)
+  ABS_OUTPUTDIR:=$(OUTPUTDIR)
 else
   ifndef _OUTPUTDIR
-    _OUTPUTDIR = $(_BACKUP_OUTPUTDIR)
+    # Default:  Get "build" parent directory, which should always exist
+    ifndef BUILD_PARENT_DIRECTORY
+      BUILD_PARENT_DIRECTORY=$(BUILDDIR)/..
+    endif
+    ABS_BUILD_PARENT_DIRECTORY:=$(call FullPath,$(BUILD_PARENT_DIRECTORY))
+    ifdef OPENJDK
+      _OUTPUTDIRNAME=$(PLATFORM)-$(ARCH)$(OPENJDK_SUFFIX)
+    else
+      _OUTPUTDIRNAME=$(PLATFORM)-$(ARCH)
+    endif
+    _OUTPUTDIR=$(BUILD_PARENT_DIRECTORY)/build/$(_OUTPUTDIRNAME)
+    ABS_OUTPUTDIR:=$(ABS_BUILD_PARENT_DIRECTORY)/build/$(_OUTPUTDIRNAME)
   endif
-  _POSSIBLE_OUTPUTDIR =$(_OUTPUTDIR)
+  OUTPUTDIR:=$(_OUTPUTDIR)
 endif
-_create_outputdir1:=$(shell mkdir -p $(_POSSIBLE_OUTPUTDIR) > $(DEV_NULL) 2>&1)
-OUTPUTDIR:=$(call WriteDirExists,$(_POSSIBLE_OUTPUTDIR),$(_BACKUP_OUTPUTDIR))
-_create_outputdir2:=$(shell mkdir -p $(OUTPUTDIR) > $(DEV_NULL) 2>&1)
-ifeq "$(OUTPUTDIR)" "$(_BACKUP_OUTPUTDIR)"
-  _outputdir_warning:=$(warning "WARNING: OUTPUTDIR '$(_POSSIBLE_OUTPUTDIR)' not writable, will use '$(_BACKUP_OUTPUTDIR)'")
-endif
+# Check for spaces and null value
 OUTPUTDIR:=$(call AltCheckSpaces,OUTPUTDIR)
 OUTPUTDIR:=$(call AltCheckValue,OUTPUTDIR)
+# Create the output directory and make sure it exists and is writable
+_create_outputdir:=$(shell $(MKDIR) -p "$(OUTPUTDIR)" > $(DEV_NULL) 2>&1)
+ifeq ($(call WriteDirExists,$(OUTPUTDIR),/dev/null),/dev/null)
+  _outputdir_error:=$(error "ERROR: OUTPUTDIR '$(OUTPUTDIR)' not created or not writable")
+endif
+# Define absolute path if needed and check for spaces and null value
+ifndef ABS_OUTPUTDIR
+  ABS_OUTPUTDIR:=$(call FullPath,$(OUTPUTDIR))
+endif
+ABS_OUTPUTDIR:=$(call AltCheckSpaces,ABS_OUTPUTDIR)
+ABS_OUTPUTDIR:=$(call AltCheckValue,ABS_OUTPUTDIR)
+# Make doubly sure this is a full path
+ifeq ($(call AbsPwdPathCheck,$(ABS_OUTPUTDIR)), )
+  ifdef ALT_OUTPUTDIR
+    _outputdir_error:=$(error "ERROR: Trouble with the absolute path for OUTPUTDIR '$(OUTPUTDIR)', was ALT_OUTPUTDIR '$(ALT_OUTPUTDIR)' an absolute path?")
+  else
+    _outputdir_error:=$(error "ERROR: Trouble with the absolute path for OUTPUTDIR '$(OUTPUTDIR)'")
+  endif
+endif
+_dir1:=$(call FullPath,$(ABS_OUTPUTDIR))
+_dir2:=$(call FullPath,$(OUTPUTDIR))
+ifneq ($(_dir1),$(_dir2))
+  _outputdir_error:=$(error "ERROR: ABS_OUTPUTDIR '$(ABS_OUTPUTDIR)' is not the same directory as OUTPUTDIR '$(OUTPUTDIR)', '$(_dir1)'!='$(_dir2)'")
+endif
 
 # Bin directory
 #   NOTE: ISA_DIR is usually empty, on Solaris it might be /sparcv9 or /amd64
@@ -475,9 +509,6 @@
   COPYRIGHT_YEAR = $(shell $(DATE) '+%Y')
 endif
 
-# Absolute path to output directory
-ABS_OUTPUTDIR:=$(call FullPath,$(OUTPUTDIR))
-
 # Get shared compiler settings
 include $(JDK_MAKE_SHARED_DIR)/Compiler.gmk
 
--- a/make/common/shared/Platform.gmk	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/common/shared/Platform.gmk	Fri Mar 28 03:06:00 2008 -0700
@@ -93,20 +93,18 @@
 # Normal boot jdk is previous release, but a hard requirement is a 1.5 boot
 REQUIRED_BOOT_VER = 1.5
 
-#This is specific to OpenJDK build
-ifdef OPENJDK
-  REQUIRED_FREETYPE_VERSION=2.3.0
-endif
+# If we are using freetype, this is the required version
+REQUIRED_FREETYPE_VERSION=2.3.0
 
 #
 # Prune out all known SCM (Source Code Management) directories
 # so they will not be included when copying directory trees
 # or packaging up .jar files, etc.  This applies to all workspaces.
 #
-SCM_DIRs = .hg .svn CVS RCS SCCS Codemgr_wsdata deleted_files
+SCM_DIRs = .hg .svn CVS RCS SCCS Codemgr_wsdata deleted_files .hgignore .hgtags
 # When changing SCM_DIRs also change SCM_DIRS_rexp and SCM_DIRS_prune:
-SCM_DIRS_rexp = ".hg|.svn|CVS|RCS|SCCS|Codemgr_wsdata|deleted_files"
-SCM_DIRS_prune = \( -name .hg -o -name .svn -o -name CVS -o -name RCS -o -name SCCS -o -name Codemgr_wsdata -o -name deleted_files \) -prune
+SCM_DIRS_rexp = ".hg|.svn|CVS|RCS|SCCS|Codemgr_wsdata|deleted_files|.hgignore|.hgtags"
+SCM_DIRS_prune = \( -name .hg -o -name .svn -o -name CVS -o -name RCS -o -name SCCS -o -name Codemgr_wsdata -o -name deleted_files -o -name .hgignore -o -name .hgtags \) -prune
 
 # Don't define this unless it's not defined
 ifndef VARIANT
--- a/make/java/java/mapfile-vers	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/java/mapfile-vers	Fri Mar 28 03:06:00 2008 -0700
@@ -85,7 +85,6 @@
 		Java_java_io_FileOutputStream_close0;
 		Java_java_io_FileOutputStream_initIDs;
 		Java_java_io_FileOutputStream_open;
-		Java_java_io_FileOutputStream_openAppend;
 		Java_java_io_FileOutputStream_write;
 		Java_java_io_FileOutputStream_writeBytes;
 		Java_java_io_FileSystem_getFileSystem;
--- a/make/java/jli/Makefile	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/jli/Makefile	Fri Mar 28 03:06:00 2008 -0700
@@ -107,6 +107,7 @@
 
 ifeq ($(PLATFORM), windows)
 	EXTRA_LIBS = advapi32.lib \
+		     comctl32.lib \
 		     user32.lib
 
 	JAVALIB =
--- a/make/java/main/java/Makefile	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/main/java/Makefile	Fri Mar 28 03:06:00 2008 -0700
@@ -43,7 +43,7 @@
 
 # Override the default version info with our own resource file (see 5106536)
 ifeq ($(PLATFORM), windows)
-LDLIBS_COMMON += user32.lib
+LDLIBS_COMMON += user32.lib comctl32.lib
 ifdef OPENJDK
     RC_FLAGS += -i "$(PLATFORM_SRC)/resource/icons"
 else
--- a/make/java/main/javaw/Makefile	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/main/javaw/Makefile	Fri Mar 28 03:06:00 2008 -0700
@@ -46,7 +46,7 @@
 include $(BUILDDIR)/common/Defs.gmk
 
 OTHER_CPPFLAGS += -DJAVAW
-LDLIBS_COMMON +=  user32.lib
+LDLIBS_COMMON +=  user32.lib comctl32.lib
 
 # Override the default version info with our own resource file (see 5106536)
 ifeq ($(PLATFORM), windows)
--- a/make/java/nio/Makefile	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/nio/Makefile	Fri Mar 28 03:06:00 2008 -0700
@@ -191,7 +191,7 @@
 
 GEN_BUFFER_SH = genBuffer.sh
 
-GEN_BUFFER_CMD = SPP="$(SPP_CMD)" NAWK=$(NAWK) SED=$(SED) \
+GEN_BUFFER_CMD = SPP="$(SPP_CMD)" NAWK=$(NAWK) SED=$(SED) SH=$(SH) \
                  $(SH) $(GEN_BUFFER_SH)
 
 # Public abstract buffer classes
@@ -582,7 +582,7 @@
 
 GEN_CODER_SH = genCoder.sh
 
-GEN_CODER_CMD = SPP="$(SPP_CMD)" SED=$(SED) NAWK=$(NAWK) $(SH) $(GEN_CODER_SH)
+GEN_CODER_CMD = SPP="$(SPP_CMD)" SED=$(SED) NAWK=$(NAWK) SH=$(SH) $(SH) $(GEN_CODER_SH)
 
 $(CS_GEN)/CharsetDecoder.java: $(CS_SRC)/Charset-X-Coder.java $(GEN_CODER_SH)
 	$(prep-target)
@@ -602,7 +602,7 @@
 
 GEN_EX_SH = genExceptions.sh
  
-GEN_EX_CMD = NAWK=$(NAWK) $(SHELL) $(GEN_EX_SH)
+GEN_EX_CMD = NAWK=$(NAWK) SH=$(SH) $(SH) $(GEN_EX_SH)
 
 $(CH_GEN)/%Exception.java: genExceptions.sh $(CH_SRC)/exceptions
 	$(prep-target)
@@ -635,8 +635,8 @@
     $(HASHER_JARFILE) $(SCS_SRC)/standard-charsets
 	$(prep-target)
 	@$(RM) $@.temp
-	NAWK=$(NAWK) TEMPDIR=$(TEMPDIR) \
+	NAWK=$(NAWK) TEMPDIR=$(TEMPDIR) SH=$(SH) \
 	  HASHER="$(BOOT_JAVA_CMD) -jar $(HASHER_JARFILE)" \
-	  $(SHELL) -e genCharsetProvider.sh $(SCS_SRC)/standard-charsets $(SCS_GEN)
+	  $(SH) -e genCharsetProvider.sh $(SCS_SRC)/standard-charsets $(SCS_GEN)
 
 .PHONY: sources 
--- a/make/java/nio/genCharsetProvider.sh	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/nio/genCharsetProvider.sh	Fri Mar 28 03:06:00 2008 -0700
@@ -48,7 +48,7 @@
 # Header
 #
 
-$SHELL addNotices.sh "$COPYRIGHT_YEARS" > $OUT
+$SH ./addNotices.sh "$COPYRIGHT_YEARS" > $OUT
 
 cat <<__END__ >>$OUT
 
--- a/make/java/nio/genExceptions.sh	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/java/nio/genExceptions.sh	Fri Mar 28 03:06:00 2008 -0700
@@ -41,7 +41,7 @@
   echo '-->' $DST/$ID.java
   out=$DST/${ID}.java
 
-  $SHELL addNotices.sh "$COPYRIGHT_YEARS" > $out
+  $SH ./addNotices.sh "$COPYRIGHT_YEARS" > $out
 
 cat >>$out <<__END__
 
--- a/make/tools/freetypecheck/Makefile	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/tools/freetypecheck/Makefile	Fri Mar 28 03:06:00 2008 -0700
@@ -38,7 +38,14 @@
 
 all: $(FT_TEST_PATH)
 
-FT_OPTIONS  = -I$(FT_HEADERS) -I$(FT_HEADERS)/freetype2
+# Start with CFLAGS (which gets us the required -xarch setting on solaris)
+ifeq ($(PLATFORM), windows)
+  FT_OPTIONS  =
+else
+  FT_OPTIONS  = $(CFLAGS)
+endif
+
+FT_OPTIONS += -I$(FT_HEADERS) -I$(FT_HEADERS)/freetype2
 FT_OPTIONS += $(XARCH)
 
 #add runtime library search path
--- a/make/tools/src/build/tools/jdwpgen/CommandNode.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/tools/src/build/tools/jdwpgen/CommandNode.java	Fri Mar 28 03:06:00 2008 -0700
@@ -32,9 +32,9 @@
 
     void constrain(Context ctx) {
         if (components.size() == 3) {
-            Node out = (Node)components.get(0);
-            Node reply = (Node)components.get(1);
-            Node error = (Node)components.get(2);
+            Node out   = components.get(0);
+            Node reply = components.get(1);
+            Node error = components.get(2);
             if (!(out instanceof OutNode)) {
                 error("Expected 'Out' item, got: " + out);
             }
@@ -45,7 +45,7 @@
                 error("Expected 'ErrorSet' item, got: " + error);
             }
         } else if (components.size() == 1) {
-            Node evt = (Node)components.get(0);
+            Node evt = components.get(0);
             if (!(evt instanceof EventNode)) {
                 error("Expected 'Event' item, got: " + evt);
             }
--- a/make/tools/src/build/tools/jdwpgen/ConstantSetNode.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/tools/src/build/tools/jdwpgen/ConstantSetNode.java	Fri Mar 28 03:06:00 2008 -0700
@@ -98,7 +98,7 @@
         if (constantMap == null) {
             return "";
         }
-        String com = (String) constantMap.get(key);
+        String com = constantMap.get(key);
         if(com == null){
             return "";
         } else {
--- a/make/tools/src/build/tools/jdwpgen/RepeatNode.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/make/tools/src/build/tools/jdwpgen/RepeatNode.java	Fri Mar 28 03:06:00 2008 -0700
@@ -37,7 +37,7 @@
         if (components.size() != 1) {
             error("Repeat must have exactly one member, use Group for more");
         }
-        member = (Node)(components.get(0));
+        member = components.get(0);
         if (!(member instanceof TypeNode)) {
             error("Repeat member must be type specifier");
         }
--- a/src/share/bin/java.c	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/bin/java.c	Fri Mar 28 03:06:00 2008 -0700
@@ -205,9 +205,7 @@
     _wc_enabled = cpwildcard;
     _ergo_policy = ergo;
 
-    if (javaw == JNI_TRUE)
-        SetJavaw();
-
+    InitLauncher(javaw);
     DumpState();
 
     /*
--- a/src/share/bin/java.h	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/bin/java.h	Fri Mar 28 03:06:00 2008 -0700
@@ -172,7 +172,6 @@
 const char* GetFullVersion();
 jboolean IsJavaArgs();
 jboolean IsJavaw();
-void SetJavaw();
 jint GetErgoPolicy();
 
 jboolean ServerClassMachine();
@@ -180,5 +179,9 @@
 static int ContinueInNewThread(InvocationFunctions* ifn, int argc, char** argv,
                         char* jarfile, char* classname, int ret);
 
+/*
+ * Initialize platform specific settings
+ */
+void InitLauncher(jboolean javaw);
 
 #endif /* _JAVA_H_ */
--- a/src/share/bin/main.c	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/bin/main.c	Fri Mar 28 03:06:00 2008 -0700
@@ -64,8 +64,6 @@
     margv = argv;
 #endif /* JAVAW */
 
-    JLI_SetTraceLauncher();
-
     return JLI_Launch(margc, margv,
                    sizeof(const_jargs) / sizeof(char *), const_jargs,
                    sizeof(const_appclasspath) / sizeof(char *), const_appclasspath,
--- a/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -34,6 +34,7 @@
 import java.security.GeneralSecurityException;
 import java.security.InvalidKeyException;
 import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
 import java.security.spec.InvalidKeySpecException;
 import javax.crypto.Mac;
 import javax.crypto.SecretKey;
@@ -107,12 +108,17 @@
             throw new InvalidKeySpecException("Key length is negative");
         }
         try {
-            this.prf = Mac.getInstance(prfAlgo, new SunJCE());
+            this.prf = Mac.getInstance(prfAlgo, "SunJCE");
         } catch (NoSuchAlgorithmException nsae) {
             // not gonna happen; re-throw just in case
             InvalidKeySpecException ike = new InvalidKeySpecException();
             ike.initCause(nsae);
             throw ike;
+        } catch (NoSuchProviderException nspe) {
+            // Again, not gonna happen; re-throw just in case
+            InvalidKeySpecException ike = new InvalidKeySpecException();
+            ike.initCause(nspe);
+            throw ike;
         }
         this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength);
     }
--- a/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Fri Mar 28 03:06:00 2008 -0700
@@ -43,6 +43,13 @@
 import javax.management.NotCompliantMBeanException;
 
 import com.sun.jmx.mbeanserver.Util;
+import com.sun.jmx.remote.util.EnvHelp;
+import java.beans.BeanInfo;
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import javax.management.AttributeNotFoundException;
+import javax.management.openmbean.CompositeData;
 
 /**
  * This class contains the methods for performing all the tests needed to verify
@@ -482,4 +489,33 @@
 
         return null;
     }
+
+    public static Object elementFromComplex(Object complex, String element)
+    throws AttributeNotFoundException {
+        try {
+            if (complex.getClass().isArray() && element.equals("length")) {
+                return Array.getLength(complex);
+            } else if (complex instanceof CompositeData) {
+                return ((CompositeData) complex).get(element);
+            } else {
+                // Java Beans introspection
+                //
+                BeanInfo bi = java.beans.Introspector.getBeanInfo(complex.getClass());
+                PropertyDescriptor[] pds = bi.getPropertyDescriptors();
+                for (PropertyDescriptor pd : pds)
+                    if (pd.getName().equals(element))
+                        return pd.getReadMethod().invoke(complex);
+                throw new AttributeNotFoundException(
+                    "Could not find the getter method for the property " +
+                    element + " using the Java Beans introspector");
+            }
+        } catch (InvocationTargetException e) {
+            throw new IllegalArgumentException(e);
+        } catch (AttributeNotFoundException e) {
+            throw e;
+        } catch (Exception e) {
+            throw EnvHelp.initCause(
+                new AttributeNotFoundException(e.getMessage()), e);
+        }
+    }
 }
--- a/src/share/classes/com/sun/tools/example/debug/bdi/EventRequestSpec.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/EventRequestSpec.java	Fri Mar 28 03:06:00 2008 -0700
@@ -91,9 +91,7 @@
 
     void attemptImmediateResolve(VirtualMachine vm) {
         // try to resolve immediately
-        Iterator iter = vm.allClasses().iterator();
-        while (iter.hasNext()) {
-            ReferenceType refType = (ReferenceType)iter.next();
+        for (ReferenceType refType : vm.allClasses()) {
             if (refSpec.matches(refType)) {
                 try {
                     resolve(refType);
--- a/src/share/classes/com/sun/tools/example/debug/bdi/EventRequestSpecList.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/EventRequestSpecList.java	Fri Mar 28 03:06:00 2008 -0700
@@ -47,9 +47,8 @@
      */
     void resolve(ReferenceType refType) {
         synchronized(eventRequestSpecs) {
-            Iterator iter = eventRequestSpecs.iterator();
-            while (iter.hasNext()) {
-                ((EventRequestSpec)iter.next()).attemptResolve(refType);
+            for (EventRequestSpec spec : eventRequestSpecs) {
+                spec.attemptResolve(refType);
              }
         }
     }
@@ -79,7 +78,7 @@
 
     BreakpointSpec
     createMethodBreakpoint(String classPattern,
-                           String methodId, List methodArgs) {
+                           String methodId, List<String> methodArgs) {
         ReferenceTypeSpec refSpec =
             new PatternReferenceTypeSpec(classPattern);
         return new MethodBreakpointSpec(this, refSpec,
@@ -132,47 +131,48 @@
 
     // --------  notify routines --------------------
 
-    private Vector specListeners() {
-        return (Vector)runtime.specListeners.clone();
+    @SuppressWarnings("unchecked")
+    private Vector<SpecListener> specListeners() {
+        return (Vector<SpecListener>)runtime.specListeners.clone();
     }
 
     void notifySet(EventRequestSpec spec) {
-        Vector l = specListeners();
+        Vector<SpecListener> l = specListeners();
         SpecEvent evt = new SpecEvent(spec);
         for (int i = 0; i < l.size(); i++) {
-            spec.notifySet((SpecListener)l.elementAt(i), evt);
+            spec.notifySet(l.elementAt(i), evt);
         }
     }
 
     void notifyDeferred(EventRequestSpec spec) {
-        Vector l = specListeners();
+        Vector<SpecListener> l = specListeners();
         SpecEvent evt = new SpecEvent(spec);
         for (int i = 0; i < l.size(); i++) {
-            spec.notifyDeferred((SpecListener)l.elementAt(i), evt);
+            spec.notifyDeferred(l.elementAt(i), evt);
         }
     }
 
     void notifyDeleted(EventRequestSpec spec) {
-        Vector l = specListeners();
+        Vector<SpecListener> l = specListeners();
         SpecEvent evt = new SpecEvent(spec);
         for (int i = 0; i < l.size(); i++) {
-            spec.notifyDeleted((SpecListener)l.elementAt(i), evt);
+            spec.notifyDeleted(l.elementAt(i), evt);
         }
     }
 
     void notifyResolved(EventRequestSpec spec) {
-        Vector l = specListeners();
+        Vector<SpecListener> l = specListeners();
         SpecEvent evt = new SpecEvent(spec);
         for (int i = 0; i < l.size(); i++) {
-            spec.notifyResolved((SpecListener)l.elementAt(i), evt);
+            spec.notifyResolved(l.elementAt(i), evt);
         }
     }
 
     void notifyError(EventRequestSpec spec, Exception exc) {
-        Vector l = specListeners();
+        Vector<SpecListener> l = specListeners();
         SpecErrorEvent evt = new SpecErrorEvent(spec, exc);
         for (int i = 0; i < l.size(); i++) {
-            spec.notifyError((SpecListener)l.elementAt(i), evt);
+            spec.notifyError(l.elementAt(i), evt);
         }
     }
 }
--- a/src/share/classes/com/sun/tools/example/debug/bdi/ExecutionManager.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/ExecutionManager.java	Fri Mar 28 03:06:00 2008 -0700
@@ -232,10 +232,7 @@
         if (pattern.startsWith("*.")) {
             // Wildcard matches any leading package name.
             pattern = pattern.substring(1);
-            List classes = vm().allClasses();
-            Iterator iter = classes.iterator();
-            while (iter.hasNext()) {
-                ReferenceType type = ((ReferenceType)iter.next());
+            for (ReferenceType type : vm().allClasses()) {
                 if (type.name().endsWith(pattern)) {
                     result.add(type);
                 }
@@ -278,7 +275,7 @@
     public ThreadGroupReference systemThreadGroup()
                                                 throws NoSessionException {
         ensureActiveSession();
-        return (ThreadGroupReference)vm().topLevelThreadGroups().get(0);
+        return vm().topLevelThreadGroups().get(0);
     }
 
     /*
@@ -349,10 +346,9 @@
          * attach sessions.
          */
         VirtualMachineManager mgr = Bootstrap.virtualMachineManager();
-        List connectors = mgr.attachingConnectors();
-        AttachingConnector connector = (AttachingConnector)connectors.get(0);
+        AttachingConnector connector = mgr.attachingConnectors().get(0);
         Map<String, Connector.Argument> arguments = connector.defaultArguments();
-        ((Connector.Argument)arguments.get("port")).setValue(portName);
+        arguments.get("port").setValue(portName);
 
         Session newSession = internalAttach(connector, arguments);
         if (newSession != null) {
@@ -504,10 +500,7 @@
          * if so, it gets removed here.
          */
          EventRequestManager mgr = vm().eventRequestManager();
-         List requests = mgr.stepRequests();
-         Iterator iter = requests.iterator();
-         while (iter.hasNext()) {
-             StepRequest request = (StepRequest)iter.next();
+         for (StepRequest request : mgr.stepRequests()) {
              if (request.thread().equals(thread)) {
                  mgr.deleteEventRequest(request);
                  break;
@@ -591,7 +584,7 @@
         if (session == null || thread == null) {
             return null;
         }
-        ThreadInfo info = (ThreadInfo)threadInfoMap.get(thread);
+        ThreadInfo info = threadInfoMap.get(thread);
         if (info == null) {
             //### Should not hardcode initial frame count and prefetch here!
             //info = new ThreadInfo(thread, 10, 10);
@@ -607,24 +600,22 @@
 
      void validateThreadInfo() {
         session.interrupted = true;
-        Iterator iter = threadInfoList.iterator();
-            while (iter.hasNext()) {
-                ((ThreadInfo)iter.next()).validate();
+        for (ThreadInfo threadInfo : threadInfoList) {
+            threadInfo.validate();
             }
     }
 
     private void invalidateThreadInfo() {
         if (session != null) {
             session.interrupted = false;
-            Iterator iter = threadInfoList.iterator();
-            while (iter.hasNext()) {
-                ((ThreadInfo)iter.next()).invalidate();
+            for (ThreadInfo threadInfo : threadInfoList) {
+                threadInfo.invalidate();
             }
         }
     }
 
     void removeThreadInfo(ThreadReference thread) {
-        ThreadInfo info = (ThreadInfo)threadInfoMap.get(thread);
+        ThreadInfo info = threadInfoMap.get(thread);
         if (info != null) {
             info.invalidate();
             threadInfoMap.remove(thread);
@@ -702,7 +693,7 @@
                         while (inputBuffer.size() < 1) {
                             inputLock.wait();
                         }
-                        line = (String)inputBuffer.removeLast();
+                        line = inputBuffer.removeLast();
                     } catch (InterruptedException e) {}
                 }
             }
@@ -774,7 +765,7 @@
 
     public BreakpointSpec
     createMethodBreakpoint(String classPattern,
-                           String methodId, List methodArgs) {
+                           String methodId, List<String> methodArgs) {
         return specList.createMethodBreakpoint(classPattern,
                                                  methodId, methodArgs);
     }
@@ -811,7 +802,7 @@
         specList.install(spec, vm());
     }
 
-    public List eventRequestSpecs() {
+    public List<EventRequestSpec> eventRequestSpecs() {
         return specList.eventRequestSpecs();
     }
 }
--- a/src/share/classes/com/sun/tools/example/debug/bdi/JDIEventSource.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/JDIEventSource.java	Fri Mar 28 03:06:00 2008 -0700
@@ -82,9 +82,7 @@
                 boolean interrupted = es.suspendedAll();
                 es.notify(firstListener);
                 boolean wantInterrupt = JDIEventSource.this.wantInterrupt;
-                for (Iterator it = session.runtime.jdiListeners.iterator();
-                     it.hasNext(); ) {
-                    JDIListener jl = (JDIListener)it.next();
+                for (JDIListener jl : session.runtime.jdiListeners) {
                     es.notify(jl);
                 }
                 if (interrupted && !wantInterrupt) {
--- a/src/share/classes/com/sun/tools/example/debug/bdi/LineBreakpointSpec.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/LineBreakpointSpec.java	Fri Mar 28 03:06:00 2008 -0700
@@ -58,12 +58,12 @@
                                             LineNotFoundException {
         Location location = null;
         try {
-            List locs = clazz.locationsOfLine(lineNumber());
+            List<Location> locs = clazz.locationsOfLine(lineNumber());
             if (locs.size() == 0) {
                 throw new LineNotFoundException();
             }
             // TODO handle multiple locations
-            location = (Location)locs.get(0);
+            location = locs.get(0);
             if (location.method() == null) {
                 throw new LineNotFoundException();
             }
--- a/src/share/classes/com/sun/tools/example/debug/bdi/MethodBreakpointSpec.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/MethodBreakpointSpec.java	Fri Mar 28 03:06:00 2008 -0700
@@ -34,11 +34,11 @@
 
 public class MethodBreakpointSpec extends BreakpointSpec {
     String methodId;
-    List methodArgs;
+    List<String> methodArgs;
 
     MethodBreakpointSpec(EventRequestSpecList specs,
                          ReferenceTypeSpec refSpec,
-                         String methodId, List methodArgs) {
+                         String methodId, List<String> methodArgs) {
         super(specs, refSpec);
         this.methodId = methodId;
         this.methodArgs = methodArgs;
@@ -76,7 +76,7 @@
         return methodId;
     }
 
-    public List methodArgs() {
+    public List<String> methodArgs() {
         return methodArgs;
     }
 
@@ -120,14 +120,13 @@
         buffer.append('.');
         buffer.append(methodId);
         if (methodArgs != null) {
-            Iterator iter = methodArgs.iterator();
             boolean first = true;
             buffer.append('(');
-            while (iter.hasNext()) {
+            for (String name : methodArgs) {
                 if (!first) {
                     buffer.append(',');
                 }
-                buffer.append((String)iter.next());
+                buffer.append(name);
                 first = false;
             }
             buffer.append(")");
@@ -151,8 +150,8 @@
      * and if the number of arguments in the method matches the
      * number of names passed
      */
-    private boolean compareArgTypes(Method method, List nameList) {
-        List argTypeNames = method.argumentTypeNames();
+    private boolean compareArgTypes(Method method, List<String> nameList) {
+        List<String> argTypeNames = method.argumentTypeNames();
 
         // If argument counts differ, we can stop here
         if (argTypeNames.size() != nameList.size()) {
@@ -162,8 +161,8 @@
         // Compare each argument type's name
         int nTypes = argTypeNames.size();
         for (int i = 0; i < nTypes; ++i) {
-            String comp1 = (String)argTypeNames.get(i);
-            String comp2 = (String)nameList.get(i);
+            String comp1 = argTypeNames.get(i);
+            String comp2 = nameList.get(i);
             if (! comp1.equals(comp2)) {
                 /*
                  * We have to handle varargs.  EG, the
@@ -288,22 +287,17 @@
         List<String> argTypeNames = null;
         if (methodArgs() != null) {
             argTypeNames = new ArrayList<String>(methodArgs().size());
-            Iterator iter = methodArgs().iterator();
-            while (iter.hasNext()) {
-                String name = (String)iter.next();
+            for (String name : methodArgs()) {
                 name = normalizeArgTypeName(name);
                 argTypeNames.add(name);
             }
         }
 
         // Check each method in the class for matches
-        Iterator iter = clazz.methods().iterator();
         Method firstMatch = null;  // first method with matching name
         Method exactMatch = null;  // (only) method with same name & sig
         int matchCount = 0;        // > 1 implies overload
-        while (iter.hasNext()) {
-            Method candidate = (Method)iter.next();
-
+        for (Method candidate : clazz.methods()) {
             if (candidate.name().equals(methodName())) {
                 matchCount++;
 
--- a/src/share/classes/com/sun/tools/example/debug/bdi/ThreadGroupIterator.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/ThreadGroupIterator.java	Fri Mar 28 03:06:00 2008 -0700
@@ -36,7 +36,7 @@
  * Descend the tree of thread groups.
  * @author Robert G. Field
  */
-public class ThreadGroupIterator implements Iterator {
+public class ThreadGroupIterator implements Iterator<ThreadGroupReference> {
     private final Stack<Iterator<ThreadGroupReference>> stack
                         = new Stack<Iterator<ThreadGroupReference>>();
 
@@ -56,8 +56,8 @@
     }
 */
 
-    private Iterator top() {
-        return (Iterator)stack.peek();
+    private Iterator<ThreadGroupReference> top() {
+        return stack.peek();
     }
 
     /**
@@ -77,12 +77,12 @@
         return !stack.isEmpty();
     }
 
-    public Object next() {
+    public ThreadGroupReference next() {
         return nextThreadGroup();
     }
 
     public ThreadGroupReference nextThreadGroup() {
-        ThreadGroupReference tg = (ThreadGroupReference)top().next();
+        ThreadGroupReference tg = top().next();
         push(tg.threadGroups());
         return tg;
     }
--- a/src/share/classes/com/sun/tools/example/debug/bdi/ThreadIterator.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/bdi/ThreadIterator.java	Fri Mar 28 03:06:00 2008 -0700
@@ -30,8 +30,8 @@
 import java.util.List;
 import java.util.Iterator;
 
-public class ThreadIterator implements Iterator {
-    Iterator it = null;
+public class ThreadIterator implements Iterator<ThreadReference> {
+    Iterator<ThreadReference> it = null;
     ThreadGroupIterator tgi;
 
     public ThreadIterator(ThreadGroupReference tg) {
@@ -53,12 +53,12 @@
         return true;
     }
 
-    public Object next() {
+    public ThreadReference next() {
         return it.next();
     }
 
     public ThreadReference nextThread() {
-        return (ThreadReference)next();
+        return next();
     }
 
     public void remove() {
--- a/src/share/classes/com/sun/tools/example/debug/expr/LValue.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/expr/LValue.java	Fri Mar 28 03:06:00 2008 -0700
@@ -191,11 +191,12 @@
         return field;
     }
 
-    static List methodsByName(ReferenceType refType, String name, int kind) {
-        List list = refType.methodsByName(name);
-        Iterator iter = list.iterator();
+    static List<Method> methodsByName(ReferenceType refType,
+                                      String name, int kind) {
+        List<Method> list = refType.methodsByName(name);
+        Iterator<Method> iter = list.iterator();
         while (iter.hasNext()) {
-            Method method = (Method)iter.next();
+            Method method = iter.next();
             boolean isStatic = method.isStatic();
             if (((kind == STATIC) && !isStatic) ||
                 ((kind == INSTANCE) && isStatic)) {
@@ -231,21 +232,21 @@
      * argType is not assignable from the type of the argument value.
      * IE, one is an Apple and the other is an Orange.
      */
-    static int argumentsMatch(List argTypes, List arguments) {
+    static int argumentsMatch(List<Type> argTypes, List<Value> arguments) {
         if (argTypes.size() != arguments.size()) {
             return DIFFERENT;
         }
 
-        Iterator typeIter = argTypes.iterator();
-        Iterator valIter = arguments.iterator();
+        Iterator<Type> typeIter = argTypes.iterator();
+        Iterator<Value> valIter = arguments.iterator();
         int result = SAME;
 
         // If any pair aren't the same, change the
         // result to ASSIGNABLE.  If any pair aren't
         // assignable, return DIFFERENT
         while (typeIter.hasNext()) {
-            Type argType = (Type)typeIter.next();
-            Value value = (Value)valIter.next();
+            Type argType = typeIter.next();
+            Value value = valIter.next();
             if (value == null) {
                 // Null values can be passed to any non-primitive argument
                 if (primitiveTypeNames.contains(argType.name())) {
@@ -333,7 +334,7 @@
         if (fromType instanceof ArrayType) {
             return isArrayAssignableTo((ArrayType)fromType, toType);
         }
-        List interfaces;
+        List<InterfaceType> interfaces;
         if (fromType instanceof ClassType) {
             ClassType superclazz = ((ClassType)fromType).superclass();
             if ((superclazz != null) && isAssignableTo(superclazz, toType)) {
@@ -344,9 +345,7 @@
             // fromType must be an InterfaceType
             interfaces = ((InterfaceType)fromType).superinterfaces();
         }
-        Iterator iter = interfaces.iterator();
-        while (iter.hasNext()) {
-            InterfaceType interfaze = (InterfaceType)iter.next();
+        for (InterfaceType interfaze : interfaces) {
             if (isAssignableTo(interfaze, toType)) {
                 return true;
             }
@@ -354,7 +353,8 @@
         return false;
     }
 
-    static Method resolveOverload(List overloads, List arguments)
+    static Method resolveOverload(List<Method> overloads,
+                                  List<Value> arguments)
                                        throws ParseException {
 
         // If there is only one method to call, we'll just choose
@@ -362,7 +362,7 @@
         // the invoke will return a better error message than we
         // could generate here.
         if (overloads.size() == 1) {
-            return (Method)overloads.get(0);
+            return overloads.get(0);
         }
 
         // Resolving overloads is beyond the scope of this exercise.
@@ -374,12 +374,10 @@
         // methods to call. And, since casts aren't implemented,
         // the user can't use them to pick a particular overload to call.
         // IE, the user is out of luck in this case.
-        Iterator iter = overloads.iterator();
         Method retVal = null;
         int assignableCount = 0;
-        while (iter.hasNext()) {
-            Method mm = (Method)iter.next();
-            List argTypes;
+        for (Method mm : overloads) {
+            List<Type> argTypes;
             try {
                 argTypes = mm.argumentTypes();
             } catch (ClassNotLoadedException ee) {
@@ -443,7 +441,7 @@
         final ObjectReference obj;
         final ThreadReference thread;
         final Field matchingField;
-        final List overloads;
+        final List<Method> overloads;
         Method matchingMethod = null;
         List<Value> methodArguments = null;
 
@@ -510,7 +508,7 @@
         final ReferenceType refType;
         final ThreadReference thread;
         final Field matchingField;
-        final List overloads;
+        final List<Method> overloads;
         Method matchingMethod = null;
         List<Value> methodArguments = null;
 
@@ -765,7 +763,7 @@
     static LValue makeNewObject(VirtualMachine vm,
                                  ExpressionParser.GetFrame frameGetter,
                                 String className, List<Value> arguments) throws ParseException {
-        List classes = vm.classesByName(className);
+        List<ReferenceType> classes = vm.classesByName(className);
         if (classes.size() == 0) {
             throw new ParseException("No class named: " + className);
         }
@@ -774,7 +772,7 @@
             throw new ParseException("More than one class named: " +
                                      className);
         }
-        ReferenceType refType = (ReferenceType)classes.get(0);
+        ReferenceType refType = classes.get(0);
 
 
         if (!(refType instanceof ClassType)) {
@@ -784,9 +782,9 @@
 
         ClassType classType = (ClassType)refType;
         List<Method> methods = new ArrayList<Method>(classType.methods()); // writable
-        Iterator iter = methods.iterator();
+        Iterator<Method> iter = methods.iterator();
         while (iter.hasNext()) {
-            Method method = (Method)iter.next();
+            Method method = iter.next();
             if (!method.isConstructor()) {
                 iter.remove();
             }
@@ -858,13 +856,13 @@
                 }
                 // check for class name
                 while (izer.hasMoreTokens()) {
-                    List classes = vm.classesByName(first);
+                    List<ReferenceType> classes = vm.classesByName(first);
                     if (classes.size() > 0) {
                         if (classes.size() > 1) {
                             throw new ParseException("More than one class named: " +
                                                      first);
                         } else {
-                            ReferenceType refType = (ReferenceType)classes.get(0);
+                            ReferenceType refType = classes.get(0);
                             LValue lval = new LValueStaticMember(refType,
                                                             izer.nextToken(), thread);
                             return nFields(lval, izer, thread);
--- a/src/share/classes/com/sun/tools/example/debug/gui/ClassTreeTool.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/ClassTreeTool.java	Fri Mar 28 03:06:00 2008 -0700
@@ -124,9 +124,7 @@
         public void sessionStart(EventObject e) {
             // Get system classes and any others loaded before attaching.
             try {
-                Iterator iter = runtime.allClasses().iterator();
-                while (iter.hasNext()) {
-                    ReferenceType type = ((ReferenceType)iter.next());
+                for (ReferenceType type : runtime.allClasses()) {
                     root.addClass(type);
                 }
             } catch (VMDisconnectedException ee) {
--- a/src/share/classes/com/sun/tools/example/debug/gui/CommandInterpreter.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/CommandInterpreter.java	Fri Mar 28 03:06:00 2008 -0700
@@ -77,7 +77,7 @@
             while (ti.hasNext()) {
                 tlist.add(ti.nextThread());
             }
-            threads = (ThreadReference[])tlist.toArray(new ThreadReference[tlist.size()]);
+            threads = tlist.toArray(new ThreadReference[tlist.size()]);
         }
         return threads;
     }
@@ -146,11 +146,9 @@
     // Command: classes
 
     private void commandClasses() throws NoSessionException {
-        List list = runtime.allClasses();
         OutputSink out = env.getOutputSink();
         //out.println("** classes list **");
-        for (int i = 0 ; i < list.size() ; i++) {
-            ReferenceType refType = (ReferenceType)list.get(i);
+        for (ReferenceType refType : runtime.allClasses()) {
             out.println(refType.name());
         }
         out.show();
@@ -167,16 +165,16 @@
         String idClass = t.nextToken();
         ReferenceType cls = findClass(idClass);
         if (cls != null) {
-            List methods = cls.allMethods();
+            List<Method> methods = cls.allMethods();
             OutputSink out = env.getOutputSink();
             for (int i = 0; i < methods.size(); i++) {
-                Method method = (Method)methods.get(i);
+                Method method = methods.get(i);
                 out.print(method.declaringType().name() + " " +
                             method.name() + "(");
-                Iterator it = method.argumentTypeNames().iterator();
+                Iterator<String> it = method.argumentTypeNames().iterator();
                 if (it.hasNext()) {
                     while (true) {
-                        out.print((String)it.next());
+                        out.print(it.next());
                         if (!it.hasNext()) {
                             break;
                         }
@@ -193,10 +191,10 @@
     }
 
     private ReferenceType findClass(String pattern) throws NoSessionException {
-        List results = runtime.findClassesMatchingPattern(pattern);
+        List<ReferenceType> results = runtime.findClassesMatchingPattern(pattern);
         if (results.size() > 0) {
             //### Should handle multiple results sensibly.
-            return (ReferenceType)results.get(0);
+            return results.get(0);
         }
         return null;
     }
@@ -235,11 +233,11 @@
 
     private int printThreadGroup(OutputSink out, ThreadGroupReference tg, int iThread) {
         out.println("Group " + tg.name() + ":");
-        List tlist = tg.threads();
+        List<ThreadReference> tlist = tg.threads();
         int maxId = 0;
         int maxName = 0;
         for (int i = 0 ; i < tlist.size() ; i++) {
-            ThreadReference thr = (ThreadReference)tlist.get(i);
+            ThreadReference thr = tlist.get(i);
             int len = Utils.description(thr).length();
             if (len > maxId)
                 maxId = len;
@@ -254,7 +252,7 @@
         String maxNumString = String.valueOf(iThread + tlist.size());
         int maxNumDigits = maxNumString.length();
         for (int i = 0 ; i < tlist.size() ; i++) {
-            ThreadReference thr = (ThreadReference)tlist.get(i);
+            ThreadReference thr = tlist.get(i);
             char buf[] = new char[80];
             for (int j = 0; j < 79; j++) {
                 buf[j] = ' ';
@@ -283,9 +281,7 @@
             sbOut.setLength(79);
             out.println(sbOut.toString());
         }
-        List tglist = tg.threadGroups();
-        for (int ig = 0; ig < tglist.size(); ig++) {
-            ThreadGroupReference tg0 = (ThreadGroupReference)tglist.get(ig);
+        for (ThreadGroupReference tg0 : tg.threadGroups()) {
             if (!tg.equals(tg0)) {  // TODO ref mgt
                 iThread += printThreadGroup(out, tg0, iThread + tlist.size());
             }
@@ -733,7 +729,7 @@
             if (token.toLowerCase().equals("all")) {
                 ThreadIterator it = allThreads();
                 while (it.hasNext()) {
-                    ThreadReference thread = (ThreadReference)it.next();
+                    ThreadReference thread = it.next();
                     out.println(thread.name() + ": ");
                     dumpStack(thread, showPC);
                 }
@@ -755,7 +751,7 @@
         //env.failure("Target VM must be in interrupted state.");
         //env.failure("Current thread isn't suspended.");
         //### Should handle extremely long stack traces sensibly for user.
-        List stack = null;
+        List<StackFrame> stack = null;
         try {
             stack = thread.frames();
         } catch (IncompatibleThreadStateException e) {
@@ -772,7 +768,7 @@
             OutputSink out = env.getOutputSink();
             int nFrames = stack.size();
             for (int i = frameIndex; i < nFrames; i++) {
-                StackFrame frame = (StackFrame)stack.get(i);
+                StackFrame frame = stack.get(i);
                 Location loc = frame.location();
                 Method meth = loc.method();
                 out.print("  [" + (i + 1) + "] ");
@@ -780,7 +776,7 @@
                 out.print('.');
                 out.print(meth.name());
                 out.print(" (");
-                if (meth instanceof Method && ((Method)meth).isNative()) {
+                if (meth.isNative()) {
                     out.print("native method");
                 } else if (loc.lineNumber() != -1) {
                     try {
@@ -806,14 +802,13 @@
 
     private void listEventRequests() throws NoSessionException {
         // Print set breakpoints
-        Iterator iter = runtime.eventRequestSpecs().iterator();
-        if (!iter.hasNext()) {
+        List<EventRequestSpec> specs = runtime.eventRequestSpecs();
+        if (specs.isEmpty()) {
             env.notice("No breakpoints/watchpoints/exceptions set.");
         } else {
             OutputSink out = env.getOutputSink();
             out.println("Current breakpoints/watchpoints/exceptions set:");
-            while (iter.hasNext()) {
-                EventRequestSpec  bp = (EventRequestSpec)iter.next();
+            for (EventRequestSpec bp : specs) {
                 out.println("\t" + bp);
             }
             out.show();
@@ -926,13 +921,13 @@
         //### need 'clear all'
         BreakpointSpec bpSpec = parseBreakpointSpec(t.nextToken());
         if (bpSpec != null) {
-            Iterator iter = runtime.eventRequestSpecs().iterator();
-            if (!iter.hasNext()) {
+            List<EventRequestSpec> specs = runtime.eventRequestSpecs();
+
+            if (specs.isEmpty()) {
                 env.notice("No breakpoints set.");
             } else {
-                List<BreakpointSpec> toDelete = new ArrayList<BreakpointSpec>();
-                while (iter.hasNext()) {
-                    BreakpointSpec spec = (BreakpointSpec)iter.next();
+                List<EventRequestSpec> toDelete = new ArrayList<EventRequestSpec>();
+                for (EventRequestSpec spec : specs) {
                     if (spec.equals(bpSpec)) {
                         toDelete.add(spec);
                     }
@@ -941,7 +936,7 @@
                 if (toDelete.size() <= 1) {
                     env.notice("No matching breakpoint set.");
                 }
-                for (BreakpointSpec spec : toDelete) {
+                for (EventRequestSpec spec : toDelete) {
                     runtime.delete(spec);
                 }
             }
@@ -988,7 +983,7 @@
                 lineno = Integer.valueOf(id).intValue();
             } catch (NumberFormatException nfe) {
                 // It isn't -- see if it's a method name.
-                List meths = refType.methodsByName(id);
+                List<Method> meths = refType.methodsByName(id);
                 if (meths == null || meths.size() == 0) {
                     env.failure(id +
                                 " is not a valid line number or " +
@@ -1001,7 +996,7 @@
                                 refType.name());
                     return;
                 }
-                loc = ((Method)meths.get(0)).location();
+                loc = meths.get(0).location();
                 lineno = loc.lineNumber();
             }
         }
@@ -1121,7 +1116,7 @@
             return;
         }
 
-        List vars;
+        List<LocalVariable> vars;
         try {
             vars = frame.visibleVariables();
             if (vars == null || vars.size() == 0) {
@@ -1136,15 +1131,13 @@
 
         OutputSink out = env.getOutputSink();
         out.println("Method arguments:");
-        for (Iterator it = vars.iterator(); it.hasNext(); ) {
-            LocalVariable var = (LocalVariable)it.next();
+        for (LocalVariable var : vars) {
             if (var.isArgument()) {
                 printVar(out, var, frame);
             }
         }
         out.println("Local variables:");
-        for (Iterator it = vars.iterator(); it.hasNext(); ) {
-            LocalVariable var = (LocalVariable)it.next();
+        for (LocalVariable var : vars) {
             if (!var.isArgument()) {
                 printVar(out, var, frame);
             }
@@ -1245,8 +1238,7 @@
     private void dump(OutputSink out,
                       ObjectReference obj, ReferenceType refType,
                       ReferenceType refTypeBase) {
-        for (Iterator it = refType.fields().iterator(); it.hasNext(); ) {
-            Field field = (Field)it.next();
+        for (Field field : refType.fields()) {
             out.print("    ");
             if (!refType.equals(refTypeBase)) {
                 out.print(refType.name() + ".");
@@ -1261,9 +1253,8 @@
                 dump(out, obj, sup, refTypeBase);
             }
         } else if (refType instanceof InterfaceType) {
-            List sups = ((InterfaceType)refType).superinterfaces();
-            for (Iterator it = sups.iterator(); it.hasNext(); ) {
-                dump(out, obj, (ReferenceType)it.next(), refTypeBase);
+            for (InterfaceType sup : ((InterfaceType)refType).superinterfaces()) {
+                dump(out, obj, sup, refTypeBase);
             }
         }
     }
--- a/src/share/classes/com/sun/tools/example/debug/gui/JDBFileFilter.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/JDBFileFilter.java	Fri Mar 28 03:06:00 2008 -0700
@@ -201,11 +201,11 @@
             if(description == null || isExtensionListInDescription()) {
                 fullDescription = description==null ? "(" : description + " (";
                 // build the description from the extension list
-                Enumeration extensions = filters.keys();
+                Enumeration<String> extensions = filters.keys();
                 if(extensions != null) {
-                    fullDescription += "." + (String) extensions.nextElement();
+                    fullDescription += "." + extensions.nextElement();
                     while (extensions.hasMoreElements()) {
-                        fullDescription += ", " + (String) extensions.nextElement();
+                        fullDescription += ", " + extensions.nextElement();
                     }
                 }
                 fullDescription += ")";
--- a/src/share/classes/com/sun/tools/example/debug/gui/LaunchTool.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/LaunchTool.java	Fri Mar 28 03:06:00 2008 -0700
@@ -131,14 +131,13 @@
         final JPanel radioPanel = new JPanel();
         final ButtonGroup radioGroup = new ButtonGroup();
         VirtualMachineManager manager = Bootstrap.virtualMachineManager();
-        List all = manager.allConnectors();
+        List<Connector> all = manager.allConnectors();
         Map<ButtonModel, Connector> modelToConnector = new HashMap<ButtonModel, Connector>(all.size(), 0.5f);
 
         dialog.setModal(true);
         dialog.setTitle("Select Connector Type");
         radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
-        for (Iterator it = all.iterator(); it.hasNext(); ) {
-            Connector connector = (Connector)it.next();
+        for (Connector connector : all) {
             JRadioButton radio = new JRadioButton(connector.description());
             modelToConnector.put(radio.getModel(), connector);
             radioPanel.add(radio);
@@ -166,7 +165,7 @@
         dialog.show();
 
         return oked[0] ?
-            (Connector)(modelToConnector.get(radioGroup.getSelection())) :
+            modelToConnector.get(radioGroup.getSelection()) :
             null;
     }
 
@@ -188,13 +187,12 @@
         //        guts.add(new JLabel(connector.description()));
 
         final List<ArgRep> argReps = new ArrayList<ArgRep>(args.size());
-        for (Iterator it = args.values().iterator(); it.hasNext(); ) {
-            Object arg = it.next();
+        for (Connector.Argument arg : args.values()) {
             ArgRep ar;
             if (arg instanceof Connector.BooleanArgument) {
                 ar = new BooleanArgRep((Connector.BooleanArgument)arg, guts);
             } else {
-                ar = new StringArgRep((Connector.Argument)arg, guts);
+                ar = new StringArgRep(arg, guts);
             }
             argReps.add(ar);
         }
@@ -202,8 +200,7 @@
 
         JPanel buttonPanel = okCancel( dialog, new ActionListener() {
             public void actionPerformed(ActionEvent event) {
-                for (Iterator it = argReps.iterator(); it.hasNext(); ) {
-                    ArgRep ar = (ArgRep)it.next();
+                for (ArgRep ar : argReps) {
                     if (!ar.isSpecified()) {
                         JOptionPane.showMessageDialog(dialog,
                                     ar.arg.label() +
--- a/src/share/classes/com/sun/tools/example/debug/gui/SearchPath.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/SearchPath.java	Fri Mar 28 03:06:00 2008 -0700
@@ -42,7 +42,7 @@
             dlist.add(st.nextToken());
         }
         pathString = searchPath;
-        pathArray = (String[])dlist.toArray(new String[dlist.size()]);
+        pathArray = dlist.toArray(new String[dlist.size()]);
     }
 
     public boolean isEmpty() {
@@ -54,7 +54,7 @@
     }
 
     public String[] asArray() {
-        return (String[])pathArray.clone();
+        return pathArray.clone();
     }
 
     public File resolve(String relativeFileName) {
@@ -89,7 +89,7 @@
                 }
             }
         }
-        return (String[])s.toArray(new String[s.size()]);
+        return s.toArray(new String[s.size()]);
     }
 
 }
--- a/src/share/classes/com/sun/tools/example/debug/gui/SourceManager.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/SourceManager.java	Fri Mar 28 03:06:00 2008 -0700
@@ -113,7 +113,7 @@
      * Returns null if not available.
      */
     public SourceModel sourceForClass(ReferenceType refType) {
-        SourceModel sm = (SourceModel)classToSource.get(refType);
+        SourceModel sm = classToSource.get(refType);
         if (sm != null) {
             return sm;
         }
@@ -140,10 +140,10 @@
      */
     //### Use hash table for this?
     public SourceModel sourceForFile(File path) {
-        Iterator iter = sourceList.iterator();
+        Iterator<SourceModel> iter = sourceList.iterator();
         SourceModel sm = null;
         while (iter.hasNext()) {
-            SourceModel candidate = (SourceModel)iter.next();
+            SourceModel candidate = iter.next();
             if (candidate.fileName().equals(path)) {
                 sm = candidate;
                 iter.remove();    // Will move to start of list.
--- a/src/share/classes/com/sun/tools/example/debug/gui/SourceModel.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/SourceModel.java	Fri Mar 28 03:06:00 2008 -0700
@@ -187,22 +187,17 @@
      * when sourceLines is set.
      */
     private void markClassLines(ReferenceType refType) {
-        List methods = refType.methods();
-        for (Iterator mit = methods.iterator(); mit.hasNext();) {
-            Method meth = (Method)mit.next();
+        for (Method meth : refType.methods()) {
             try {
-                List lines = meth.allLineLocations();
-                for (Iterator lit = lines.iterator(); lit.hasNext();) {
-                    Location loc = (Location)lit.next();
+                for (Location loc : meth.allLineLocations()) {
                     showExecutable(loc.lineNumber(), refType);
                 }
             } catch (AbsentInformationException exc) {
                 // do nothing
             }
         }
-        List bps = env.getExecutionManager().eventRequestManager().breakpointRequests();
-        for (Iterator it = bps.iterator(); it.hasNext();) {
-            BreakpointRequest bp = (BreakpointRequest)it.next();
+        for (BreakpointRequest bp :
+                 env.getExecutionManager().eventRequestManager().breakpointRequests()) {
             if (bp.location() != null) {
                 Location loc = bp.location();
                 if (loc.declaringType().equals(refType)) {
@@ -224,8 +219,8 @@
         } finally {
             reader.close();
         }
-        for (Iterator it = classes.iterator(); it.hasNext();) {
-            markClassLines((ClassType)it.next());
+        for (ReferenceType refType : classes) {
+            markClassLines(refType);
         }
     }
 
--- a/src/share/classes/com/sun/tools/example/debug/gui/StackTraceTool.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/StackTraceTool.java	Fri Mar 28 03:06:00 2008 -0700
@@ -139,7 +139,7 @@
                 String methName =
                     meth.declaringType().name() + '.' + meth.name();
                 String position = "";
-                if (meth instanceof Method && ((Method)meth).isNative()) {
+                if (meth.isNative()) {
                     position = " (native method)";
                 } else if (loc.lineNumber() != -1) {
                     position = ":" + loc.lineNumber();
--- a/src/share/classes/com/sun/tools/example/debug/gui/ThreadTreeTool.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/gui/ThreadTreeTool.java	Fri Mar 28 03:06:00 2008 -0700
@@ -133,9 +133,7 @@
 
         public void sessionStart(EventObject e) {
             try {
-                Iterator iter = runtime.allThreads().iterator();
-                while (iter.hasNext()) {
-                    ThreadReference thread = ((ThreadReference)iter.next());
+                for (ThreadReference thread : runtime.allThreads()) {
                     root.addThread(thread);
                 }
             } catch (VMDisconnectedException ee) {
@@ -244,16 +242,16 @@
             }
         }
 
-        private void addThread(List threadPath, ThreadReference thread) {
+        private void addThread(List<String> threadPath, ThreadReference thread) {
             int size = threadPath.size();
             if (size == 0) {
                 return;
             } else if (size == 1) {
-                String name = (String)threadPath.get(0);
+                String name = threadPath.get(0);
                 insertNode(name, thread);
             } else {
-                String head = (String)threadPath.get(0);
-                List tail = threadPath.subList(1, size);
+                String head = threadPath.get(0);
+                List<String> tail = threadPath.subList(1, size);
                 ThreadTreeNode child = insertNode(head, null);
                 child.addThread(tail, thread);
             }
@@ -288,17 +286,17 @@
             }
         }
 
-        private void removeThread(List threadPath, ThreadReference thread) {
+        private void removeThread(List<String> threadPath, ThreadReference thread) {
             int size = threadPath.size();
             if (size == 0) {
                 return;
             } else if (size == 1) {
-                String name = (String)threadPath.get(0);
+                String name = threadPath.get(0);
                 ThreadTreeNode child = findLeafNode(thread, name);
                 treeModel.removeNodeFromParent(child);
             } else {
-                String head = (String)threadPath.get(0);
-                List tail = threadPath.subList(1, size);
+                String head = threadPath.get(0);
+                List<String> tail = threadPath.subList(1, size);
                 ThreadTreeNode child = findInternalNode(head);
                 child.removeThread(tail, thread);
                 if (child.isThreadGroup() && child.getChildCount() < 1) {
--- a/src/share/classes/com/sun/tools/example/debug/tty/BreakpointSpec.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/BreakpointSpec.java	Fri Mar 28 03:06:00 2008 -0700
@@ -34,7 +34,7 @@
 
 class BreakpointSpec extends EventRequestSpec {
     String methodId;
-    List methodArgs;
+    List<String> methodArgs;
     int lineNumber;
 
     BreakpointSpec(ReferenceTypeSpec refSpec, int lineNumber) {
@@ -45,7 +45,7 @@
     }
 
     BreakpointSpec(ReferenceTypeSpec refSpec, String methodId,
-                   List methodArgs) throws MalformedMemberNameException {
+                   List<String> methodArgs) throws MalformedMemberNameException {
         super(refSpec);
         this.methodId = methodId;
         this.methodArgs = methodArgs;
@@ -83,7 +83,7 @@
         return lineNumber;
     }
 
-    List methodArgs() {
+    List<String> methodArgs() {
         return methodArgs;
     }
 
@@ -146,14 +146,13 @@
             buffer.append('.');
             buffer.append(methodId);
             if (methodArgs != null) {
-                Iterator iter = methodArgs.iterator();
                 boolean first = true;
                 buffer.append('(');
-                while (iter.hasNext()) {
+                for (String arg : methodArgs) {
                     if (!first) {
                         buffer.append(',');
                     }
-                    buffer.append((String)iter.next());
+                    buffer.append(arg);
                     first = false;
                 }
                 buffer.append(")");
@@ -176,12 +175,12 @@
             location = method.location();
         } else {
             // let AbsentInformationException be thrown
-            List locs = refType.locationsOfLine(lineNumber());
+            List<Location> locs = refType.locationsOfLine(lineNumber());
             if (locs.size() == 0) {
                 throw new LineNotFoundException();
             }
             // TO DO: handle multiple locations
-            location = (Location)locs.get(0);
+            location = locs.get(0);
             if (location.method() == null) {
                 throw new LineNotFoundException();
             }
@@ -202,8 +201,8 @@
      * and if the number of arguments in the method matches the
      * number of names passed
      */
-    private boolean compareArgTypes(Method method, List nameList) {
-        List argTypeNames = method.argumentTypeNames();
+    private boolean compareArgTypes(Method method, List<String> nameList) {
+        List<String> argTypeNames = method.argumentTypeNames();
 
         // If argument counts differ, we can stop here
         if (argTypeNames.size() != nameList.size()) {
@@ -213,8 +212,8 @@
         // Compare each argument type's name
         int nTypes = argTypeNames.size();
         for (int i = 0; i < nTypes; ++i) {
-            String comp1 = (String)argTypeNames.get(i);
-            String comp2 = (String)nameList.get(i);
+            String comp1 = argTypeNames.get(i);
+            String comp2 = nameList.get(i);
             if (! comp1.equals(comp2)) {
                 /*
                  * We have to handle varargs.  EG, the
@@ -331,22 +330,17 @@
         List<String> argTypeNames = null;
         if (methodArgs() != null) {
             argTypeNames = new ArrayList<String>(methodArgs().size());
-            Iterator iter = methodArgs().iterator();
-            while (iter.hasNext()) {
-                String name = (String)iter.next();
+            for (String name : methodArgs()) {
                 name = normalizeArgTypeName(name);
                 argTypeNames.add(name);
             }
         }
 
         // Check each method in the class for matches
-        Iterator iter = refType.methods().iterator();
         Method firstMatch = null;  // first method with matching name
         Method exactMatch = null;  // (only) method with same name & sig
         int matchCount = 0;        // > 1 implies overload
-        while (iter.hasNext()) {
-            Method candidate = (Method)iter.next();
-
+        for (Method candidate : refType.methods()) {
             if (candidate.name().equals(methodName())) {
                 matchCount++;
 
--- a/src/share/classes/com/sun/tools/example/debug/tty/Commands.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/Commands.java	Fri Mar 28 03:06:00 2008 -0700
@@ -157,16 +157,16 @@
         buf.append(method.name());
         buf.append("(");
 
-        List args = method.argumentTypeNames();
+        List<String> args = method.argumentTypeNames();
         int lastParam = args.size() - 1;
         // output param types except for the last
         for (int ii = 0; ii < lastParam; ii++) {
-            buf.append((String)args.get(ii));
+            buf.append(args.get(ii));
             buf.append(", ");
         }
         if (lastParam >= 0) {
             // output the last param
-            String lastStr = (String)args.get(lastParam);
+            String lastStr = args.get(lastParam);
             if (method.isVarArgs()) {
                 // lastParam is an array.  Replace the [] with ...
                 buf.append(lastStr.substring(0, lastStr.length() - 2));
@@ -180,12 +180,11 @@
     }
 
     void commandConnectors(VirtualMachineManager vmm) {
-        Iterator iter = vmm.allConnectors().iterator();
-        if (iter.hasNext()) {
+        Collection<Connector> ccs = vmm.allConnectors();
+        if (ccs.isEmpty()) {
             MessageOutput.println("Connectors available");
         }
-        while (iter.hasNext()) {
-            Connector cc = (Connector)iter.next();
+        for (Connector cc : ccs) {
             String transportName =
                 cc.transport() == null ? "null" : cc.transport().name();
             MessageOutput.println();
@@ -193,10 +192,7 @@
                                   new Object [] {cc.name(), transportName});
             MessageOutput.println("Connector description", cc.description());
 
-            Iterator argIter = cc.defaultArguments().values().iterator();
-            if (argIter.hasNext()) {
-                while (argIter.hasNext()) {
-                    Connector.Argument aa = (Connector.Argument)argIter.next();
+            for (Connector.Argument aa : cc.defaultArguments().values()) {
                     MessageOutput.println();
 
                     boolean requiredArgument = aa.mustSpecify();
@@ -215,16 +211,12 @@
 
                 }
             }
-        }
 
     }
 
     void commandClasses() {
-        List list = Env.vm().allClasses();
-
         StringBuffer classList = new StringBuffer();
-        for (int i = 0 ; i < list.size() ; i++) {
-            ReferenceType refType = (ReferenceType)list.get(i);
+        for (ReferenceType refType : Env.vm().allClasses()) {
             classList.append(refType.name());
             classList.append("\n");
         }
@@ -232,7 +224,7 @@
     }
 
     void commandClass(StringTokenizer t) {
-        List list = Env.vm().allClasses();
+        List<ReferenceType> list = Env.vm().allClasses();
 
         if (!t.hasMoreTokens()) {
             MessageOutput.println("No class specified.");
@@ -265,51 +257,31 @@
                 superclass = showAll ? superclass.superclass() : null;
             }
 
-            List interfaces = showAll ? clazz.allInterfaces()
-                                      : clazz.interfaces();
-            Iterator iter = interfaces.iterator();
-            while (iter.hasNext()) {
-                InterfaceType interfaze = (InterfaceType)iter.next();
+            List<InterfaceType> interfaces =
+                showAll ? clazz.allInterfaces() : clazz.interfaces();
+            for (InterfaceType interfaze : interfaces) {
                 MessageOutput.println("implements:", interfaze.name());
             }
 
-            List subs = clazz.subclasses();
-            iter = subs.iterator();
-            while (iter.hasNext()) {
-                ClassType sub = (ClassType)iter.next();
+            for (ClassType sub : clazz.subclasses()) {
                 MessageOutput.println("subclass:", sub.name());
             }
-            List nested = clazz.nestedTypes();
-            iter = nested.iterator();
-            while (iter.hasNext()) {
-                ReferenceType nest = (ReferenceType)iter.next();
+            for (ReferenceType nest : clazz.nestedTypes()) {
                 MessageOutput.println("nested:", nest.name());
             }
         } else if (type instanceof InterfaceType) {
             InterfaceType interfaze = (InterfaceType)type;
             MessageOutput.println("Interface:", interfaze.name());
-            List supers = interfaze.superinterfaces();
-            Iterator iter = supers.iterator();
-            while (iter.hasNext()) {
-                InterfaceType superinterface = (InterfaceType)iter.next();
+            for (InterfaceType superinterface : interfaze.superinterfaces()) {
                 MessageOutput.println("extends:", superinterface.name());
             }
-            List subs = interfaze.subinterfaces();
-            iter = subs.iterator();
-            while (iter.hasNext()) {
-                InterfaceType sub = (InterfaceType)iter.next();
+            for (InterfaceType sub : interfaze.subinterfaces()) {
                 MessageOutput.println("subinterface:", sub.name());
             }
-            List implementors = interfaze.implementors();
-            iter = implementors.iterator();
-            while (iter.hasNext()) {
-                ClassType implementor = (ClassType)iter.next();
+            for (ClassType implementor : interfaze.implementors()) {
                 MessageOutput.println("implementor:", implementor.name());
             }
-            List nested = interfaze.nestedTypes();
-            iter = nested.iterator();
-            while (iter.hasNext()) {
-                ReferenceType nest = (ReferenceType)iter.next();
+            for (ReferenceType nest : interfaze.nestedTypes()) {
                 MessageOutput.println("nested:", nest.name());
             }
         } else {  // array type
@@ -327,10 +299,8 @@
         String idClass = t.nextToken();
         ReferenceType cls = Env.getReferenceTypeFromToken(idClass);
         if (cls != null) {
-            List methods = cls.allMethods();
             StringBuffer methodsList = new StringBuffer();
-            for (int i = 0; i < methods.size(); i++) {
-                Method method = (Method)methods.get(i);
+            for (Method method : cls.allMethods()) {
                 methodsList.append(method.declaringType().name());
                 methodsList.append(" ");
                 methodsList.append(typedName(method));
@@ -351,11 +321,10 @@
         String idClass = t.nextToken();
         ReferenceType cls = Env.getReferenceTypeFromToken(idClass);
         if (cls != null) {
-            List fields = cls.allFields();
-            List visible = cls.visibleFields();
+            List<Field> fields = cls.allFields();
+            List<Field> visible = cls.visibleFields();
             StringBuffer fieldsList = new StringBuffer();
-            for (int i = 0; i < fields.size(); i++) {
-                Field field = (Field)fields.get(i);
+            for (Field field : fields) {
                 String s;
                 if (!visible.contains(field)) {
                     s = MessageOutput.format("list field typename and name hidden",
@@ -386,7 +355,7 @@
         int maxIdLength = 0;
         int maxNameLength = 0;
         while (threadIter.hasNext()) {
-            ThreadReference thr = (ThreadReference)threadIter.next();
+            ThreadReference thr = threadIter.next();
             maxIdLength = Math.max(maxIdLength,
                                    Env.description(thr).length());
             maxNameLength = Math.max(maxNameLength,
@@ -395,7 +364,7 @@
 
         threadIter = new ThreadIterator(tg);
         while (threadIter.hasNext()) {
-            ThreadReference thr = (ThreadReference)threadIter.next();
+            ThreadReference thr = threadIter.next();
             if (thr.threadGroup() == null) {
                 continue;
             }
@@ -588,9 +557,7 @@
     private List<ThreadReference> allThreads(ThreadGroupReference group) {
         List<ThreadReference> list = new ArrayList<ThreadReference>();
         list.addAll(group.threads());
-        Iterator iter = group.threadGroups().iterator();
-        while (iter.hasNext()) {
-            ThreadGroupReference child = (ThreadGroupReference)iter.next();
+        for (ThreadGroupReference child : group.threadGroups()) {
             list.addAll(allThreads(child));
         }
         return list;
@@ -641,10 +608,7 @@
          * if so, it gets removed here.
          */
          EventRequestManager mgr = Env.vm().eventRequestManager();
-         List requests = mgr.stepRequests();
-         Iterator iter = requests.iterator();
-         while (iter.hasNext()) {
-             StepRequest request = (StepRequest)iter.next();
+         for (StepRequest request : mgr.stepRequests()) {
              if (request.thread().equals(thread)) {
                  mgr.deleteEventRequest(request);
                  break;
@@ -768,9 +732,7 @@
         boolean noExceptions = true;
 
         // Print a listing of the catch patterns currently in place
-        Iterator iter = Env.specList.eventRequestSpecs().iterator();
-        while (iter.hasNext()) {
-            EventRequestSpec spec = (EventRequestSpec)iter.next();
+        for (EventRequestSpec spec : Env.specList.eventRequestSpecs()) {
             if (spec instanceof ExceptionSpec) {
                 if (noExceptions) {
                     noExceptions = false;
@@ -928,7 +890,7 @@
     }
 
     private void dumpStack(ThreadInfo threadInfo, boolean showPC) {
-        List stack = null;
+        List<StackFrame> stack = null;
         try {
             stack = threadInfo.getStack();
         } catch (IncompatibleThreadStateException e) {
@@ -940,7 +902,7 @@
         } else {
             int nFrames = stack.size();
             for (int i = threadInfo.getCurrentFrameIndex(); i < nFrames; i++) {
-                StackFrame frame = (StackFrame)stack.get(i);
+                StackFrame frame = stack.get(i);
                 dumpFrame (i, showPC, frame);
             }
         }
@@ -956,7 +918,7 @@
 
         long lineNumber = loc.lineNumber();
         String methodInfo = null;
-        if (meth instanceof Method && ((Method)meth).isNative()) {
+        if (meth.isNative()) {
             methodInfo = MessageOutput.format("native method");
         } else if (lineNumber != -1) {
             try {
@@ -994,9 +956,7 @@
         } else {
             String token = t.nextToken();
             if (token.toLowerCase().equals("all")) {
-                Iterator iter = ThreadInfo.threads().iterator();
-                while (iter.hasNext()) {
-                    ThreadInfo threadInfo = (ThreadInfo)iter.next();
+                for (ThreadInfo threadInfo : ThreadInfo.threads()) {
                     MessageOutput.println("Thread:",
                                           threadInfo.getThread().name());
                     dumpStack(threadInfo, showPC);
@@ -1051,9 +1011,7 @@
         boolean noBreakpoints = true;
 
         // Print set breakpoints
-        Iterator iter = Env.specList.eventRequestSpecs().iterator();
-        while (iter.hasNext()) {
-            EventRequestSpec spec = (EventRequestSpec)iter.next();
+        for (EventRequestSpec spec : Env.specList.eventRequestSpecs()) {
             if (spec instanceof BreakpointSpec) {
                 if (noBreakpoints) {
                     noBreakpoints = false;
@@ -1075,7 +1033,7 @@
 
     protected BreakpointSpec parseBreakpointSpec(StringTokenizer t,
                                              String atForm, String inForm) {
-        EventRequestSpec breakpoint = null;
+        BreakpointSpec breakpoint = null;
         try {
             String token = t.nextToken(":( \t\n\r");
 
@@ -1149,7 +1107,7 @@
             printBreakpointCommandUsage(atForm, inForm);
             return null;
         }
-        return (BreakpointSpec)breakpoint;
+        return breakpoint;
     }
 
     private void resolveNow(EventRequestSpec spec) {
@@ -1209,8 +1167,8 @@
         }
     }
 
-    private List<EventRequestSpec> parseWatchpointSpec(StringTokenizer t) {
-        List<EventRequestSpec> list = new ArrayList<EventRequestSpec>();
+    private List<WatchpointSpec> parseWatchpointSpec(StringTokenizer t) {
+        List<WatchpointSpec> list = new ArrayList<WatchpointSpec>();
         boolean access = false;
         boolean modification = false;
         int suspendPolicy = EventRequest.SUSPEND_ALL;
@@ -1242,7 +1200,7 @@
         fieldName = fieldName.substring(dot+1);
 
         try {
-            EventRequestSpec spec;
+            WatchpointSpec spec;
             if (access) {
                 spec = Env.specList.createAccessWatchpoint(className,
                                                            fieldName);
@@ -1269,9 +1227,8 @@
             return;
         }
 
-        Iterator iter = parseWatchpointSpec(t).iterator();
-        while (iter.hasNext()) {
-            resolveNow((WatchpointSpec)iter.next());
+        for (WatchpointSpec spec : parseWatchpointSpec(t)) {
+            resolveNow(spec);
         }
     }
 
@@ -1281,9 +1238,7 @@
             return;
         }
 
-        Iterator iter = parseWatchpointSpec(t).iterator();
-        while (iter.hasNext()) {
-            WatchpointSpec spec = (WatchpointSpec)iter.next();
+        for (WatchpointSpec spec : parseWatchpointSpec(t)) {
             if (Env.specList.delete(spec)) {
                 MessageOutput.println("Removed:", spec.toString());
             } else {
@@ -1482,7 +1437,7 @@
                     lineno = n.intValue();
                 } catch (java.text.ParseException jtpe) {
                     // It isn't -- see if it's a method name.
-                        List meths = refType.methodsByName(id);
+                        List<Method> meths = refType.methodsByName(id);
                         if (meths == null || meths.size() == 0) {
                             MessageOutput.println("is not a valid line number or method name for",
                                                   new Object [] {id, refType.name()});
@@ -1492,7 +1447,7 @@
                                                   new Object [] {id, refType.name()});
                             return;
                         }
-                        loc = ((Method)meths.get(0)).location();
+                        loc = meths.get(0).location();
                         lineno = loc.lineNumber();
                 }
             }
@@ -1539,14 +1494,11 @@
             try {
                 ReferenceType refType = Env.getReferenceTypeFromToken(idClass);
                 if (refType != null) {
-                    List lines = null;
+                    List<Location> lines = null;
                     if (idMethod == null) {
                         lines = refType.allLineLocations();
                     } else {
-                        List methods = refType.allMethods();
-                        Iterator iter = methods.iterator();
-                        while (iter.hasNext()) {
-                            Method method = (Method)iter.next();
+                        for (Method method : refType.allMethods()) {
                             if (method.name().equals(idMethod)) {
                                 lines = method.allLineLocations();
                             }
@@ -1555,9 +1507,7 @@
                             MessageOutput.println("is not a valid method name", idMethod);
                         }
                     }
-                    Iterator iter = lines.iterator();
-                    while (iter.hasNext()) {
-                        Location line = (Location)iter.next();
+                    for (Location line : lines) {
                         MessageOutput.printDirectln(line.toString());// Special case: use printDirectln()
                     }
                 } else {
@@ -1620,21 +1570,19 @@
                 MessageOutput.println("No local variables");
                 return;
             }
-            Map values = frame.getValues(vars);
+            Map<LocalVariable, Value> values = frame.getValues(vars);
 
             MessageOutput.println("Method arguments:");
-            for (Iterator it = vars.iterator(); it.hasNext(); ) {
-                LocalVariable var = (LocalVariable)it.next();
+            for (LocalVariable var : vars) {
                 if (var.isArgument()) {
-                    Value val = (Value)values.get(var);
+                    Value val = values.get(var);
                     printVar(var, val);
                 }
             }
             MessageOutput.println("Local variables:");
-            for (Iterator it = vars.iterator(); it.hasNext(); ) {
-                LocalVariable var = (LocalVariable)it.next();
+            for (LocalVariable var : vars) {
                 if (!var.isArgument()) {
-                    Value val = (Value)values.get(var);
+                    Value val = values.get(var);
                     printVar(var, val);
                 }
             }
@@ -1647,9 +1595,8 @@
 
     private void dump(ObjectReference obj, ReferenceType refType,
                       ReferenceType refTypeBase) {
-        for (Iterator it = refType.fields().iterator(); it.hasNext(); ) {
+        for (Field field : refType.fields()) {
             StringBuffer o = new StringBuffer();
-            Field field = (Field)it.next();
             o.append("    ");
             if (!refType.equals(refTypeBase)) {
                 o.append(refType.name());
@@ -1666,14 +1613,13 @@
                 dump(obj, sup, refTypeBase);
             }
         } else if (refType instanceof InterfaceType) {
-            List sups = ((InterfaceType)refType).superinterfaces();
-            for (Iterator it = sups.iterator(); it.hasNext(); ) {
-                dump(obj, (ReferenceType)it.next(), refTypeBase);
+            for (InterfaceType sup : ((InterfaceType)refType).superinterfaces()) {
+                dump(obj, sup, refTypeBase);
             }
         } else {
             /* else refType is an instanceof ArrayType */
             if (obj instanceof ArrayReference) {
-                for (Iterator it = ((ArrayReference)obj).getValues().iterator();
+                for (Iterator<Value> it = ((ArrayReference)obj).getValues().iterator();
                      it.hasNext(); ) {
                     MessageOutput.printDirect(it.next().toString());// Special case: use printDirect()
                     if (it.hasNext()) {
@@ -1770,13 +1716,11 @@
                                           new Object [] {owner.name(),
                                                          new Integer (object.entryCount())});
                 }
-                List waiters = object.waitingThreads();
+                List<ThreadReference> waiters = object.waitingThreads();
                 if (waiters.size() == 0) {
                     MessageOutput.println("No waiters");
                 } else {
-                    Iterator iter = waiters.iterator();
-                    while (iter.hasNext()) {
-                        ThreadReference waiter = (ThreadReference)iter.next();
+                    for (ThreadReference waiter : waiters) {
                         MessageOutput.println("Waiting thread:", waiter.name());
                     }
                 }
@@ -1800,13 +1744,11 @@
         ThreadReference thread = threadInfo.getThread();
         try {
             MessageOutput.println("Monitor information for thread", thread.name());
-            List owned = thread.ownedMonitors();
+            List<ObjectReference> owned = thread.ownedMonitors();
             if (owned.size() == 0) {
                 MessageOutput.println("No monitors owned");
             } else {
-                Iterator iter = owned.iterator();
-                while (iter.hasNext()) {
-                    ObjectReference monitor = (ObjectReference)iter.next();
+                for (ObjectReference monitor : owned) {
                     MessageOutput.println("Owned monitor:", monitor.toString());
                 }
             }
@@ -1833,9 +1775,7 @@
         }
         String token = t.nextToken();
         if (token.toLowerCase().equals("all")) {
-            Iterator iter = ThreadInfo.threads().iterator();
-            while (iter.hasNext()) {
-                ThreadInfo threadInfo = (ThreadInfo)iter.next();
+            for (ThreadInfo threadInfo : ThreadInfo.threads()) {
                 printThreadLockInfo(threadInfo);
             }
         } else {
@@ -1930,14 +1870,12 @@
 
     void commandSave(final StringTokenizer t) { // Undocumented command: useful for testing.
         if (!t.hasMoreTokens()) {
-            Set keys = Env.getSaveKeys();
-            Iterator iter = keys.iterator();
-            if (!iter.hasNext()) {
+            Set<String> keys = Env.getSaveKeys();
+            if (keys.isEmpty()) {
                 MessageOutput.println("No saved values");
                 return;
             }
-            while (iter.hasNext()) {
-                String key = (String)iter.next();
+            for (String key : keys) {
                 Value value = Env.getSavedValue(key);
                 if ((value instanceof ObjectReference) &&
                     ((ObjectReference)value).isCollected()) {
@@ -1976,7 +1914,7 @@
         // Overloading is not handled here.
         String methodName = t.nextToken();
 
-        List classes = Env.vm().classesByName(className);
+        List<ReferenceType> classes = Env.vm().classesByName(className);
         // TO DO: handle multiple classes found
         if (classes.size() == 0) {
             if (className.indexOf('.') < 0) {
@@ -1987,17 +1925,14 @@
             return;
         }
 
-        ReferenceType rt = (ReferenceType)classes.get(0);
+        ReferenceType rt = classes.get(0);
         if (!(rt instanceof ClassType)) {
             MessageOutput.println("not a class", className);
             return;
         }
 
         byte[] bytecodes = null;
-        List list = rt.methodsByName(methodName);
-        Iterator iter = list.iterator();
-        while (iter.hasNext()) {
-            Method method = (Method)iter.next();
+        for (Method method : rt.methodsByName(methodName)) {
             if (!method.isAbstract()) {
                 bytecodes = method.bytecodes();
                 break;
@@ -2047,7 +1982,7 @@
             MessageOutput.println("Specify classes to redefine");
         } else {
             String className = t.nextToken();
-            List classes = Env.vm().classesByName(className);
+            List<ReferenceType> classes = Env.vm().classesByName(className);
             if (classes.size() == 0) {
                 MessageOutput.println("No class named", className);
                 return;
@@ -2057,7 +1992,7 @@
                 return;
             }
             Env.setSourcePath(Env.getSourcePath());
-            ReferenceType refType = (ReferenceType)classes.get(0);
+            ReferenceType refType = classes.get(0);
             if (!t.hasMoreTokens()) {
                 MessageOutput.println("Specify file name for class", className);
                 return;
@@ -2074,7 +2009,8 @@
                              new Object [] {fileName, exc.toString()});
                 return;
             }
-            Map<ReferenceType, byte[]> map = new HashMap<ReferenceType, byte[]>();
+            Map<ReferenceType, byte[]> map
+                = new HashMap<ReferenceType, byte[]>();
             map.put(refType, bytes);
             try {
                 Env.vm().redefineClasses(map);
--- a/src/share/classes/com/sun/tools/example/debug/tty/Env.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/Env.java	Fri Mar 28 03:06:00 2008 -0700
@@ -89,7 +89,7 @@
         sourceCache.clear();
     }
 
-    static void setSourcePath(List srcList) {
+    static void setSourcePath(List<String> srcList) {
         sourceMapper = new SourceMapper(srcList);
         sourceCache.clear();
     }
@@ -106,10 +106,8 @@
     }
 
     static String excludesString() {
-        Iterator iter = excludes().iterator();
         StringBuffer buffer = new StringBuffer();
-        while (iter.hasNext()) {
-            String pattern = (String)iter.next();
+        for (String pattern : excludes()) {
             buffer.append(pattern);
             buffer.append(",");
         }
@@ -117,25 +115,19 @@
     }
 
     static void addExcludes(StepRequest request) {
-        Iterator iter = excludes().iterator();
-        while (iter.hasNext()) {
-            String pattern = (String)iter.next();
+        for (String pattern : excludes()) {
             request.addClassExclusionFilter(pattern);
         }
     }
 
     static void addExcludes(MethodEntryRequest request) {
-        Iterator iter = excludes().iterator();
-        while (iter.hasNext()) {
-            String pattern = (String)iter.next();
+        for (String pattern : excludes()) {
             request.addClassExclusionFilter(pattern);
         }
     }
 
     static void addExcludes(MethodExitRequest request) {
-        Iterator iter = excludes().iterator();
-        while (iter.hasNext()) {
-            String pattern = (String)iter.next();
+        for (String pattern : excludes()) {
             request.addClassExclusionFilter(pattern);
         }
     }
@@ -175,10 +167,10 @@
         try {
             String fileName = location.sourceName();
 
-            Iterator iter = sourceCache.iterator();
+            Iterator<SourceCode> iter = sourceCache.iterator();
             SourceCode code = null;
             while (iter.hasNext()) {
-                SourceCode candidate = (SourceCode)iter.next();
+                SourceCode candidate = iter.next();
                 if (candidate.fileName().equals(fileName)) {
                     code = candidate;
                     iter.remove();
@@ -269,10 +261,7 @@
         // loaded class whose name matches this limited regular
         // expression is selected.
         idToken = idToken.substring(1);
-        List classes = Env.vm().allClasses();
-        Iterator iter = classes.iterator();
-        while (iter.hasNext()) {
-            ReferenceType type = ((ReferenceType)iter.next());
+        for (ReferenceType type : Env.vm().allClasses()) {
             if (type.name().endsWith(idToken)) {
                 cls = type;
                 break;
@@ -280,21 +269,21 @@
         }
     } else {
             // It's a class name
-            List classes = Env.vm().classesByName(idToken);
+            List<ReferenceType> classes = Env.vm().classesByName(idToken);
             if (classes.size() > 0) {
                 // TO DO: handle multiples
-                cls = (ReferenceType)classes.get(0);
+                cls = classes.get(0);
             }
         }
         return cls;
     }
 
-    static Set getSaveKeys() {
+    static Set<String> getSaveKeys() {
         return savedValues.keySet();
     }
 
     static Value getSavedValue(String key) {
-        return (Value)savedValues.get(key);
+        return savedValues.get(key);
     }
 
     static void setSavedValue(String key, Value value) {
@@ -327,7 +316,7 @@
             if (index >= sourceLines.size()) {
                 return null;
             } else {
-                return (String)sourceLines.get(index);
+                return sourceLines.get(index);
             }
         }
     }
--- a/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java	Fri Mar 28 03:06:00 2008 -0700
@@ -150,7 +150,7 @@
                 EventSet eventSet = queue.remove();
                 EventIterator iter = eventSet.eventIterator();
                 while (iter.hasNext()) {
-                    handleExitEvent((Event)iter.next());
+                    handleExitEvent(iter.next());
                 }
             } catch (InterruptedException exc) {
                 // ignore
@@ -183,7 +183,7 @@
              * If any event in the set has a thread associated with it,
              * they all will, so just grab the first one.
              */
-            Event event = (Event)set.iterator().next(); // Is there a better way?
+            Event event = set.iterator().next(); // Is there a better way?
             thread = eventThread(event);
         } else {
             thread = null;
--- a/src/share/classes/com/sun/tools/example/debug/tty/EventRequestSpec.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/EventRequestSpec.java	Fri Mar 28 03:06:00 2008 -0700
@@ -101,10 +101,8 @@
                  * so that is all we need to examine.
                  */
                 ArrayList<ExceptionRequest> deleteList = new ArrayList<ExceptionRequest>();
-                Iterator iter =
-                    Env.vm().eventRequestManager().exceptionRequests().iterator();
-                while (iter.hasNext()) {
-                    ExceptionRequest er = (ExceptionRequest)iter.next();
+                for (ExceptionRequest er :
+                         Env.vm().eventRequestManager().exceptionRequests()) {
                     if (prs.matches(er.exception())) {
                         deleteList.add (er);
                     }
@@ -115,9 +113,7 @@
     }
 
     private EventRequest resolveAgainstPreparedClasses() throws Exception {
-        Iterator iter = Env.vm().allClasses().iterator();
-        while (iter.hasNext()) {
-            ReferenceType refType = (ReferenceType)iter.next();
+        for (ReferenceType refType : Env.vm().allClasses()) {
             if (refType.isPrepared() && refSpec.matches(refType)) {
                 resolved = resolveEventRequest(refType);
             }
--- a/src/share/classes/com/sun/tools/example/debug/tty/EventRequestSpecList.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/EventRequestSpecList.java	Fri Mar 28 03:06:00 2008 -0700
@@ -55,9 +55,7 @@
     boolean resolve(ClassPrepareEvent event) {
         boolean failure = false;
         synchronized(eventRequestSpecs) {
-            Iterator iter = eventRequestSpecs.iterator();
-            while (iter.hasNext()) {
-                EventRequestSpec spec = (EventRequestSpec)iter.next();
+            for (EventRequestSpec spec : eventRequestSpecs) {
                 if (!spec.isResolved()) {
                     try {
                         EventRequest eventRequest = spec.resolve(event);
@@ -77,9 +75,7 @@
     }
 
     void resolveAll() {
-        Iterator iter = eventRequestSpecs.iterator();
-        while (iter.hasNext()) {
-            EventRequestSpec spec = (EventRequestSpec)iter.next();
+        for (EventRequestSpec spec : eventRequestSpecs) {
             try {
                 EventRequest eventRequest = spec.resolveEagerly();
                 if (eventRequest != null) {
@@ -106,16 +102,16 @@
         }
     }
 
-    EventRequestSpec createBreakpoint(String classPattern,
-                                 int line) throws ClassNotFoundException {
+    BreakpointSpec createBreakpoint(String classPattern, int line)
+        throws ClassNotFoundException {
         ReferenceTypeSpec refSpec =
             new PatternReferenceTypeSpec(classPattern);
         return new BreakpointSpec(refSpec, line);
     }
 
-    EventRequestSpec createBreakpoint(String classPattern,
+    BreakpointSpec createBreakpoint(String classPattern,
                                  String methodId,
-                                 List methodArgs)
+                                    List<String> methodArgs)
                                 throws MalformedMemberNameException,
                                        ClassNotFoundException {
         ReferenceTypeSpec refSpec =
@@ -132,7 +128,7 @@
         return new ExceptionSpec(refSpec, notifyCaught, notifyUncaught);
     }
 
-    EventRequestSpec createAccessWatchpoint(String classPattern,
+    WatchpointSpec createAccessWatchpoint(String classPattern,
                                        String fieldId)
                                       throws MalformedMemberNameException,
                                              ClassNotFoundException {
@@ -141,7 +137,7 @@
         return new AccessWatchpointSpec(refSpec, fieldId);
     }
 
-    EventRequestSpec createModificationWatchpoint(String classPattern,
+    WatchpointSpec createModificationWatchpoint(String classPattern,
                                        String fieldId)
                                       throws MalformedMemberNameException,
                                              ClassNotFoundException {
@@ -154,7 +150,7 @@
         synchronized (eventRequestSpecs) {
             int inx = eventRequestSpecs.indexOf(proto);
             if (inx != -1) {
-                EventRequestSpec spec = (EventRequestSpec)eventRequestSpecs.get(inx);
+                EventRequestSpec spec = eventRequestSpecs.get(inx);
                 spec.remove();
                 eventRequestSpecs.remove(inx);
                 return true;
--- a/src/share/classes/com/sun/tools/example/debug/tty/SourceMapper.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/SourceMapper.java	Fri Mar 28 03:06:00 2008 -0700
@@ -39,15 +39,13 @@
 
     private final String[] dirs;
 
-    SourceMapper(List sourcepath) {
+    SourceMapper(List<String> sourcepath) {
         /*
          * sourcepath can arrive from the debugee as a List.
          * (via PathSearchingVirtualMachine.classPath())
          */
         List<String> dirList = new ArrayList<String>();
-        Iterator iter = sourcepath.iterator();
-        while (iter.hasNext()) {
-            String element = (String)iter.next();
+        for (String element : sourcepath) {
             //XXX remove .jar and .zip files; we want only directories on
             //the source path. (Bug ID 4186582)
             if ( ! (element.endsWith(".jar") ||
@@ -55,7 +53,7 @@
                 dirList.add(element);
             }
         }
-        dirs = (String[])dirList.toArray(new String[0]);
+        dirs = dirList.toArray(new String[0]);
     }
 
     SourceMapper(String sourcepath) {
@@ -79,7 +77,7 @@
                 dirList.add(s);
             }
         }
-        dirs = (String[])dirList.toArray(new String[0]);
+        dirs = dirList.toArray(new String[0]);
     }
 
     /*
--- a/src/share/classes/com/sun/tools/example/debug/tty/TTY.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/TTY.java	Fri Mar 28 03:06:00 2008 -0700
@@ -160,9 +160,7 @@
                 // here the next time.
                 Env.setAtExitMethod(null);
                 EventRequestManager erm = Env.vm().eventRequestManager();
-                Iterator it = erm.methodExitRequests().iterator();
-                while (it.hasNext()) {
-                    EventRequest eReq = (EventRequest)it.next();
+                for (EventRequest eReq : erm.methodExitRequests()) {
                     if (eReq.equals(me.request())) {
                         eReq.disable();
                     }
@@ -178,9 +176,8 @@
     public void vmInterrupted() {
         Thread.yield();  // fetch output
         printCurrentLocation();
-        Iterator it = monitorCommands.iterator();
-        while (it.hasNext()) {
-            StringTokenizer t = new StringTokenizer((String)it.next());
+        for (String cmd : monitorCommands) {
+            StringTokenizer t = new StringTokenizer(cmd);
             t.nextToken();  // get rid of monitor number
             executeCommand(t);
         }
@@ -563,9 +560,8 @@
             ++monitorCount;
             monitorCommands.add(monitorCount + ": " + t.nextToken(""));
         } else {
-            Iterator it = monitorCommands.iterator();
-            while (it.hasNext()) {
-                MessageOutput.printDirectln((String)it.next());// Special case: use printDirectln()
+            for (String cmd : monitorCommands) {
+                MessageOutput.printDirectln(cmd);// Special case: use printDirectln()
             }
         }
     }
@@ -581,9 +577,7 @@
                 return;
             }
             String monStr = monTok + ":";
-            Iterator it = monitorCommands.iterator();
-            while (it.hasNext()) {
-                String cmd = (String)it.next();
+            for (String cmd : monitorCommands) {
                 StringTokenizer ct = new StringTokenizer(cmd);
                 if (ct.nextToken().equals(monStr)) {
                     monitorCommands.remove(cmd);
@@ -768,10 +762,8 @@
     }
 
     private static boolean supportsSharedMemory() {
-        List connectors = Bootstrap.virtualMachineManager().allConnectors();
-        Iterator iter = connectors.iterator();
-        while (iter.hasNext()) {
-            Connector connector = (Connector)iter.next();
+        for (Connector connector :
+                 Bootstrap.virtualMachineManager().allConnectors()) {
             if (connector.transport() == null) {
                 continue;
             }
--- a/src/share/classes/com/sun/tools/example/debug/tty/ThreadGroupIterator.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/ThreadGroupIterator.java	Fri Mar 28 03:06:00 2008 -0700
@@ -36,7 +36,7 @@
  * Descend the tree of thread groups.
  * @author Robert G. Field
  */
-class ThreadGroupIterator implements Iterator {
+class ThreadGroupIterator implements Iterator<ThreadGroupReference> {
     private final Stack<Iterator<ThreadGroupReference>> stack = new Stack<Iterator<ThreadGroupReference>>();
 
     ThreadGroupIterator(List<ThreadGroupReference> tgl) {
@@ -53,8 +53,8 @@
         this(Env.vm().topLevelThreadGroups());
     }
 
-    private Iterator top() {
-        return (Iterator)stack.peek();
+    private Iterator<ThreadGroupReference> top() {
+        return stack.peek();
     }
 
     /**
@@ -74,12 +74,12 @@
         return !stack.isEmpty();
     }
 
-    public Object next() {
+    public ThreadGroupReference next() {
         return nextThreadGroup();
     }
 
     public ThreadGroupReference nextThreadGroup() {
-        ThreadGroupReference tg = (ThreadGroupReference)top().next();
+        ThreadGroupReference tg = top().next();
         push(tg.threadGroups());
         return tg;
     }
--- a/src/share/classes/com/sun/tools/example/debug/tty/ThreadInfo.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/ThreadInfo.java	Fri Mar 28 03:06:00 2008 -0700
@@ -56,9 +56,7 @@
 
     private static void initThreads() {
         if (!gotInitialThreads) {
-            Iterator iter = Env.vm().allThreads().iterator();
-            while (iter.hasNext()) {
-                ThreadReference thread = (ThreadReference)iter.next();
+            for (ThreadReference thread : Env.vm().allThreads()) {
                 threads.add(new ThreadInfo(thread));
             }
             gotInitialThreads = true;
@@ -113,9 +111,7 @@
         current = null;
         group = null;
         synchronized (threads) {
-            Iterator iter = threads().iterator();
-            while (iter.hasNext()) {
-                ThreadInfo ti = (ThreadInfo)iter.next();
+            for (ThreadInfo ti : threads()) {
                 ti.invalidate();
             }
         }
@@ -163,8 +159,7 @@
         if (group == null) {
             // Current thread group defaults to the first top level
             // thread group.
-            setThreadGroup((ThreadGroupReference)
-                           Env.vm().topLevelThreadGroups().get(0));
+            setThreadGroup(Env.vm().topLevelThreadGroups().get(0));
         }
         return group;
     }
@@ -173,9 +168,7 @@
         ThreadInfo retInfo = null;
 
         synchronized (threads) {
-            Iterator iter = threads().iterator();
-            while (iter.hasNext()) {
-                ThreadInfo ti  = (ThreadInfo)iter.next();
+            for (ThreadInfo ti : threads()) {
                 if (ti.thread.uniqueID() == id) {
                    retInfo = ti;
                    break;
@@ -208,7 +201,7 @@
      *
      * @return a <code>List</code> of the stack frames.
      */
-    List getStack() throws IncompatibleThreadStateException {
+    List<StackFrame> getStack() throws IncompatibleThreadStateException {
         return thread.frames();
     }
 
--- a/src/share/classes/com/sun/tools/example/debug/tty/ThreadIterator.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/ThreadIterator.java	Fri Mar 28 03:06:00 2008 -0700
@@ -30,8 +30,8 @@
 import java.util.List;
 import java.util.Iterator;
 
-class ThreadIterator implements Iterator {
-    Iterator it = null;
+class ThreadIterator implements Iterator<ThreadReference> {
+    Iterator<ThreadReference> it = null;
     ThreadGroupIterator tgi;
 
     ThreadIterator(ThreadGroupReference tg) {
@@ -56,12 +56,12 @@
         return true;
     }
 
-    public Object next() {
+    public ThreadReference next() {
         return it.next();
     }
 
     public ThreadReference nextThread() {
-        return (ThreadReference)next();
+        return next();
     }
 
     public void remove() {
--- a/src/share/classes/com/sun/tools/example/debug/tty/VMConnection.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/VMConnection.java	Fri Mar 28 03:06:00 2008 -0700
@@ -61,10 +61,8 @@
     }
 
     private Connector findConnector(String name) {
-        List connectors = Bootstrap.virtualMachineManager().allConnectors();
-        Iterator iter = connectors.iterator();
-        while (iter.hasNext()) {
-            Connector connector = (Connector)iter.next();
+        for (Connector connector :
+                 Bootstrap.virtualMachineManager().allConnectors()) {
             if (connector.name().equals(name)) {
                 return connector;
             }
@@ -108,7 +106,7 @@
             String value = token.substring(index + 1,
                                            token.length() - 1); // Remove comma delimiter
 
-            Connector.Argument argument = (Connector.Argument)arguments.get(name);
+            Connector.Argument argument = arguments.get(name);
             if (argument == null) {
                 throw new IllegalArgumentException
                     (MessageOutput.format("Argument is not defined for connector:",
@@ -195,7 +193,7 @@
             return false;
         }
 
-        Connector.Argument argument = (Connector.Argument)connectorArgs.get(name);
+        Connector.Argument argument = connectorArgs.get(name);
         if (argument == null) {
             return false;
         }
@@ -204,7 +202,7 @@
     }
 
     String connectorArg(String name) {
-        Connector.Argument argument = (Connector.Argument)connectorArgs.get(name);
+        Connector.Argument argument = connectorArgs.get(name);
         if (argument == null) {
             return "";
         }
--- a/src/share/classes/com/sun/tools/hat/internal/server/ClassQuery.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/hat/internal/server/ClassQuery.java	Fri Mar 28 03:06:00 2008 -0700
@@ -99,8 +99,7 @@
         }
 
         out.println("<h2>Instance Data Members:</h2>");
-        JavaField[] ff = clazz.getFields();
-        ff = (JavaField[]) ff.clone();
+        JavaField[] ff = clazz.getFields().clone();
         ArraySorter.sort(ff, new Comparer() {
             public int compare(Object lhs, Object rhs) {
                 JavaField left = (JavaField) lhs;
--- a/src/share/classes/com/sun/tools/hat/internal/server/PlatformClasses.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/hat/internal/server/PlatformClasses.java	Fri Mar 28 03:06:00 2008 -0700
@@ -90,9 +90,7 @@
                     // is the right thing to do anyway.
                 }
             }
-            int num = list.size();
-            names = new String[num];
-            names = (String[]) list.toArray(names);
+            names = list.toArray(new String[list.size()]);
         }
         return names;
     }
--- a/src/share/classes/com/sun/tools/jdi/AbstractLauncher.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/AbstractLauncher.java	Fri Mar 28 03:06:00 2008 -0700
@@ -119,7 +119,7 @@
 
         String[] tokenArray = new String[tokenList.size()];
         for (int i = 0; i < tokenList.size(); i++) {
-            tokenArray[i] = (String)tokenList.get(i);
+            tokenArray[i] = tokenList.get(i);
         }
         return tokenArray;
     }
--- a/src/share/classes/com/sun/tools/jdi/ClassTypeImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/ClassTypeImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -95,11 +95,8 @@
     }
 
     public List<ClassType> subclasses() {
-        List<ReferenceType> all = vm.allClasses();
         List<ClassType> subs = new ArrayList<ClassType>();
-        Iterator iter = all.iterator();
-        while (iter.hasNext()) {
-            ReferenceType refType = (ReferenceType)iter.next();
+        for (ReferenceType refType : vm.allClasses()) {
             if (refType instanceof ClassType) {
                 ClassType clazz = (ClassType)refType;
                 ClassType superclass = clazz.superclass();
@@ -223,7 +220,7 @@
 
         List<? extends Value> arguments = method.validateAndPrepareArgumentsForInvoke(origArguments);
 
-        ValueImpl[] args = (ValueImpl[])arguments.toArray(new ValueImpl[0]);
+        ValueImpl[] args = arguments.toArray(new ValueImpl[0]);
         JDWP.ClassType.InvokeMethod ret;
         try {
             PacketStream stream =
@@ -271,7 +268,7 @@
 
         List<Value> arguments = method.validateAndPrepareArgumentsForInvoke(
                                                        origArguments);
-        ValueImpl[] args = (ValueImpl[])arguments.toArray(new ValueImpl[0]);
+        ValueImpl[] args = arguments.toArray(new ValueImpl[0]);
         JDWP.ClassType.NewInstance ret = null;
         try {
             PacketStream stream =
@@ -301,11 +298,8 @@
     }
 
     public Method concreteMethodByName(String name, String signature)  {
-       List methods = visibleMethods();
        Method method = null;
-       Iterator iter = methods.iterator();
-       while (iter.hasNext()) {
-           Method candidate = (Method)iter.next();
+       for (Method candidate : visibleMethods()) {
            if (candidate.name().equals(name) &&
                candidate.signature().equals(signature) &&
                !candidate.isAbstract()) {
@@ -330,9 +324,7 @@
          * Avoid duplicate checking on each method by iterating through
          * duplicate-free allInterfaces() rather than recursing
          */
-        Iterator iter = allInterfaces().iterator();
-        while (iter.hasNext()) {
-            InterfaceType interfaze = (InterfaceType)iter.next();
+        for (InterfaceType interfaze : allInterfaces()) {
             list.addAll(interfaze.methods());
         }
 
--- a/src/share/classes/com/sun/tools/jdi/ConcreteMethodImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/ConcreteMethodImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -247,7 +247,7 @@
 
     public byte[] bytecodes() {
         byte[] bytecodes = (bytecodesRef == null) ? null :
-                                     (byte[])bytecodesRef.get();
+                                     bytecodesRef.get();
         if (bytecodes == null) {
             try {
                 bytecodes = JDWP.Method.Bytecodes.
@@ -262,7 +262,7 @@
          * to return the cached bytecodes directly; instead, we
          * make a clone at the cost of using more memory.
          */
-        return (byte[])bytecodes.clone();
+        return bytecodes.clone();
     }
 
     int argSlotCount() throws AbsentInformationException {
@@ -279,7 +279,7 @@
         String stratumID = stratum.id();
         SoftLocationXRefs info =
             (softOtherLocationXRefsRef == null) ? null :
-               (SoftLocationXRefs)softOtherLocationXRefsRef.get();
+               softOtherLocationXRefsRef.get();
         if (info != null && info.stratumID.equals(stratumID)) {
             return info;
         }
@@ -348,7 +348,7 @@
 
     private SoftLocationXRefs getBaseLocations() {
         SoftLocationXRefs info = (softBaseLocationXRefsRef == null) ? null :
-                                     (SoftLocationXRefs)softBaseLocationXRefsRef.get();
+                                     softBaseLocationXRefsRef.get();
         if (info != null) {
             return info;
         }
--- a/src/share/classes/com/sun/tools/jdi/EventSetImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/EventSetImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -56,10 +56,8 @@
     public String toString() {
         String string = "event set, policy:" + suspendPolicy +
                         ", count:" + this.size() + " = {";
-        Iterator iter = this.iterator();
         boolean first = true;
-        while (iter.hasNext()) {
-            Event event = (Event)iter.next();
+        for (Event event : this) {
             if (!first) {
                 string += ", ";
             }
@@ -787,9 +785,7 @@
     }
 
     private ThreadReference eventThread() {
-        Iterator iter = this.iterator();
-        while (iter.hasNext()) {
-            Event event = (Event)iter.next();
+        for (Event event : this) {
             if (event instanceof ThreadedEventImpl) {
                 return ((ThreadedEventImpl)event).thread();
             }
@@ -846,7 +842,7 @@
         }
 
         public Event nextEvent() {
-            return (Event)next();
+            return next();
         }
 
         public void remove() {
--- a/src/share/classes/com/sun/tools/jdi/JNITypeParser.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/JNITypeParser.java	Fri Mar 28 03:06:00 2008 -0700
@@ -82,7 +82,7 @@
     }
 
     String typeName() {
-        return (String)typeNameList().get(typeNameList().size()-1);
+        return typeNameList().get(typeNameList().size()-1);
     }
 
     List<String> argumentTypeNames() {
@@ -90,7 +90,7 @@
     }
 
     String signature() {
-        return (String)signatureList().get(signatureList().size()-1);
+        return signatureList().get(signatureList().size()-1);
     }
 
     List<String> argumentSignatures() {
--- a/src/share/classes/com/sun/tools/jdi/MethodImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/MethodImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -158,7 +158,7 @@
 
     Type argumentType(int index) throws ClassNotLoadedException {
         ReferenceTypeImpl enclosing = (ReferenceTypeImpl)declaringType();
-        String signature = (String)argumentSignatures().get(index);
+        String signature = argumentSignatures().get(index);
         return enclosing.findType(signature);
     }
 
@@ -263,10 +263,10 @@
             return argumentType(index);
         }
         public String typeName(){
-            return (String)argumentTypeNames().get(index);
+            return argumentTypeNames().get(index);
         }
         public String signature() {
-            return (String)argumentSignatures().get(index);
+            return argumentSignatures().get(index);
         }
         public Type findType(String signature) throws ClassNotLoadedException {
             return MethodImpl.this.findType(signature);
@@ -307,7 +307,7 @@
             arguments.add(argArray);
             return;
         }
-        Value nthArgValue = (Value)arguments.get(paramCount - 1);
+        Value nthArgValue = arguments.get(paramCount - 1);
         if (nthArgValue == null) {
             return;
         }
@@ -371,7 +371,7 @@
         }
 
         for (int i = 0; i < argSize; i++) {
-            Value value = (Value)arguments.get(i);
+            Value value = arguments.get(i);
             value = ValueImpl.prepareForAssignment(value,
                                                    new ArgumentContainer(i));
             arguments.set(i, value);
@@ -386,11 +386,11 @@
         sb.append(name());
         sb.append("(");
         boolean first = true;
-        for (Iterator it = argumentTypeNames().iterator(); it.hasNext();) {
+        for (String name : argumentTypeNames()) {
             if (!first) {
                 sb.append(", ");
             }
-            sb.append((String)it.next());
+            sb.append(name);
             first = false;
         }
         sb.append(")");
--- a/src/share/classes/com/sun/tools/jdi/ObjectReferenceImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/ObjectReferenceImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -383,7 +383,7 @@
         List<Value> arguments = method.validateAndPrepareArgumentsForInvoke(
                                                   origArguments);
 
-        ValueImpl[] args = (ValueImpl[])arguments.toArray(new ValueImpl[0]);
+        ValueImpl[] args = arguments.toArray(new ValueImpl[0]);
         JDWP.ObjectReference.InvokeMethod ret;
         try {
             PacketStream stream =
@@ -583,7 +583,7 @@
         // Validate assignment
         ReferenceType destType = (ReferenceTypeImpl)destination.type();
         ReferenceTypeImpl myType = (ReferenceTypeImpl)referenceType();
-        if (!myType.isAssignableTo((ReferenceType)destType)) {
+        if (!myType.isAssignableTo(destType)) {
             JNITypeParser parser = new JNITypeParser(destType.signature());
             String destTypeName = parser.typeName();
             throw new InvalidTypeException("Can't assign " +
--- a/src/share/classes/com/sun/tools/jdi/PacketStream.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/PacketStream.java	Fri Mar 28 03:06:00 2008 -0700
@@ -485,7 +485,7 @@
      * Read field represented as vm specific byte sequence.
      */
     Field readField() {
-        ReferenceTypeImpl refType = (ReferenceTypeImpl)readReferenceType();
+        ReferenceTypeImpl refType = readReferenceType();
         long fieldRef = readFieldRef();
         return refType.getFieldMirror(fieldRef);
     }
--- a/src/share/classes/com/sun/tools/jdi/ReferenceTypeImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/ReferenceTypeImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -59,7 +59,7 @@
     private boolean constantPoolInfoGotten = false;
     private int constanPoolCount;
     private byte[] constantPoolBytes;
-    private SoftReference constantPoolBytesRef = null;
+    private SoftReference<byte[]> constantPoolBytesRef = null;
 
     /* to mark a SourceFile request that returned a genuine JDWP.Error.ABSENT_INFORMATION */
     private static final String ABSENT_BASE_SOURCE_NAME = "**ABSENT_BASE_SOURCE_NAME**";
@@ -352,13 +352,10 @@
     abstract List<? extends ReferenceType> inheritedTypes();
 
     void addVisibleFields(List<Field> visibleList, Map<String, Field> visibleTable, List<String> ambiguousNames) {
-        List<Field> list = visibleFields();
-        Iterator iter = list.iterator();
-        while (iter.hasNext()) {
-            Field field = (Field)iter.next();
+        for (Field field : visibleFields()) {
             String name = field.name();
             if (!ambiguousNames.contains(name)) {
-                Field duplicate = (Field)visibleTable.get(name);
+                Field duplicate = visibleTable.get(name);
                 if (duplicate == null) {
                     visibleList.add(field);
                     visibleTable.put(name, field);
@@ -402,10 +399,8 @@
          * hide.
          */
         List<Field> retList = new ArrayList<Field>(fields());
-        iter = retList.iterator();
-        while (iter.hasNext()) {
-            Field field = (Field)iter.next();
-            Field hidden = (Field)visibleTable.get(field.name());
+        for (Field field : retList) {
+            Field hidden = visibleTable.get(field.name());
             if (hidden != null) {
                 visibleList.remove(hidden);
             }
@@ -515,12 +510,9 @@
      * methods.
      */
     void addToMethodMap(Map<String, Method> methodMap, List<Method> methodList) {
-        Iterator iter = methodList.iterator();
-        while (iter.hasNext()) {
-            Method method = (Method)iter.next();
+        for (Method method : methodList)
             methodMap.put(method.name().concat(method.signature()), method);
         }
-    }
 
     abstract void addVisibleMethods(Map<String, Method> methodMap);
 
@@ -549,9 +541,7 @@
     public List<Method> methodsByName(String name) {
         List<Method> methods = visibleMethods();
         ArrayList<Method> retList = new ArrayList<Method>(methods.size());
-        Iterator iter = methods.iterator();
-        while (iter.hasNext()) {
-            Method candidate = (Method)iter.next();
+        for (Method candidate : methods) {
             if (candidate.name().equals(name)) {
                 retList.add(candidate);
             }
@@ -563,9 +553,7 @@
     public List<Method> methodsByName(String name, String signature) {
         List<Method> methods = visibleMethods();
         ArrayList<Method> retList = new ArrayList<Method>(methods.size());
-        Iterator iter = methods.iterator();
-        while (iter.hasNext()) {
-            Method candidate = (Method)iter.next();
+        for (Method candidate : methods) {
             if (candidate.name().equals(name) &&
                 candidate.signature().equals(signature)) {
                 retList.add(candidate);
@@ -706,7 +694,7 @@
     }
 
     public String sourceName() throws AbsentInformationException {
-        return (String)(sourceNames(vm.getDefaultStratum()).get(0));
+        return sourceNames(vm.getDefaultStratum()).get(0);
     }
 
     public List<String> sourceNames(String stratumID)
@@ -796,7 +784,7 @@
         if (!vm.canGetSourceDebugExtension()) {
             return NO_SDE_INFO_MARK;
         }
-        SDE sde = (sdeRef == null) ?  null : (SDE)sdeRef.get();
+        SDE sde = (sdeRef == null) ?  null : sdeRef.get();
         if (sde == null) {
             String extension = null;
             try {
@@ -1034,13 +1022,13 @@
             throw exc;
         }
         if (constantPoolBytesRef != null) {
-            byte[] cpbytes = (byte[])constantPoolBytesRef.get();
+            byte[] cpbytes = constantPoolBytesRef.get();
             /*
              * Arrays are always modifiable, so it is a little unsafe
              * to return the cached bytecodes directly; instead, we
              * make a clone at the cost of using more memory.
              */
-            return (byte[])cpbytes.clone();
+            return cpbytes.clone();
         } else {
             return null;
         }
--- a/src/share/classes/com/sun/tools/jdi/SDE.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/SDE.java	Fri Mar 28 03:06:00 2008 -0700
@@ -327,7 +327,7 @@
 
         ignoreWhite();
         while (((ch = sdeRead()) != '\n') && (ch != '\r')) {
-            sb.append((char)ch);
+            sb.append(ch);
         }
         // check for CR LF
         if ((ch == '\r') && (sdePeek() == '\n')) {
--- a/src/share/classes/com/sun/tools/jdi/StackFrameImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/StackFrameImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -162,7 +162,7 @@
             for (LocalVariable variable : allVariables) {
                 String name = variable.name();
                 if (variable.isVisible(this)) {
-                    LocalVariable existing = (LocalVariable)map.get(name);
+                    LocalVariable existing = map.get(name);
                     if ((existing == null) ||
                         ((LocalVariableImpl)variable).hides(existing)) {
                         map.put(name, variable);
@@ -330,7 +330,7 @@
             slot = 1;
         }
         for (int ii = 0; ii < count; ++ii) {
-            char sigChar =  (char)argSigs.get(ii).charAt(0);
+            char sigChar = argSigs.get(ii).charAt(0);
             slots[ii] = new JDWP.StackFrame.GetValues.SlotInfo(slot++,(byte)sigChar);
             if (sigChar == 'J' || sigChar == 'D') {
                 slot++;
--- a/src/share/classes/com/sun/tools/jdi/TargetVM.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/TargetVM.java	Fri Mar 28 03:06:00 2008 -0700
@@ -148,7 +148,7 @@
                 idString = String.valueOf(p.id);
 
                 synchronized(waitingQueue) {
-                    p2 = (Packet)waitingQueue.get(idString);
+                    p2 = waitingQueue.get(idString);
 
                     if (p2 != null)
                         waitingQueue.remove(idString);
--- a/src/share/classes/com/sun/tools/jdi/ThreadGroupReferenceImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/ThreadGroupReferenceImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -86,30 +86,22 @@
     }
 
     public void suspend() {
-        List threads = threads();
-        Iterator iter = threads.iterator();
-        while (iter.hasNext()) {
-                ((ThreadReference)iter.next()).suspend();
+        for (ThreadReference thread : threads()) {
+            thread.suspend();
         }
 
-        List groups = threadGroups();
-        iter = groups.iterator();
-        while (iter.hasNext()) {
-                ((ThreadGroupReference)iter.next()).suspend();
+        for (ThreadGroupReference threadGroup : threadGroups()) {
+            threadGroup.suspend();
         }
     }
 
     public void resume() {
-        List threads = threads();
-        Iterator iter = threads.iterator();
-        while (iter.hasNext()) {
-                ((ThreadReference)iter.next()).resume();
+        for (ThreadReference thread : threads()) {
+            thread.resume();
         }
 
-        List groups = threadGroups();
-        iter = groups.iterator();
-        while (iter.hasNext()) {
-                ((ThreadGroupReference)iter.next()).resume();
+        for (ThreadGroupReference threadGroup : threadGroups()) {
+            threadGroup.resume();
         }
     }
 
--- a/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1191,8 +1191,7 @@
                 }
                 requests = new JDWP.VirtualMachine.DisposeObjects.Request[size];
                 for (int i = 0; i < requests.length; i++) {
-                    SoftObjectReference ref =
-                        (SoftObjectReference)batchedDisposeRequests.get(i);
+                    SoftObjectReference ref = batchedDisposeRequests.get(i);
                     if ((traceFlags & TRACE_OBJREFS) != 0) {
                         printTrace("Disposing object " + ref.key().longValue() +
                                    " (ref count = " + ref.count() + ")");
@@ -1436,7 +1435,7 @@
        }
 
        ObjectReferenceImpl object() {
-           return (ObjectReferenceImpl)get();
+           return get();
        }
    }
 }
--- a/src/share/classes/com/sun/tools/jdi/VirtualMachineManagerImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/com/sun/tools/jdi/VirtualMachineManagerImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -92,7 +92,7 @@
             Connector connector;
 
             try {
-                connector = (Connector)connectors.next();
+                connector = connectors.next();
             } catch (ThreadDeath x) {
                 throw x;
             } catch (Exception x) {
@@ -121,7 +121,7 @@
             TransportService transportService;
 
             try {
-                transportService = (TransportService)transportServices.next();
+                transportService = transportServices.next();
             } catch (ThreadDeath x) {
                 throw x;
             } catch (Exception x) {
--- a/src/share/classes/java/io/FileInputStream.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/io/FileInputStream.java	Fri Mar 28 03:06:00 2008 -0700
@@ -48,15 +48,15 @@
 class FileInputStream extends InputStream
 {
     /* File Descriptor - handle to the open file */
-    private FileDescriptor fd;
+    private final FileDescriptor fd;
 
     private FileChannel channel = null;
 
-    private Object closeLock = new Object();
+    private final Object closeLock = new Object();
     private volatile boolean closed = false;
 
-    private static ThreadLocal<Boolean> runningFinalize =
-                                new ThreadLocal<Boolean>();
+    private static final ThreadLocal<Boolean> runningFinalize =
+        new ThreadLocal<Boolean>();
 
     private static boolean isRunningFinalize() {
         Boolean val;
@@ -151,7 +151,7 @@
      * is thrown.
      * <p>
      * This constructor does not throw an exception if <code>fdObj</code>
-     * is {link java.io.FileDescriptor#valid() invalid}.
+     * is {@link java.io.FileDescriptor#valid() invalid}.
      * However, if the methods are invoked on the resulting stream to attempt
      * I/O on the stream, an <code>IOException</code> is thrown.
      *
@@ -389,7 +389,7 @@
      * @see        java.io.FileInputStream#close()
      */
     protected void finalize() throws IOException {
-        if ((fd != null) &&  (fd != fd.in)) {
+        if ((fd != null) &&  (fd != FileDescriptor.in)) {
 
             /*
              * Finalizer should not release the FileDescriptor if another
--- a/src/share/classes/java/io/FileOutputStream.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/io/FileOutputStream.java	Fri Mar 28 03:06:00 2008 -0700
@@ -52,20 +52,16 @@
 class FileOutputStream extends OutputStream
 {
     /**
-     * The system dependent file descriptor. The value is
-     * 1 more than actual file descriptor. This means that
-     * the default value 0 indicates that the file is not open.
+     * The system dependent file descriptor.
      */
-    private FileDescriptor fd;
+    private final FileDescriptor fd;
 
     private FileChannel channel= null;
 
-    private boolean append = false;
-
-    private Object closeLock = new Object();
+    private final Object closeLock = new Object();
     private volatile boolean closed = false;
-    private static ThreadLocal<Boolean> runningFinalize =
-                                        new ThreadLocal<Boolean>();
+    private static final ThreadLocal<Boolean> runningFinalize =
+        new ThreadLocal<Boolean>();
 
     private static boolean isRunningFinalize() {
         Boolean val;
@@ -75,7 +71,7 @@
     }
 
     /**
-     * Creates an output file stream to write to the file with the
+     * Creates a file output stream to write to the file with the
      * specified name. A new <code>FileDescriptor</code> object is
      * created to represent this file connection.
      * <p>
@@ -100,8 +96,8 @@
     }
 
     /**
-     * Creates an output file stream to write to the file with the specified
-     * <code>name</code>.  If the second argument is <code>true</code>, then
+     * Creates a file output stream to write to the file with the specified
+     * name.  If the second argument is <code>true</code>, then
      * bytes will be written to the end of the file rather than the beginning.
      * A new <code>FileDescriptor</code> object is created to represent this
      * file connection.
@@ -202,16 +198,11 @@
         }
         fd = new FileDescriptor();
         fd.incrementAndGetUseCount();
-        this.append = append;
-        if (append) {
-            openAppend(name);
-        } else {
-            open(name);
-        }
+        open(name, append);
     }
 
     /**
-     * Creates an output file stream to write to the specified file
+     * Creates a file output stream to write to the specified file
      * descriptor, which represents an existing connection to an actual
      * file in the file system.
      * <p>
@@ -223,7 +214,7 @@
      * is thrown.
      * <p>
      * This constructor does not throw an exception if <code>fdObj</code>
-     * is {link java.io.FileDescriptor#valid() invalid}.
+     * is {@link java.io.FileDescriptor#valid() invalid}.
      * However, if the methods are invoked on the resulting stream to attempt
      * I/O on the stream, an <code>IOException</code> is thrown.
      *
@@ -252,16 +243,12 @@
     }
 
     /**
-     * Opens a file, with the specified name, for writing.
+     * Opens a file, with the specified name, for overwriting or appending.
      * @param name name of file to be opened
+     * @param append whether the file is to be opened in append mode
      */
-    private native void open(String name) throws FileNotFoundException;
-
-    /**
-     * Opens a file, with the specified name, for appending.
-     * @param name name of file to be opened
-     */
-    private native void openAppend(String name) throws FileNotFoundException;
+    private native void open(String name, boolean append)
+        throws FileNotFoundException;
 
     /**
      * Writes the specified byte to this file output stream. Implements
@@ -385,7 +372,7 @@
     public FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
-                channel = FileChannelImpl.open(fd, false, true, this, append);
+                channel = FileChannelImpl.open(fd, false, true, this);
 
                 /*
                  * Increment fd's use count. Invoking the channel's close()
@@ -408,7 +395,7 @@
      */
     protected void finalize() throws IOException {
         if (fd != null) {
-            if (fd == fd.out || fd == fd.err) {
+            if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
                 flush();
             } else {
 
--- a/src/share/classes/java/io/ObjectInputStream.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/io/ObjectInputStream.java	Fri Mar 28 03:06:00 2008 -0700
@@ -212,7 +212,8 @@
     private static final Object unsharedMarker = new Object();
 
     /** table mapping primitive type names to corresponding class objects */
-    private static final HashMap primClasses = new HashMap(8, 1.0F);
+    private static final HashMap<String, Class<?>> primClasses
+        = new HashMap<String, Class<?>>(8, 1.0F);
     static {
         primClasses.put("boolean", boolean.class);
         primClasses.put("byte", byte.class);
@@ -620,7 +621,7 @@
         try {
             return Class.forName(name, false, latestUserDefinedLoader());
         } catch (ClassNotFoundException ex) {
-            Class cl = (Class) primClasses.get(name);
+            Class<?> cl = primClasses.get(name);
             if (cl != null) {
                 return cl;
             } else {
@@ -1254,11 +1255,11 @@
      * override security-sensitive non-final methods.  Returns true if subclass
      * is "safe", false otherwise.
      */
-    private static boolean auditSubclass(final Class subcl) {
+    private static boolean auditSubclass(final Class<?> subcl) {
         Boolean result = AccessController.doPrivileged(
             new PrivilegedAction<Boolean>() {
                 public Boolean run() {
-                    for (Class cl = subcl;
+                    for (Class<?> cl = subcl;
                          cl != ObjectInputStream.class;
                          cl = cl.getSuperclass())
                     {
@@ -2217,9 +2218,9 @@
             try {
                 while (list != null) {
                     AccessController.doPrivileged(
-                        new PrivilegedExceptionAction()
+                        new PrivilegedExceptionAction<Void>()
                     {
-                        public Object run() throws InvalidObjectException {
+                        public Void run() throws InvalidObjectException {
                             list.obj.validateObject();
                             return null;
                         }
--- a/src/share/classes/java/io/ObjectStreamClass.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/io/ObjectStreamClass.java	Fri Mar 28 03:06:00 2008 -0700
@@ -77,7 +77,7 @@
         NO_FIELDS;
 
     /** reflection factory for obtaining serialization constructors */
-    private static final ReflectionFactory reflFactory = (ReflectionFactory)
+    private static final ReflectionFactory reflFactory =
         AccessController.doPrivileged(
             new ReflectionFactory.GetReflectionFactoryAction());
 
@@ -216,10 +216,10 @@
     public long getSerialVersionUID() {
         // REMIND: synchronize instead of relying on volatile?
         if (suid == null) {
-            suid = (Long) AccessController.doPrivileged(
-                new PrivilegedAction() {
-                    public Object run() {
-                        return Long.valueOf(computeDefaultSUID(cl));
+            suid = AccessController.doPrivileged(
+                new PrivilegedAction<Long>() {
+                    public Long run() {
+                        return computeDefaultSUID(cl);
                     }
                 }
             );
@@ -392,8 +392,8 @@
             }
             if (interrupted) {
                 AccessController.doPrivileged(
-                    new PrivilegedAction() {
-                        public Object run() {
+                    new PrivilegedAction<Void>() {
+                        public Void run() {
                             Thread.currentThread().interrupt();
                             return null;
                         }
@@ -427,8 +427,8 @@
         localDesc = this;
 
         if (serializable) {
-            AccessController.doPrivileged(new PrivilegedAction() {
-                public Object run() {
+            AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                public Void run() {
                     if (isEnum) {
                         suid = Long.valueOf(0);
                         fields = NO_FIELDS;
@@ -802,7 +802,7 @@
      * non-primitive types, and any other non-null type matches assignable
      * types only.  Returns matching field, or null if no match found.
      */
-    ObjectStreamField getField(String name, Class type) {
+    ObjectStreamField getField(String name, Class<?> type) {
         for (int i = 0; i < fields.length; i++) {
             ObjectStreamField f = fields[i];
             if (f.getName().equals(name)) {
@@ -811,7 +811,7 @@
                 {
                     return f;
                 }
-                Class ftype = f.getType();
+                Class<?> ftype = f.getType();
                 if (ftype != null && type.isAssignableFrom(ftype)) {
                     return f;
                 }
@@ -1130,7 +1130,7 @@
     private ClassDataSlot[] getClassDataLayout0()
         throws InvalidClassException
     {
-        ArrayList slots = new ArrayList();
+        ArrayList<ClassDataSlot> slots = new ArrayList<ClassDataSlot>();
         Class start = cl, end = cl;
 
         // locate closest non-serializable superclass
@@ -1171,8 +1171,7 @@
 
         // order slots from superclass -> subclass
         Collections.reverse(slots);
-        return (ClassDataSlot[])
-            slots.toArray(new ClassDataSlot[slots.size()]);
+        return slots.toArray(new ClassDataSlot[slots.size()]);
     }
 
     /**
@@ -1309,9 +1308,9 @@
      * Access checks are disabled on the returned constructor (if any), since
      * the defining class may still be non-public.
      */
-    private static Constructor getExternalizableConstructor(Class cl) {
+    private static Constructor getExternalizableConstructor(Class<?> cl) {
         try {
-            Constructor cons = cl.getDeclaredConstructor((Class[]) null);
+            Constructor cons = cl.getDeclaredConstructor((Class<?>[]) null);
             cons.setAccessible(true);
             return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
                 cons : null;
@@ -1325,15 +1324,15 @@
      * superclass, or null if none found.  Access checks are disabled on the
      * returned constructor (if any).
      */
-    private static Constructor getSerializableConstructor(Class cl) {
-        Class initCl = cl;
+    private static Constructor getSerializableConstructor(Class<?> cl) {
+        Class<?> initCl = cl;
         while (Serializable.class.isAssignableFrom(initCl)) {
             if ((initCl = initCl.getSuperclass()) == null) {
                 return null;
             }
         }
         try {
-            Constructor cons = initCl.getDeclaredConstructor((Class[]) null);
+            Constructor cons = initCl.getDeclaredConstructor((Class<?>[]) null);
             int mods = cons.getModifiers();
             if ((mods & Modifier.PRIVATE) != 0 ||
                 ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
@@ -1355,12 +1354,12 @@
      * null if no match found.  Access checks are disabled on the returned
      * method (if any).
      */
-    private static Method getInheritableMethod(Class cl, String name,
+    private static Method getInheritableMethod(Class<?> cl, String name,
                                                Class[] argTypes,
                                                Class returnType)
     {
         Method meth = null;
-        Class defCl = cl;
+        Class<?> defCl = cl;
         while (defCl != null) {
             try {
                 meth = defCl.getDeclaredMethod(name, argTypes);
@@ -1391,9 +1390,9 @@
      * class, or null if none found.  Access checks are disabled on the
      * returned method (if any).
      */
-    private static Method getPrivateMethod(Class cl, String name,
-                                           Class[] argTypes,
-                                           Class returnType)
+    private static Method getPrivateMethod(Class<?> cl, String name,
+                                           Class<?>[] argTypes,
+                                           Class<?> returnType)
     {
         try {
             Method meth = cl.getDeclaredMethod(name, argTypes);
@@ -1567,7 +1566,7 @@
 
         ObjectStreamField[] boundFields =
             new ObjectStreamField[serialPersistentFields.length];
-        Set fieldNames = new HashSet(serialPersistentFields.length);
+        Set<String> fieldNames = new HashSet<String>(serialPersistentFields.length);
 
         for (int i = 0; i < serialPersistentFields.length; i++) {
             ObjectStreamField spf = serialPersistentFields[i];
@@ -1605,7 +1604,7 @@
      */
     private static ObjectStreamField[] getDefaultSerialFields(Class cl) {
         Field[] clFields = cl.getDeclaredFields();
-        ArrayList list = new ArrayList();
+        ArrayList<ObjectStreamField> list = new ArrayList<ObjectStreamField>();
         int mask = Modifier.STATIC | Modifier.TRANSIENT;
 
         for (int i = 0; i < clFields.length; i++) {
@@ -1615,7 +1614,7 @@
         }
         int size = list.size();
         return (size == 0) ? NO_FIELDS :
-            (ObjectStreamField[]) list.toArray(new ObjectStreamField[size]);
+            list.toArray(new ObjectStreamField[size]);
     }
 
     /**
@@ -1688,11 +1687,9 @@
             for (int i = 0; i < fields.length; i++) {
                 fieldSigs[i] = new MemberSignature(fields[i]);
             }
-            Arrays.sort(fieldSigs, new Comparator() {
-                public int compare(Object o1, Object o2) {
-                    String name1 = ((MemberSignature) o1).name;
-                    String name2 = ((MemberSignature) o2).name;
-                    return name1.compareTo(name2);
+            Arrays.sort(fieldSigs, new Comparator<MemberSignature>() {
+                public int compare(MemberSignature ms1, MemberSignature ms2) {
+                    return ms1.name.compareTo(ms2.name);
                 }
             });
             for (int i = 0; i < fieldSigs.length; i++) {
@@ -1721,11 +1718,9 @@
             for (int i = 0; i < cons.length; i++) {
                 consSigs[i] = new MemberSignature(cons[i]);
             }
-            Arrays.sort(consSigs, new Comparator() {
-                public int compare(Object o1, Object o2) {
-                    String sig1 = ((MemberSignature) o1).signature;
-                    String sig2 = ((MemberSignature) o2).signature;
-                    return sig1.compareTo(sig2);
+            Arrays.sort(consSigs, new Comparator<MemberSignature>() {
+                public int compare(MemberSignature ms1, MemberSignature ms2) {
+                    return ms1.signature.compareTo(ms2.signature);
                 }
             });
             for (int i = 0; i < consSigs.length; i++) {
@@ -1746,10 +1741,8 @@
             for (int i = 0; i < methods.length; i++) {
                 methSigs[i] = new MemberSignature(methods[i]);
             }
-            Arrays.sort(methSigs, new Comparator() {
-                public int compare(Object o1, Object o2) {
-                    MemberSignature ms1 = (MemberSignature) o1;
-                    MemberSignature ms2 = (MemberSignature) o2;
+            Arrays.sort(methSigs, new Comparator<MemberSignature>() {
+                public int compare(MemberSignature ms1, MemberSignature ms2) {
                     int comp = ms1.name.compareTo(ms2.name);
                     if (comp == 0) {
                         comp = ms1.signature.compareTo(ms2.signature);
@@ -1859,7 +1852,7 @@
             keys = new long[nfields];
             offsets = new int[nfields];
             typeCodes = new char[nfields];
-            ArrayList typeList = new ArrayList();
+            ArrayList<Class<?>> typeList = new ArrayList<Class<?>>();
 
             for (int i = 0; i < nfields; i++) {
                 ObjectStreamField f = fields[i];
@@ -1873,7 +1866,7 @@
                 }
             }
 
-            types = (Class[]) typeList.toArray(new Class[typeList.size()]);
+            types = typeList.toArray(new Class<?>[typeList.size()]);
             numPrimFields = nfields - types.length;
         }
 
--- a/src/share/classes/java/lang/Class.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/Class.java	Fri Mar 28 03:06:00 2008 -0700
@@ -345,9 +345,9 @@
                 // since we have to do the security check here anyway
                 // (the stack depth is wrong for the Constructor's
                 // security check to work)
-                java.security.AccessController.doPrivileged
-                    (new java.security.PrivilegedAction() {
-                            public Object run() {
+                java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedAction<Void>() {
+                        public Void run() {
                                 c.setAccessible(true);
                                 return null;
                             }
@@ -1302,10 +1302,10 @@
         // out anything other than public members and (2) public member access
         // has already been ok'd by the SecurityManager.
 
-        Class[] result = (Class[]) java.security.AccessController.doPrivileged
-            (new java.security.PrivilegedAction() {
-                public Object run() {
-                    java.util.List<Class> list = new java.util.ArrayList();
+        return java.security.AccessController.doPrivileged(
+            new java.security.PrivilegedAction<Class[]>() {
+                public Class[] run() {
+                    List<Class> list = new ArrayList<Class>();
                     Class currentClass = Class.this;
                     while (currentClass != null) {
                         Class[] members = currentClass.getDeclaredClasses();
@@ -1316,12 +1316,9 @@
                         }
                         currentClass = currentClass.getSuperclass();
                     }
-                    Class[] empty = {};
-                    return list.toArray(empty);
+                    return list.toArray(new Class[0]);
                 }
             });
-
-        return result;
     }
 
 
@@ -2215,15 +2212,15 @@
 
     // Caches for certain reflective results
     private static boolean useCaches = true;
-    private volatile transient SoftReference declaredFields;
-    private volatile transient SoftReference publicFields;
-    private volatile transient SoftReference declaredMethods;
-    private volatile transient SoftReference publicMethods;
-    private volatile transient SoftReference declaredConstructors;
-    private volatile transient SoftReference publicConstructors;
+    private volatile transient SoftReference<Field[]> declaredFields;
+    private volatile transient SoftReference<Field[]> publicFields;
+    private volatile transient SoftReference<Method[]> declaredMethods;
+    private volatile transient SoftReference<Method[]> publicMethods;
+    private volatile transient SoftReference<Constructor<T>[]> declaredConstructors;
+    private volatile transient SoftReference<Constructor<T>[]> publicConstructors;
     // Intermediate results for getFields and getMethods
-    private volatile transient SoftReference declaredPublicFields;
-    private volatile transient SoftReference declaredPublicMethods;
+    private volatile transient SoftReference<Field[]> declaredPublicFields;
+    private volatile transient SoftReference<Method[]> declaredPublicMethods;
 
     // Incremented by the VM on each call to JVM TI RedefineClasses()
     // that redefines this class or a superclass.
@@ -2295,11 +2292,11 @@
             clearCachesOnClassRedefinition();
             if (publicOnly) {
                 if (declaredPublicFields != null) {
-                    res = (Field[]) declaredPublicFields.get();
+                    res = declaredPublicFields.get();
                 }
             } else {
                 if (declaredFields != null) {
-                    res = (Field[]) declaredFields.get();
+                    res = declaredFields.get();
                 }
             }
             if (res != null) return res;
@@ -2308,9 +2305,9 @@
         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
         if (useCaches) {
             if (publicOnly) {
-                declaredPublicFields = new SoftReference(res);
+                declaredPublicFields = new SoftReference<Field[]>(res);
             } else {
-                declaredFields = new SoftReference(res);
+                declaredFields = new SoftReference<Field[]>(res);
             }
         }
         return res;
@@ -2319,22 +2316,22 @@
     // Returns an array of "root" fields. These Field objects must NOT
     // be propagated to the outside world, but must instead be copied
     // via ReflectionFactory.copyField.
-    private Field[] privateGetPublicFields(Set traversedInterfaces) {
+    private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
         checkInitted();
         Field[] res = null;
         if (useCaches) {
             clearCachesOnClassRedefinition();
             if (publicFields != null) {
-                res = (Field[]) publicFields.get();
+                res = publicFields.get();
             }
             if (res != null) return res;
         }
 
         // No cached value available; compute value recursively.
         // Traverse in correct order for getField().
-        List fields = new ArrayList();
+        List<Field> fields = new ArrayList<Field>();
         if (traversedInterfaces == null) {
-            traversedInterfaces = new HashSet();
+            traversedInterfaces = new HashSet<Class<?>>();
         }
 
         // Local fields
@@ -2342,9 +2339,7 @@
         addAll(fields, tmp);
 
         // Direct superinterfaces, recursively
-        Class[] interfaces = getInterfaces();
-        for (int i = 0; i < interfaces.length; i++) {
-            Class c = interfaces[i];
+        for (Class<?> c : getInterfaces()) {
             if (!traversedInterfaces.contains(c)) {
                 traversedInterfaces.add(c);
                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
@@ -2353,7 +2348,7 @@
 
         // Direct superclass, recursively
         if (!isInterface()) {
-            Class c = getSuperclass();
+            Class<?> c = getSuperclass();
             if (c != null) {
                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
             }
@@ -2362,12 +2357,12 @@
         res = new Field[fields.size()];
         fields.toArray(res);
         if (useCaches) {
-            publicFields = new SoftReference(res);
+            publicFields = new SoftReference<Field[]>(res);
         }
         return res;
     }
 
-    private static void addAll(Collection c, Field[] o) {
+    private static void addAll(Collection<Field> c, Field[] o) {
         for (int i = 0; i < o.length; i++) {
             c.add(o[i]);
         }
@@ -2383,18 +2378,18 @@
     // Returns an array of "root" constructors. These Constructor
     // objects must NOT be propagated to the outside world, but must
     // instead be copied via ReflectionFactory.copyConstructor.
-    private Constructor[] privateGetDeclaredConstructors(boolean publicOnly) {
+    private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
         checkInitted();
-        Constructor[] res = null;
+        Constructor<T>[] res = null;
         if (useCaches) {
             clearCachesOnClassRedefinition();
             if (publicOnly) {
                 if (publicConstructors != null) {
-                    res = (Constructor[]) publicConstructors.get();
+                    res = publicConstructors.get();
                 }
             } else {
                 if (declaredConstructors != null) {
-                    res = (Constructor[]) declaredConstructors.get();
+                    res = declaredConstructors.get();
                 }
             }
             if (res != null) return res;
@@ -2407,9 +2402,9 @@
         }
         if (useCaches) {
             if (publicOnly) {
-                publicConstructors = new SoftReference(res);
+                publicConstructors = new SoftReference<Constructor<T>[]>(res);
             } else {
-                declaredConstructors = new SoftReference(res);
+                declaredConstructors = new SoftReference<Constructor<T>[]>(res);
             }
         }
         return res;
@@ -2431,11 +2426,11 @@
             clearCachesOnClassRedefinition();
             if (publicOnly) {
                 if (declaredPublicMethods != null) {
-                    res = (Method[]) declaredPublicMethods.get();
+                    res = declaredPublicMethods.get();
                 }
             } else {
                 if (declaredMethods != null) {
-                    res = (Method[]) declaredMethods.get();
+                    res = declaredMethods.get();
                 }
             }
             if (res != null) return res;
@@ -2444,9 +2439,9 @@
         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
         if (useCaches) {
             if (publicOnly) {
-                declaredPublicMethods = new SoftReference(res);
+                declaredPublicMethods = new SoftReference<Method[]>(res);
             } else {
-                declaredMethods = new SoftReference(res);
+                declaredMethods = new SoftReference<Method[]>(res);
             }
         }
         return res;
@@ -2552,7 +2547,7 @@
         if (useCaches) {
             clearCachesOnClassRedefinition();
             if (publicMethods != null) {
-                res = (Method[]) publicMethods.get();
+                res = publicMethods.get();
             }
             if (res != null) return res;
         }
@@ -2602,7 +2597,7 @@
         methods.compactAndTrim();
         res = methods.getArray();
         if (useCaches) {
-            publicMethods = new SoftReference(res);
+            publicMethods = new SoftReference<Method[]>(res);
         }
         return res;
     }
@@ -2713,11 +2708,11 @@
     private Constructor<T> getConstructor0(Class[] parameterTypes,
                                         int which) throws NoSuchMethodException
     {
-        Constructor[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
-        for (int i = 0; i < constructors.length; i++) {
+        Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
+        for (Constructor<T> constructor : constructors) {
             if (arrayContentsEq(parameterTypes,
-                                constructors[i].getParameterTypes())) {
-                return getReflectionFactory().copyConstructor(constructors[i]);
+                                constructor.getParameterTypes())) {
+                return getReflectionFactory().copyConstructor(constructor);
             }
         }
         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
@@ -2767,18 +2762,18 @@
         return out;
     }
 
-    private static Constructor[] copyConstructors(Constructor[] arg) {
-        Constructor[] out = new Constructor[arg.length];
+    private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
+        Constructor<U>[] out = arg.clone();
         ReflectionFactory fact = getReflectionFactory();
-        for (int i = 0; i < arg.length; i++) {
-            out[i] = fact.copyConstructor(arg[i]);
+        for (int i = 0; i < out.length; i++) {
+            out[i] = fact.copyConstructor(out[i]);
         }
         return out;
     }
 
     private native Field[]       getDeclaredFields0(boolean publicOnly);
     private native Method[]      getDeclaredMethods0(boolean publicOnly);
-    private native Constructor[] getDeclaredConstructors0(boolean publicOnly);
+    private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
     private native Class[]   getDeclaredClasses0();
 
     private static String        argumentTypesToString(Class[] argTypes) {
@@ -2883,7 +2878,7 @@
     // Fetches the factory for reflective objects
     private static ReflectionFactory getReflectionFactory() {
         if (reflectionFactory == null) {
-            reflectionFactory =  (ReflectionFactory)
+            reflectionFactory =
                 java.security.AccessController.doPrivileged
                     (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
         }
@@ -2895,8 +2890,8 @@
     private static boolean initted = false;
     private static void checkInitted() {
         if (initted) return;
-        AccessController.doPrivileged(new PrivilegedAction() {
-                public Object run() {
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                public Void run() {
                     // Tests to ensure the system properties table is fully
                     // initialized. This is needed because reflection code is
                     // called very early in the initialization process (before
@@ -2941,17 +2936,17 @@
     /**
      * Returns the elements of this enum class or null if this
      * Class object does not represent an enum type;
-     * identical to getEnumConstantsShared except that
-     * the result is uncloned, cached, and shared by all callers.
+     * identical to getEnumConstants except that the result is
+     * uncloned, cached, and shared by all callers.
      */
     T[] getEnumConstantsShared() {
         if (enumConstants == null) {
             if (!isEnum()) return null;
             try {
                 final Method values = getMethod("values");
-                java.security.AccessController.doPrivileged
-                    (new java.security.PrivilegedAction() {
-                            public Object run() {
+                java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedAction<Void>() {
+                        public Void run() {
                                 values.setAccessible(true);
                                 return null;
                             }
--- a/src/share/classes/java/lang/ClassLoader.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/ClassLoader.java	Fri Mar 28 03:06:00 2008 -0700
@@ -39,6 +39,7 @@
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
 import java.security.ProtectionDomain;
+import java.security.cert.Certificate;
 import java.util.Enumeration;
 import java.util.Hashtable;
 import java.util.HashMap;
@@ -172,17 +173,18 @@
     private ClassLoader parent;
 
     // Hashtable that maps packages to certs
-    private Hashtable package2certs = new Hashtable(11);
+    private Hashtable<String, Certificate[]> package2certs
+        = new Hashtable<String, Certificate[]>(11);
 
     // Shared among all packages with unsigned classes
-    java.security.cert.Certificate[] nocerts;
+    Certificate[] nocerts;
 
     // The classes loaded by this class loader.  The only purpose of this table
     // is to keep the classes from being GC'ed until the loader is GC'ed.
-    private Vector classes = new Vector();
+    private Vector<Class<?>> classes = new Vector<Class<?>>();
 
     // The initiating protection domains for all classes loaded by this loader
-    private Set domains = new HashSet();
+    private Set<ProtectionDomain> domains = new HashSet<ProtectionDomain>();
 
     // Invoked by the VM to record every loaded class with this loader.
     void addClass(Class c) {
@@ -191,7 +193,7 @@
 
     // The packages defined in this class loader.  Each package name is mapped
     // to its corresponding Package object.
-    private HashMap packages = new HashMap();
+    private HashMap<String, Package> packages = new HashMap<String, Package>();
 
     /**
      * Creates a new class loader using the specified parent class loader for
@@ -342,8 +344,8 @@
             final String name = cls.getName();
             final int i = name.lastIndexOf('.');
             if (i != -1) {
-                AccessController.doPrivileged(new PrivilegedAction() {
-                    public Object run() {
+                AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                    public Void run() {
                         sm.checkPackageAccess(name.substring(0, i));
                         return null;
                     }
@@ -524,17 +526,20 @@
         // Class format error - try to transform the bytecode and
         // define the class again
         //
-        Object[] transformers = ClassFileTransformer.getTransformers();
+        ClassFileTransformer[] transformers = ClassFileTransformer.getTransformers();
         Class c = null;
 
-        for (int i = 0; transformers != null && i < transformers.length; i++) {
-            try {
-              // Transform byte code using transformer
-              byte[] tb = ((ClassFileTransformer) transformers[i]).transform(b, off, len);
-              c = defineClass1(name, tb, 0, tb.length, protectionDomain, source);
-              break;
-            } catch (ClassFormatError cfe2)     {
-              // If ClassFormatError occurs, try next transformer
+        if (transformers != null) {
+            for (ClassFileTransformer transformer : transformers) {
+                try {
+                    // Transform byte code using transformer
+                    byte[] tb = transformer.transform(b, off, len);
+                    c = defineClass1(name, tb, 0, tb.length,
+                                     protectionDomain, source);
+                    break;
+                } catch (ClassFormatError cfe2)     {
+                    // If ClassFormatError occurs, try next transformer
+                }
             }
         }
 
@@ -550,7 +555,7 @@
     private void postDefineClass(Class c, ProtectionDomain protectionDomain)
     {
         if (protectionDomain.getCodeSource() != null) {
-            java.security.cert.Certificate certs[] =
+            Certificate certs[] =
                 protectionDomain.getCodeSource().getCertificates();
             if (certs != null)
                 setSigners(c, certs);
@@ -767,8 +772,7 @@
     private synchronized void checkCerts(String name, CodeSource cs) {
         int i = name.lastIndexOf('.');
         String pname = (i == -1) ? "" : name.substring(0, i);
-        java.security.cert.Certificate[] pcerts =
-            (java.security.cert.Certificate[]) package2certs.get(pname);
+        Certificate[] pcerts = package2certs.get(pname);
         if (pcerts == null) {
             // first class in this package gets to define which
             // certificates must be the same for all other classes
@@ -778,12 +782,12 @@
             }
             if (pcerts == null) {
                 if (nocerts == null)
-                    nocerts = new java.security.cert.Certificate[0];
+                    nocerts = new Certificate[0];
                 pcerts = nocerts;
             }
             package2certs.put(pname, pcerts);
         } else {
-            java.security.cert.Certificate[] certs = null;
+            Certificate[] certs = null;
             if (cs != null) {
                 certs = cs.getCertificates();
             }
@@ -799,8 +803,8 @@
      * check to make sure the certs for the new class (certs) are the same as
      * the certs for the first class inserted in the package (pcerts)
      */
-    private boolean compareCerts(java.security.cert.Certificate[] pcerts,
-                                 java.security.cert.Certificate[] certs)
+    private boolean compareCerts(Certificate[] pcerts,
+                                 Certificate[] certs)
     {
         // certs can be null, indicating no certs.
         if ((certs == null) || (certs.length == 0)) {
@@ -1031,7 +1035,7 @@
         }
         tmp[1] = findResources(name);
 
-        return new CompoundEnumeration(tmp);
+        return new CompoundEnumeration<URL>(tmp);
     }
 
     /**
@@ -1068,7 +1072,7 @@
      * @since  1.2
      */
     protected Enumeration<URL> findResources(String name) throws IOException {
-        return new CompoundEnumeration(new Enumeration[0]);
+        return java.util.Collections.emptyEnumeration();
     }
 
     /**
@@ -1134,13 +1138,13 @@
     /**
      * Find resources from the VM's built-in classloader.
      */
-    private static Enumeration getBootstrapResources(String name)
+    private static Enumeration<URL> getBootstrapResources(String name)
         throws IOException
     {
-        final Enumeration e = getBootstrapClassPath().getResources(name);
-        return new Enumeration () {
-            public Object nextElement() {
-                return ((Resource)e.nextElement()).getURL();
+        final Enumeration<Resource> e = getBootstrapClassPath().getResources(name);
+        return new Enumeration<URL> () {
+            public URL nextElement() {
+                return e.nextElement().getURL();
             }
             public boolean hasMoreElements() {
                 return e.hasMoreElements();
@@ -1323,9 +1327,8 @@
                 Throwable oops = null;
                 scl = l.getClassLoader();
                 try {
-                    PrivilegedExceptionAction a;
-                    a = new SystemClassLoaderAction(scl);
-                    scl = (ClassLoader) AccessController.doPrivileged(a);
+                    scl = AccessController.doPrivileged(
+                        new SystemClassLoaderAction(scl));
                 } catch (PrivilegedActionException pae) {
                     oops = pae.getCause();
                     if (oops instanceof InvocationTargetException) {
@@ -1456,7 +1459,7 @@
      */
     protected Package getPackage(String name) {
         synchronized (packages) {
-            Package pkg = (Package)packages.get(name);
+            Package pkg = packages.get(name);
             if (pkg == null) {
                 if (parent != null) {
                     pkg = parent.getPackage(name);
@@ -1481,9 +1484,9 @@
      * @since  1.2
      */
     protected Package[] getPackages() {
-        Map map;
+        Map<String, Package> map;
         synchronized (packages) {
-            map = (Map)packages.clone();
+            map = new HashMap<String, Package>(packages);
         }
         Package[] pkgs;
         if (parent != null) {
@@ -1499,7 +1502,7 @@
                 }
             }
         }
-        return (Package[])map.values().toArray(new Package[map.size()]);
+        return map.values().toArray(new Package[map.size()]);
     }
 
 
@@ -1585,8 +1588,7 @@
         // Invoked in the VM to determine the context class in
         // JNI_Load/JNI_Unload
         static Class getFromClass() {
-            return ((NativeLibrary)
-                    (ClassLoader.nativeLibraryContext.peek())).fromClass;
+            return ClassLoader.nativeLibraryContext.peek().fromClass;
         }
     }
 
@@ -1597,22 +1599,27 @@
     // Returns (and initializes) the default domain.
     private synchronized ProtectionDomain getDefaultDomain() {
         if (defaultDomain == null) {
-            CodeSource cs =
-                new CodeSource(null, (java.security.cert.Certificate[]) null);
+            CodeSource cs = new CodeSource(null, (Certificate[]) null);
             defaultDomain = new ProtectionDomain(cs, null, this, null);
         }
         return defaultDomain;
     }
 
     // All native library names we've loaded.
-    private static Vector loadedLibraryNames = new Vector();
+    private static Vector<String> loadedLibraryNames
+        = new Vector<String>();
+
     // Native libraries belonging to system classes.
-    private static Vector systemNativeLibraries = new Vector();
+    private static Vector<NativeLibrary> systemNativeLibraries
+        = new Vector<NativeLibrary>();
+
     // Native libraries associated with the class loader.
-    private Vector nativeLibraries = new Vector();
+    private Vector<NativeLibrary> nativeLibraries
+        = new Vector<NativeLibrary>();
 
     // native libraries being loaded/unloaded.
-    private static Stack nativeLibraryContext = new Stack();
+    private static Stack<NativeLibrary> nativeLibraryContext
+        = new Stack<NativeLibrary>();
 
     // The paths searched for libraries
     static private String usr_paths[];
@@ -1699,13 +1706,13 @@
     }
 
     private static boolean loadLibrary0(Class fromClass, final File file) {
-        Boolean exists = (Boolean)
-            AccessController.doPrivileged(new PrivilegedAction() {
+        boolean exists = AccessController.doPrivileged(
+            new PrivilegedAction<Object>() {
                 public Object run() {
-                    return new Boolean(file.exists());
-                }
-            });
-        if (!exists.booleanValue()) {
+                    return file.exists() ? Boolean.TRUE : null;
+                }})
+            != null;
+        if (!exists) {
             return false;
         }
         String name;
@@ -1716,12 +1723,12 @@
         }
         ClassLoader loader =
             (fromClass == null) ? null : fromClass.getClassLoader();
-        Vector libs =
+        Vector<NativeLibrary> libs =
             loader != null ? loader.nativeLibraries : systemNativeLibraries;
         synchronized (libs) {
             int size = libs.size();
             for (int i = 0; i < size; i++) {
-                NativeLibrary lib = (NativeLibrary)libs.elementAt(i);
+                NativeLibrary lib = libs.elementAt(i);
                 if (name.equals(lib.name)) {
                     return true;
                 }
@@ -1748,8 +1755,7 @@
                  */
                 int n = nativeLibraryContext.size();
                 for (int i = 0; i < n; i++) {
-                    NativeLibrary lib = (NativeLibrary)
-                        nativeLibraryContext.elementAt(i);
+                    NativeLibrary lib = nativeLibraryContext.elementAt(i);
                     if (name.equals(lib.name)) {
                         if (loader == lib.fromClass.getClassLoader()) {
                             return true;
@@ -1780,12 +1786,12 @@
 
     // Invoked in the VM class linking code.
     static long findNative(ClassLoader loader, String name) {
-        Vector libs =
+        Vector<NativeLibrary> libs =
             loader != null ? loader.nativeLibraries : systemNativeLibraries;
         synchronized (libs) {
             int size = libs.size();
             for (int i = 0; i < size; i++) {
-                NativeLibrary lib = (NativeLibrary)libs.elementAt(i);
+                NativeLibrary lib = libs.elementAt(i);
                 long entry = lib.find(name);
                 if (entry != 0)
                     return entry;
@@ -1805,13 +1811,13 @@
     // is null then we are delegating assertion status queries to the VM, i.e.,
     // none of this ClassLoader's assertion status modification methods have
     // been invoked.
-    private Map packageAssertionStatus = null;
+    private Map<String, Boolean> packageAssertionStatus = null;
 
     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
     // field is null then we are delegating assertion status queries to the VM,
     // i.e., none of this ClassLoader's assertion status modification methods
     // have been invoked.
-    Map classAssertionStatus = null;
+    Map<String, Boolean> classAssertionStatus = null;
 
     /**
      * Sets the default assertion status for this class loader.  This setting
@@ -1878,7 +1884,7 @@
         if (packageAssertionStatus == null)
             initializeJavaAssertionMaps();
 
-        packageAssertionStatus.put(packageName, Boolean.valueOf(enabled));
+        packageAssertionStatus.put(packageName, enabled);
     }
 
     /**
@@ -1909,7 +1915,7 @@
         if (classAssertionStatus == null)
             initializeJavaAssertionMaps();
 
-        classAssertionStatus.put(className, Boolean.valueOf(enabled));
+        classAssertionStatus.put(className, enabled);
     }
 
     /**
@@ -1927,8 +1933,8 @@
          * Whether or not "Java assertion maps" are initialized, set
          * them to empty maps, effectively ignoring any present settings.
          */
-        classAssertionStatus = new HashMap();
-        packageAssertionStatus = new HashMap();
+        classAssertionStatus = new HashMap<String, Boolean>();
+        packageAssertionStatus = new HashMap<String, Boolean>();
 
         defaultAssertionStatus = false;
     }
@@ -1962,20 +1968,20 @@
         // assert packageAssertionStatus != null;
 
         // Check for a class entry
-        result = (Boolean)classAssertionStatus.get(className);
+        result = classAssertionStatus.get(className);
         if (result != null)
             return result.booleanValue();
 
         // Check for most specific package entry
         int dotIndex = className.lastIndexOf(".");
         if (dotIndex < 0) { // default package
-            result = (Boolean)packageAssertionStatus.get(null);
+            result = packageAssertionStatus.get(null);
             if (result != null)
                 return result.booleanValue();
         }
         while(dotIndex > 0) {
             className = className.substring(0, dotIndex);
-            result = (Boolean)packageAssertionStatus.get(className);
+            result = packageAssertionStatus.get(className);
             if (result != null)
                 return result.booleanValue();
             dotIndex = className.lastIndexOf(".", dotIndex-1);
@@ -1989,17 +1995,17 @@
     private void initializeJavaAssertionMaps() {
         // assert Thread.holdsLock(this);
 
-        classAssertionStatus = new HashMap();
-        packageAssertionStatus = new HashMap();
+        classAssertionStatus = new HashMap<String, Boolean>();
+        packageAssertionStatus = new HashMap<String, Boolean>();
         AssertionStatusDirectives directives = retrieveDirectives();
 
         for(int i = 0; i < directives.classes.length; i++)
             classAssertionStatus.put(directives.classes[i],
-                              Boolean.valueOf(directives.classEnabled[i]));
+                                     directives.classEnabled[i]);
 
         for(int i = 0; i < directives.packages.length; i++)
             packageAssertionStatus.put(directives.packages[i],
-                              Boolean.valueOf(directives.packageEnabled[i]));
+                                       directives.packageEnabled[i]);
 
         defaultAssertionStatus = directives.deflt;
     }
@@ -2009,28 +2015,24 @@
 }
 
 
-class SystemClassLoaderAction implements PrivilegedExceptionAction {
+class SystemClassLoaderAction
+    implements PrivilegedExceptionAction<ClassLoader> {
     private ClassLoader parent;
 
     SystemClassLoaderAction(ClassLoader parent) {
         this.parent = parent;
     }
 
-    public Object run() throws Exception {
-        ClassLoader sys;
-        Constructor ctor;
-        Class c;
-        Class cp[] = { ClassLoader.class };
-        Object params[] = { parent };
-
+    public ClassLoader run() throws Exception {
         String cls = System.getProperty("java.system.class.loader");
         if (cls == null) {
             return parent;
         }
 
-        c = Class.forName(cls, true, parent);
-        ctor = c.getDeclaredConstructor(cp);
-        sys = (ClassLoader) ctor.newInstance(params);
+        Constructor ctor = Class.forName(cls, true, parent)
+            .getDeclaredConstructor(new Class[] { ClassLoader.class });
+        ClassLoader sys = (ClassLoader) ctor.newInstance(
+            new Object[] { parent });
         Thread.currentThread().setContextClassLoader(sys);
         return sys;
     }
--- a/src/share/classes/java/lang/Compiler.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/Compiler.java	Fri Mar 28 03:06:00 2008 -0700
@@ -53,9 +53,9 @@
 
     static {
         registerNatives();
-        java.security.AccessController.doPrivileged
-            (new java.security.PrivilegedAction() {
-                public Object run() {
+        java.security.AccessController.doPrivileged(
+            new java.security.PrivilegedAction<Void>() {
+                public Void run() {
                     boolean loaded = false;
                     String jit = System.getProperty("java.compiler");
                     if ((jit != null) && (!jit.equals("NONE")) &&
--- a/src/share/classes/java/lang/Long.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/Long.java	Fri Mar 28 03:06:00 2008 -0700
@@ -650,7 +650,7 @@
 
         try {
             result = Long.valueOf(nm.substring(index), radix);
-            result = negative ? new Long((long)-result.longValue()) : result;
+            result = negative ? new Long(-result.longValue()) : result;
         } catch (NumberFormatException e) {
             // If number is Long.MIN_VALUE, we'll end up here. The next line
             // handles this case, and causes any genuine format error to be
--- a/src/share/classes/java/lang/Package.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/Package.java	Fri Mar 28 03:06:00 2008 -0700
@@ -507,7 +507,7 @@
      */
     static Package getSystemPackage(String name) {
         synchronized (pkgs) {
-            Package pkg = (Package)pkgs.get(name);
+            Package pkg = pkgs.get(name);
             if (pkg == null) {
                 name = name.replace('.', '/').concat("/");
                 String fn = getSystemPackage0(name);
@@ -529,18 +529,18 @@
             for (int i = 0; i < names.length; i++) {
                 defineSystemPackage(names[i], getSystemPackage0(names[i]));
             }
-            return (Package[])pkgs.values().toArray(new Package[pkgs.size()]);
+            return pkgs.values().toArray(new Package[pkgs.size()]);
         }
     }
 
     private static Package defineSystemPackage(final String iname,
                                                final String fn)
     {
-        return (Package) AccessController.doPrivileged(new PrivilegedAction() {
-            public Object run() {
+        return AccessController.doPrivileged(new PrivilegedAction<Package>() {
+            public Package run() {
                 String name = iname;
                 // Get the cached code source url for the file name
-                URL url = (URL)urls.get(fn);
+                URL url = urls.get(fn);
                 if (url == null) {
                     // URL not found, so create one
                     File file = new File(fn);
@@ -559,7 +559,7 @@
                 // Convert to "."-separated package name
                 name = name.substring(0, name.length() - 1).replace('/', '.');
                 Package pkg;
-                Manifest man = (Manifest)mans.get(fn);
+                Manifest man = mans.get(fn);
                 if (man != null) {
                     pkg = new Package(name, man, url, null);
                 } else {
@@ -588,13 +588,16 @@
     }
 
     // The map of loaded system packages
-    private static Map pkgs = new HashMap(31);
+    private static Map<String, Package> pkgs
+        = new HashMap<String, Package>(31);
 
     // Maps each directory or zip file name to its corresponding url
-    private static Map urls = new HashMap(10);
+    private static Map<String, URL> urls
+        = new HashMap<String, URL>(10);
 
     // Maps each code source url for a jar file to its manifest
-    private static Map mans = new HashMap(10);
+    private static Map<String, Manifest> mans
+        = new HashMap<String, Manifest>(10);
 
     private static native String getSystemPackage0(String name);
     private static native String[] getSystemPackages0();
--- a/src/share/classes/java/lang/Process.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/Process.java	Fri Mar 28 03:06:00 2008 -0700
@@ -41,18 +41,24 @@
  * <p>The methods that create processes may not work well for special
  * processes on certain native platforms, such as native windowing
  * processes, daemon processes, Win16/DOS processes on Microsoft
- * Windows, or shell scripts.  The created subprocess does not have
- * its own terminal or console.  All its standard I/O (i.e. stdin,
- * stdout, stderr) operations will be redirected to the parent process
- * through three streams
- * ({@link #getOutputStream()},
- * {@link #getInputStream()},
- * {@link #getErrorStream()}).
+ * Windows, or shell scripts.
+ *
+ * <p>By default, the created subprocess does not have its own terminal
+ * or console.  All its standard I/O (i.e. stdin, stdout, stderr)
+ * operations will be redirected to the parent process, where they can
+ * be accessed via the streams obtained using the methods
+ * {@link #getOutputStream()},
+ * {@link #getInputStream()}, and
+ * {@link #getErrorStream()}.
  * The parent process uses these streams to feed input to and get output
  * from the subprocess.  Because some native platforms only provide
  * limited buffer size for standard input and output streams, failure
  * to promptly write the input stream or read the output stream of
- * the subprocess may cause the subprocess to block, and even deadlock.
+ * the subprocess may cause the subprocess to block, or even deadlock.
+ *
+ * <p>Where desired, <a href="ProcessBuilder.html#redirect-input">
+ * subprocess I/O can also be redirected</a>
+ * using methods of the {@link ProcessBuilder} class.
  *
  * <p>The subprocess is not killed when there are no more references to
  * the {@code Process} object, but rather the subprocess
@@ -62,16 +68,22 @@
  * Process} object execute asynchronously or concurrently with respect
  * to the Java process that owns the {@code Process} object.
  *
- * @author  unascribed
- * @see     ProcessBuilder
+ * <p>As of 1.5, {@link ProcessBuilder#start()} is the preferred way
+ * to create a {@code Process}.
+ *
  * @since   JDK1.0
  */
 public abstract class Process {
     /**
      * Returns the output stream connected to the normal input of the
      * subprocess.  Output to the stream is piped into the standard
-     * input stream of the process represented by this {@code Process}
-     * object.
+     * input of the process represented by this {@code Process} object.
+     *
+     * <p>If the standard input of the subprocess has been redirected using
+     * {@link ProcessBuilder#redirectInput(Redirect)
+     * ProcessBuilder.redirectInput}
+     * then this method will return a
+     * <a href="ProcessBuilder.html#redirect-input">null output stream</a>.
      *
      * <p>Implementation note: It is a good idea for the returned
      * output stream to be buffered.
@@ -84,30 +96,47 @@
     /**
      * Returns the input stream connected to the normal output of the
      * subprocess.  The stream obtains data piped from the standard
-     * output stream of the process represented by this {@code
-     * Process} object.
+     * output of the process represented by this {@code Process} object.
+     *
+     * <p>If the standard output of the subprocess has been redirected using
+     * {@link ProcessBuilder#redirectOutput(Redirect)
+     * ProcessBuilder.redirectOutput}
+     * then this method will return a
+     * <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
+     *
+     * <p>Otherwise, if the standard error of the subprocess has been
+     * redirected using
+     * {@link ProcessBuilder#redirectErrorStream(boolean)
+     * ProcessBuilder.redirectErrorStream}
+     * then the input stream returned by this method will receive the
+     * merged standard output and the standard error of the subprocess.
      *
      * <p>Implementation note: It is a good idea for the returned
      * input stream to be buffered.
      *
      * @return the input stream connected to the normal output of the
      *         subprocess
-     * @see ProcessBuilder#redirectErrorStream()
      */
     abstract public InputStream getInputStream();
 
     /**
-     * Returns the input stream connected to the error output stream of
-     * the subprocess.  The stream obtains data piped from the error
-     * output stream of the process represented by this {@code Process}
-     * object.
+     * Returns the input stream connected to the error output of the
+     * subprocess.  The stream obtains data piped from the error output
+     * of the process represented by this {@code Process} object.
+     *
+     * <p>If the standard error of the subprocess has been redirected using
+     * {@link ProcessBuilder#redirectError(Redirect)
+     * ProcessBuilder.redirectError} or
+     * {@link ProcessBuilder#redirectErrorStream(boolean)
+     * ProcessBuilder.redirectErrorStream}
+     * then this method will return a
+     * <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
      *
      * <p>Implementation note: It is a good idea for the returned
      * input stream to be buffered.
      *
-     * @return the input stream connected to the error output stream of
+     * @return the input stream connected to the error output of
      *         the subprocess
-     * @see ProcessBuilder#redirectErrorStream()
      */
     abstract public InputStream getErrorStream();
 
--- a/src/share/classes/java/lang/ProcessBuilder.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/ProcessBuilder.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  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
@@ -27,6 +27,10 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.FileOutputStream;
+import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -34,7 +38,7 @@
 /**
  * This class is used to create operating system processes.
  *
- * <p>Each <code>ProcessBuilder</code> instance manages a collection
+ * <p>Each {@code ProcessBuilder} instance manages a collection
  * of process attributes.  The {@link #start()} method creates a new
  * {@link Process} instance with those attributes.  The {@link
  * #start()} method can be invoked repeatedly from the same instance
@@ -59,19 +63,64 @@
  *
  * <li>a <i>working directory</i>.  The default value is the current
  * working directory of the current process, usually the directory
- * named by the system property <code>user.dir</code>.
+ * named by the system property {@code user.dir}.
+ *
+ * <li><a name="redirect-input">a source of <i>standard input</i>.
+ * By default, the subprocess reads input from a pipe.  Java code
+ * can access this pipe via the output stream returned by
+ * {@link Process#getOutputStream()}.  However, standard input may
+ * be redirected to another source using
+ * {@link #redirectInput(Redirect) redirectInput}.
+ * In this case, {@link Process#getOutputStream()} will return a
+ * <i>null output stream</i>, for which:
+ *
+ * <ul>
+ * <li>the {@link OutputStream#write(int) write} methods always
+ * throw {@code IOException}
+ * <li>the {@link OutputStream#close() close} method does nothing
+ * </ul>
+ *
+ * <li><a name="redirect-output">a destination for <i>standard output</i>
+ * and <i>standard error</i>.  By default, the subprocess writes standard
+ * output and standard error to pipes.  Java code can access these pipes
+ * via the input streams returned by {@link Process#getInputStream()} and
+ * {@link Process#getErrorStream()}.  However, standard output and
+ * standard error may be redirected to other destinations using
+ * {@link #redirectOutput(Redirect) redirectOutput} and
+ * {@link #redirectError(Redirect) redirectError}.
+ * In this case, {@link Process#getInputStream()} and/or
+ * {@link Process#getErrorStream()} will return a <i>null input
+ * stream</i>, for which:
+ *
+ * <ul>
+ * <li>the {@link InputStream#read() read} methods always return
+ * {@code -1}
+ * <li>the {@link InputStream#available() available} method always returns
+ * {@code 0}
+ * <li>the {@link InputStream#close() close} method does nothing
+ * </ul>
  *
  * <li>a <i>redirectErrorStream</i> property.  Initially, this property
- * is <code>false</code>, meaning that the standard output and error
+ * is {@code false}, meaning that the standard output and error
  * output of a subprocess are sent to two separate streams, which can
  * be accessed using the {@link Process#getInputStream()} and {@link
- * Process#getErrorStream()} methods.  If the value is set to
- * <code>true</code>, the standard error is merged with the standard
- * output.  This makes it easier to correlate error messages with the
- * corresponding output.  In this case, the merged data can be read
- * from the stream returned by {@link Process#getInputStream()}, while
- * reading from the stream returned by {@link
- * Process#getErrorStream()} will get an immediate end of file.
+ * Process#getErrorStream()} methods.
+ *
+ * <p>If the value is set to {@code true}, then:
+ *
+ * <ul>
+ * <li>standard error is merged with the standard output and always sent
+ * to the same destination (this makes it easier to correlate error
+ * messages with the corresponding output)
+ * <li>the common destination of standard error and standard output can be
+ * redirected using
+ * {@link #redirectOutput(Redirect) redirectOutput}
+ * <li>any redirection set by the
+ * {@link #redirectError(Redirect) redirectError}
+ * method is ignored when creating a subprocess
+ * <li>the stream returned from {@link Process#getErrorStream()} will
+ * always be a <a href="#redirect-output">null input stream</a>
+ * </ul>
  *
  * </ul>
  *
@@ -87,34 +136,43 @@
  * is invoked.
  *
  * <p><strong>Note that this class is not synchronized.</strong>
- * If multiple threads access a <code>ProcessBuilder</code> instance
+ * If multiple threads access a {@code ProcessBuilder} instance
  * concurrently, and at least one of the threads modifies one of the
  * attributes structurally, it <i>must</i> be synchronized externally.
  *
  * <p>Starting a new process which uses the default working directory
  * and environment is easy:
  *
- * <blockquote><pre>
+ * <pre> {@code
  * Process p = new ProcessBuilder("myCommand", "myArg").start();
- * </pre></blockquote>
+ * }</pre>
  *
  * <p>Here is an example that starts a process with a modified working
- * directory and environment:
+ * directory and environment, and redirects standard output and error
+ * to be appended to a log file:
  *
- * <blockquote><pre>
- * ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
- * Map&lt;String, String&gt; env = pb.environment();
+ * <pre> {@code
+ * ProcessBuilder pb =
+ *   new ProcessBuilder("myCommand", "myArg1", "myArg2");
+ * Map<String, String> env = pb.environment();
  * env.put("VAR1", "myValue");
  * env.remove("OTHERVAR");
  * env.put("VAR2", env.get("VAR1") + "suffix");
  * pb.directory(new File("myDir"));
+ * File log = new File("log");
+ * pb.redirectErrorStream(true);
+ * pb.redirectOutput(Redirect.appendTo(log));
  * Process p = pb.start();
- * </pre></blockquote>
+ * assert pb.redirectInput() == Redirect.PIPE;
+ * assert pb.redirectOutput().file() == log;
+ * assert p.getInputStream().read() == -1;
+ * }</pre>
  *
  * <p>To start a process with an explicit set of environment
  * variables, first call {@link java.util.Map#clear() Map.clear()}
  * before adding environment variables.
  *
+ * @author Martin Buchholz
  * @since 1.5
  */
 
@@ -124,20 +182,19 @@
     private File directory;
     private Map<String,String> environment;
     private boolean redirectErrorStream;
+    private Redirect[] redirects;
 
     /**
      * Constructs a process builder with the specified operating
      * system program and arguments.  This constructor does <i>not</i>
-     * make a copy of the <code>command</code> list.  Subsequent
+     * make a copy of the {@code command} list.  Subsequent
      * updates to the list will be reflected in the state of the
      * process builder.  It is not checked whether
-     * <code>command</code> corresponds to a valid operating system
-     * command.</p>
+     * {@code command} corresponds to a valid operating system
+     * command.
      *
-     * @param   command  The list containing the program and its arguments
-     *
-     * @throws  NullPointerException
-     *          If the argument is <code>null</code>
+     * @param  command the list containing the program and its arguments
+     * @throws NullPointerException if the argument is null
      */
     public ProcessBuilder(List<String> command) {
         if (command == null)
@@ -149,12 +206,12 @@
      * Constructs a process builder with the specified operating
      * system program and arguments.  This is a convenience
      * constructor that sets the process builder's command to a string
-     * list containing the same strings as the <code>command</code>
+     * list containing the same strings as the {@code command}
      * array, in the same order.  It is not checked whether
-     * <code>command</code> corresponds to a valid operating system
-     * command.</p>
+     * {@code command} corresponds to a valid operating system
+     * command.
      *
-     * @param   command  A string array containing the program and its arguments
+     * @param command a string array containing the program and its arguments
      */
     public ProcessBuilder(String... command) {
         this.command = new ArrayList<String>(command.length);
@@ -165,16 +222,15 @@
     /**
      * Sets this process builder's operating system program and
      * arguments.  This method does <i>not</i> make a copy of the
-     * <code>command</code> list.  Subsequent updates to the list will
+     * {@code command} list.  Subsequent updates to the list will
      * be reflected in the state of the process builder.  It is not
-     * checked whether <code>command</code> corresponds to a valid
-     * operating system command.</p>
+     * checked whether {@code command} corresponds to a valid
+     * operating system command.
      *
-     * @param   command  The list containing the program and its arguments
-     * @return  This process builder
+     * @param  command the list containing the program and its arguments
+     * @return this process builder
      *
-     * @throws  NullPointerException
-     *          If the argument is <code>null</code>
+     * @throws NullPointerException if the argument is null
      */
     public ProcessBuilder command(List<String> command) {
         if (command == null)
@@ -187,12 +243,12 @@
      * Sets this process builder's operating system program and
      * arguments.  This is a convenience method that sets the command
      * to a string list containing the same strings as the
-     * <code>command</code> array, in the same order.  It is not
-     * checked whether <code>command</code> corresponds to a valid
-     * operating system command.</p>
+     * {@code command} array, in the same order.  It is not
+     * checked whether {@code command} corresponds to a valid
+     * operating system command.
      *
-     * @param   command  A string array containing the program and its arguments
-     * @return  This process builder
+     * @param  command a string array containing the program and its arguments
+     * @return this process builder
      */
     public ProcessBuilder command(String... command) {
         this.command = new ArrayList<String>(command.length);
@@ -205,9 +261,9 @@
      * Returns this process builder's operating system program and
      * arguments.  The returned list is <i>not</i> a copy.  Subsequent
      * updates to the list will be reflected in the state of this
-     * process builder.</p>
+     * process builder.
      *
-     * @return  This process builder's program and its arguments
+     * @return this process builder's program and its arguments
      */
     public List<String> command() {
         return command;
@@ -225,10 +281,10 @@
      * <p>The returned object may be modified using ordinary {@link
      * java.util.Map Map} operations.  These modifications will be
      * visible to subprocesses started via the {@link #start()}
-     * method.  Two <code>ProcessBuilder</code> instances always
+     * method.  Two {@code ProcessBuilder} instances always
      * contain independent process environments, so changes to the
      * returned map will never be reflected in any other
-     * <code>ProcessBuilder</code> instance or the values returned by
+     * {@code ProcessBuilder} instance or the values returned by
      * {@link System#getenv System.getenv}.
      *
      * <p>If the system does not support environment variables, an
@@ -262,25 +318,24 @@
      * <p>The returned map is typically case-sensitive on all platforms.
      *
      * <p>If a security manager exists, its
-     * {@link SecurityManager#checkPermission checkPermission}
-     * method is called with a
-     * <code>{@link RuntimePermission}("getenv.*")</code>
-     * permission.  This may result in a {@link SecurityException} being
-     * thrown.
+     * {@link SecurityManager#checkPermission checkPermission} method
+     * is called with a
+     * {@link RuntimePermission}{@code ("getenv.*")} permission.
+     * This may result in a {@link SecurityException} being thrown.
      *
      * <p>When passing information to a Java subprocess,
      * <a href=System.html#EnvironmentVSSystemProperties>system properties</a>
-     * are generally preferred over environment variables.</p>
+     * are generally preferred over environment variables.
      *
-     * @return  This process builder's environment
+     * @return this process builder's environment
      *
-     * @throws  SecurityException
-     *          If a security manager exists and its
-     *          {@link SecurityManager#checkPermission checkPermission}
-     *          method doesn't allow access to the process environment
+     * @throws SecurityException
+     *         if a security manager exists and its
+     *         {@link SecurityManager#checkPermission checkPermission}
+     *         method doesn't allow access to the process environment
      *
-     * @see     Runtime#exec(String[],String[],java.io.File)
-     * @see     System#getenv()
+     * @see    Runtime#exec(String[],String[],java.io.File)
+     * @see    System#getenv()
      */
     public Map<String,String> environment() {
         SecurityManager security = System.getSecurityManager();
@@ -328,12 +383,12 @@
      *
      * Subprocesses subsequently started by this object's {@link
      * #start()} method will use this as their working directory.
-     * The returned value may be <code>null</code> -- this means to use
+     * The returned value may be {@code null} -- this means to use
      * the working directory of the current Java process, usually the
-     * directory named by the system property <code>user.dir</code>,
-     * as the working directory of the child process.</p>
+     * directory named by the system property {@code user.dir},
+     * as the working directory of the child process.
      *
-     * @return  This process builder's working directory
+     * @return this process builder's working directory
      */
     public File directory() {
         return directory;
@@ -344,50 +399,522 @@
      *
      * Subprocesses subsequently started by this object's {@link
      * #start()} method will use this as their working directory.
-     * The argument may be <code>null</code> -- this means to use the
+     * The argument may be {@code null} -- this means to use the
      * working directory of the current Java process, usually the
-     * directory named by the system property <code>user.dir</code>,
-     * as the working directory of the child process.</p>
+     * directory named by the system property {@code user.dir},
+     * as the working directory of the child process.
      *
-     * @param   directory  The new working directory
-     * @return  This process builder
+     * @param  directory the new working directory
+     * @return this process builder
      */
     public ProcessBuilder directory(File directory) {
         this.directory = directory;
         return this;
     }
 
+    // ---------------- I/O Redirection ----------------
+
+    /**
+     * Implements a <a href="#redirect-output">null input stream</a>.
+     */
+    static class NullInputStream extends InputStream {
+        public int read()      { return -1; }
+        public int available() { return 0; }
+    }
+
+    /**
+     * Implements a <a href="#redirect-input">null output stream</a>.
+     */
+    static class NullOutputStream extends OutputStream {
+        public void write(int b) throws IOException {
+            throw new IOException("Stream closed");
+        }
+    }
+
+    /**
+     * Represents a source of subprocess input or a destination of
+     * subprocess output.
+     *
+     * Each {@code Redirect} instance is one of the following:
+     *
+     * <ul>
+     * <li>the special value {@link #PIPE Redirect.PIPE}
+     * <li>the special value {@link #INHERIT Redirect.INHERIT}
+     * <li>a redirection to read from a file, created by an invocation of
+     *     {@link Redirect#from Redirect.from(File)}
+     * <li>a redirection to write to a file,  created by an invocation of
+     *     {@link Redirect#to Redirect.to(File)}
+     * <li>a redirection to append to a file, created by an invocation of
+     *     {@link Redirect#appendTo Redirect.appendTo(File)}
+     * </ul>
+     *
+     * <p>Each of the above categories has an associated unique
+     * {@link Type Type}.
+     *
+     * @since 1.7
+     */
+    public static abstract class Redirect {
+        /**
+         * The type of a {@link Redirect}.
+         */
+        public enum Type {
+            /**
+             * The type of {@link Redirect#PIPE Redirect.PIPE}.
+             */
+            PIPE,
+
+            /**
+             * The type of {@link Redirect#INHERIT Redirect.INHERIT}.
+             */
+            INHERIT,
+
+            /**
+             * The type of redirects returned from
+             * {@link Redirect#from Redirect.from(File)}.
+             */
+            READ,
+
+            /**
+             * The type of redirects returned from
+             * {@link Redirect#to Redirect.to(File)}.
+             */
+            WRITE,
+
+            /**
+             * The type of redirects returned from
+             * {@link Redirect#appendTo Redirect.appendTo(File)}.
+             */
+            APPEND
+        };
+
+        /**
+         * Returns the type of this {@code Redirect}.
+         * @return the type of this {@code Redirect}
+         */
+        public abstract Type type();
+
+        /**
+         * Indicates that subprocess I/O will be connected to the
+         * current Java process over a pipe.
+         *
+         * This is the default handling of subprocess standard I/O.
+         *
+         * <p>It will always be true that
+         *  <pre> {@code
+         * Redirect.PIPE.file() == null &&
+         * Redirect.PIPE.type() == Redirect.Type.PIPE
+         * }</pre>
+         */
+        public static final Redirect PIPE = new Redirect() {
+                public Type type() { return Type.PIPE; }
+                public String toString() { return type().toString(); }};
+
+        /**
+         * Indicates that subprocess I/O source or destination will be the
+         * same as those of the current process.  This is the normal
+         * behavior of most operating system command interpreters (shells).
+         *
+         * <p>It will always be true that
+         *  <pre> {@code
+         * Redirect.INHERIT.file() == null &&
+         * Redirect.INHERIT.type() == Redirect.Type.INHERIT
+         * }</pre>
+         */
+        public static final Redirect INHERIT = new Redirect() {
+                public Type type() { return Type.INHERIT; }
+                public String toString() { return type().toString(); }};
+
+        /**
+         * Returns the {@link File} source or destination associated
+         * with this redirect, or {@code null} if there is no such file.
+         *
+         * @return the file associated with this redirect,
+         *         or {@code null} if there is no such file
+         */
+        public File file() { return null; }
+
+        FileOutputStream toFileOutputStream() throws IOException {
+            throw new UnsupportedOperationException();
+        }
+
+        /**
+         * Returns a redirect to read from the specified file.
+         *
+         * <p>It will always be true that
+         *  <pre> {@code
+         * Redirect.from(file).file() == file &&
+         * Redirect.from(file).type() == Redirect.Type.READ
+         * }</pre>
+         *
+         * @throws NullPointerException if the specified file is null
+         * @return a redirect to read from the specified file
+         */
+        public static Redirect from(final File file) {
+            if (file == null)
+                throw new NullPointerException();
+            return new Redirect() {
+                    public Type type() { return Type.READ; }
+                    public File file() { return file; }
+                    public String toString() {
+                        return "redirect to read from file \"" + file + "\"";
+                    }
+                };
+        }
+
+        /**
+         * Returns a redirect to write to the specified file.
+         * If the specified file exists when the subprocess is started,
+         * its previous contents will be discarded.
+         *
+         * <p>It will always be true that
+         *  <pre> {@code
+         * Redirect.to(file).file() == file &&
+         * Redirect.to(file).type() == Redirect.Type.WRITE
+         * }</pre>
+         *
+         * @throws NullPointerException if the specified file is null
+         * @return a redirect to write to the specified file
+         */
+        public static Redirect to(final File file) {
+            if (file == null)
+                throw new NullPointerException();
+            return new Redirect() {
+                    public Type type() { return Type.WRITE; }
+                    public File file() { return file; }
+                    public String toString() {
+                        return "redirect to write to file \"" + file + "\"";
+                    }
+                    FileOutputStream toFileOutputStream() throws IOException {
+                        return new FileOutputStream(file, false);
+                    }
+                };
+        }
+
+        /**
+         * Returns a redirect to append to the specified file.
+         * Each write operation first advances the position to the
+         * end of the file and then writes the requested data.
+         * Whether the advancement of the position and the writing
+         * of the data are done in a single atomic operation is
+         * system-dependent and therefore unspecified.
+         *
+         * <p>It will always be true that
+         *  <pre> {@code
+         * Redirect.appendTo(file).file() == file &&
+         * Redirect.appendTo(file).type() == Redirect.Type.APPEND
+         * }</pre>
+         *
+         * @throws NullPointerException if the specified file is null
+         * @return a redirect to append to the specified file
+         */
+        public static Redirect appendTo(final File file) {
+            if (file == null)
+                throw new NullPointerException();
+            return new Redirect() {
+                    public Type type() { return Type.APPEND; }
+                    public File file() { return file; }
+                    public String toString() {
+                        return "redirect to append to file \"" + file + "\"";
+                    }
+                    FileOutputStream toFileOutputStream() throws IOException {
+                        return new FileOutputStream(file, true);
+                    }
+                };
+        }
+
+        /**
+         * Compares the specified object with this {@code Redirect} for
+         * equality.  Returns {@code true} if and only if the two
+         * objects are identical or both objects are {@code Redirect}
+         * instances of the same type associated with non-null equal
+         * {@code File} instances.
+         */
+        public boolean equals(Object obj) {
+            if (obj == this)
+                return true;
+            if (! (obj instanceof Redirect))
+                return false;
+            Redirect r = (Redirect) obj;
+            if (r.type() != this.type())
+                return false;
+            assert this.file() != null;
+            return this.file().equals(r.file());
+        }
+
+        /**
+         * Returns a hash code value for this {@code Redirect}.
+         * @return a hash code value for this {@code Redirect}
+         */
+        public int hashCode() {
+            File file = file();
+            if (file == null)
+                return super.hashCode();
+            else
+                return file.hashCode();
+        }
+
+        /**
+         * No public constructors.  Clients must use predefined
+         * static {@code Redirect} instances or factory methods.
+         */
+        private Redirect() {}
+    }
+
+    private Redirect[] redirects() {
+        if (redirects == null)
+            redirects = new Redirect[] {
+                Redirect.PIPE, Redirect.PIPE, Redirect.PIPE
+            };
+        return redirects;
+    }
+
+    /**
+     * Sets this process builder's standard input source.
+     *
+     * Subprocesses subsequently started by this object's {@link #start()}
+     * method obtain their standard input from this source.
+     *
+     * <p>If the source is {@link Redirect#PIPE Redirect.PIPE}
+     * (the initial value), then the standard input of a
+     * subprocess can be written to using the output stream
+     * returned by {@link Process#getOutputStream()}.
+     * If the source is set to any other value, then
+     * {@link Process#getOutputStream()} will return a
+     * <a href="#redirect-input">null output stream</a>.
+     *
+     * @param  source the new standard input source
+     * @return this process builder
+     * @throws IllegalArgumentException
+     *         if the redirect does not correspond to a valid source
+     *         of data, that is, has type
+     *         {@link Redirect.Type#WRITE WRITE} or
+     *         {@link Redirect.Type#APPEND APPEND}
+     * @since  1.7
+     */
+    public ProcessBuilder redirectInput(Redirect source) {
+        if (source.type() == Redirect.Type.WRITE ||
+            source.type() == Redirect.Type.APPEND)
+            throw new IllegalArgumentException(
+                "Redirect invalid for reading: " + source);
+        redirects()[0] = source;
+        return this;
+    }
+
+    /**
+     * Sets this process builder's standard output destination.
+     *
+     * Subprocesses subsequently started by this object's {@link #start()}
+     * method send their standard output to this destination.
+     *
+     * <p>If the destination is {@link Redirect#PIPE Redirect.PIPE}
+     * (the initial value), then the standard output of a subprocess
+     * can be read using the input stream returned by {@link
+     * Process#getInputStream()}.
+     * If the destination is set to any other value, then
+     * {@link Process#getInputStream()} will return a
+     * <a href="#redirect-output">null input stream</a>.
+     *
+     * @param  destination the new standard output destination
+     * @return this process builder
+     * @throws IllegalArgumentException
+     *         if the redirect does not correspond to a valid
+     *         destination of data, that is, has type
+     *         {@link Redirect.Type#READ READ}
+     * @since  1.7
+     */
+    public ProcessBuilder redirectOutput(Redirect destination) {
+        if (destination.type() == Redirect.Type.READ)
+            throw new IllegalArgumentException(
+                "Redirect invalid for writing: " + destination);
+        redirects()[1] = destination;
+        return this;
+    }
+
+    /**
+     * Sets this process builder's standard error destination.
+     *
+     * Subprocesses subsequently started by this object's {@link #start()}
+     * method send their standard error to this destination.
+     *
+     * <p>If the destination is {@link Redirect#PIPE Redirect.PIPE}
+     * (the initial value), then the error output of a subprocess
+     * can be read using the input stream returned by {@link
+     * Process#getErrorStream()}.
+     * If the destination is set to any other value, then
+     * {@link Process#getErrorStream()} will return a
+     * <a href="#redirect-output">null input stream</a>.
+     *
+     * <p>If the {@link #redirectErrorStream redirectErrorStream}
+     * attribute has been set {@code true}, then the redirection set
+     * by this method has no effect.
+     *
+     * @param  destination the new standard error destination
+     * @return this process builder
+     * @throws IllegalArgumentException
+     *         if the redirect does not correspond to a valid
+     *         destination of data, that is, has type
+     *         {@link Redirect.Type#READ READ}
+     * @since  1.7
+     */
+    public ProcessBuilder redirectError(Redirect destination) {
+        if (destination.type() == Redirect.Type.READ)
+            throw new IllegalArgumentException(
+                "Redirect invalid for writing: " + destination);
+        redirects()[2] = destination;
+        return this;
+    }
+
+    /**
+     * Sets this process builder's standard input source to a file.
+     *
+     * <p>This is a convenience method.  An invocation of the form
+     * {@code redirectInput(file)}
+     * behaves in exactly the same way as the invocation
+     * {@link #redirectInput(Redirect) redirectInput}
+     * {@code (Redirect.from(file))}.
+     *
+     * @param  file the new standard input source
+     * @return this process builder
+     * @since  1.7
+     */
+    public ProcessBuilder redirectInput(File file) {
+        return redirectInput(Redirect.from(file));
+    }
+
+    /**
+     * Sets this process builder's standard output destination to a file.
+     *
+     * <p>This is a convenience method.  An invocation of the form
+     * {@code redirectOutput(file)}
+     * behaves in exactly the same way as the invocation
+     * {@link #redirectOutput(Redirect) redirectOutput}
+     * {@code (Redirect.to(file))}.
+     *
+     * @param  file the new standard output destination
+     * @return this process builder
+     * @since  1.7
+     */
+    public ProcessBuilder redirectOutput(File file) {
+        return redirectOutput(Redirect.to(file));
+    }
+
+    /**
+     * Sets this process builder's standard error destination to a file.
+     *
+     * <p>This is a convenience method.  An invocation of the form
+     * {@code redirectError(file)}
+     * behaves in exactly the same way as the invocation
+     * {@link #redirectError(Redirect) redirectError}
+     * {@code (Redirect.to(file))}.
+     *
+     * @param  file the new standard error destination
+     * @return this process builder
+     * @since  1.7
+     */
+    public ProcessBuilder redirectError(File file) {
+        return redirectError(Redirect.to(file));
+    }
+
+    /**
+     * Returns this process builder's standard input source.
+     *
+     * Subprocesses subsequently started by this object's {@link #start()}
+     * method obtain their standard input from this source.
+     * The initial value is {@link Redirect#PIPE Redirect.PIPE}.
+     *
+     * @return this process builder's standard input source
+     * @since  1.7
+     */
+    public Redirect redirectInput() {
+        return (redirects == null) ? Redirect.PIPE : redirects[0];
+    }
+
+    /**
+     * Returns this process builder's standard output destination.
+     *
+     * Subprocesses subsequently started by this object's {@link #start()}
+     * method redirect their standard output to this destination.
+     * The initial value is {@link Redirect#PIPE Redirect.PIPE}.
+     *
+     * @return this process builder's standard output destination
+     * @since  1.7
+     */
+    public Redirect redirectOutput() {
+        return (redirects == null) ? Redirect.PIPE : redirects[1];
+    }
+
+    /**
+     * Returns this process builder's standard error destination.
+     *
+     * Subprocesses subsequently started by this object's {@link #start()}
+     * method redirect their standard error to this destination.
+     * The initial value is {@link Redirect#PIPE Redirect.PIPE}.
+     *
+     * @return this process builder's standard error destination
+     * @since  1.7
+     */
+    public Redirect redirectError() {
+        return (redirects == null) ? Redirect.PIPE : redirects[2];
+    }
+
+    /**
+     * Sets the source and destination for subprocess standard I/O
+     * to be the same as those of the current Java process.
+     *
+     * <p>This is a convenience method.  An invocation of the form
+     *  <pre> {@code
+     * pb.inheritIO()
+     * }</pre>
+     * behaves in exactly the same way as the invocation
+     *  <pre> {@code
+     * pb.redirectInput(Redirect.INHERIT)
+     *   .redirectOutput(Redirect.INHERIT)
+     *   .redirectError(Redirect.INHERIT)
+     * }</pre>
+     *
+     * This gives behavior equivalent to most operating system
+     * command interpreters, or the standard C library function
+     * {@code system()}.
+     *
+     * @return this process builder
+     * @since  1.7
+     */
+    public ProcessBuilder inheritIO() {
+        Arrays.fill(redirects(), Redirect.INHERIT);
+        return this;
+    }
+
     /**
      * Tells whether this process builder merges standard error and
      * standard output.
      *
-     * <p>If this property is <code>true</code>, then any error output
+     * <p>If this property is {@code true}, then any error output
      * generated by subprocesses subsequently started by this object's
      * {@link #start()} method will be merged with the standard
      * output, so that both can be read using the
      * {@link Process#getInputStream()} method.  This makes it easier
      * to correlate error messages with the corresponding output.
-     * The initial value is <code>false</code>.</p>
+     * The initial value is {@code false}.
      *
-     * @return  This process builder's <code>redirectErrorStream</code> property
+     * @return this process builder's {@code redirectErrorStream} property
      */
     public boolean redirectErrorStream() {
         return redirectErrorStream;
     }
 
     /**
-     * Sets this process builder's <code>redirectErrorStream</code> property.
+     * Sets this process builder's {@code redirectErrorStream} property.
      *
-     * <p>If this property is <code>true</code>, then any error output
+     * <p>If this property is {@code true}, then any error output
      * generated by subprocesses subsequently started by this object's
      * {@link #start()} method will be merged with the standard
      * output, so that both can be read using the
      * {@link Process#getInputStream()} method.  This makes it easier
      * to correlate error messages with the corresponding output.
-     * The initial value is <code>false</code>.</p>
+     * The initial value is {@code false}.
      *
-     * @param   redirectErrorStream  The new property value
-     * @return  This process builder
+     * @param  redirectErrorStream the new property value
+     * @return this process builder
      */
     public ProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
         this.redirectErrorStream = redirectErrorStream;
@@ -410,7 +937,7 @@
      * <p>If there is a security manager, its
      * {@link SecurityManager#checkExec checkExec}
      * method is called with the first component of this object's
-     * <code>command</code> array as its argument. This may result in
+     * {@code command} array as its argument. This may result in
      * a {@link SecurityException} being thrown.
      *
      * <p>Starting an operating system process is highly system-dependent.
@@ -426,26 +953,42 @@
      * subclass of {@link IOException}.
      *
      * <p>Subsequent modifications to this process builder will not
-     * affect the returned {@link Process}.</p>
+     * affect the returned {@link Process}.
      *
-     * @return  A new {@link Process} object for managing the subprocess
+     * @return a new {@link Process} object for managing the subprocess
      *
-     * @throws  NullPointerException
-     *          If an element of the command list is null
+     * @throws NullPointerException
+     *         if an element of the command list is null
      *
-     * @throws  IndexOutOfBoundsException
-     *          If the command is an empty list (has size <code>0</code>)
+     * @throws IndexOutOfBoundsException
+     *         if the command is an empty list (has size {@code 0})
      *
-     * @throws  SecurityException
-     *          If a security manager exists and its
-     *          {@link SecurityManager#checkExec checkExec}
-     *          method doesn't allow creation of the subprocess
+     * @throws SecurityException
+     *         if a security manager exists and
+     *         <ul>
      *
-     * @throws  IOException
-     *          If an I/O error occurs
+     *         <li>its
+     *         {@link SecurityManager#checkExec checkExec}
+     *         method doesn't allow creation of the subprocess, or
      *
-     * @see     Runtime#exec(String[], String[], java.io.File)
-     * @see     SecurityManager#checkExec(String)
+     *         <li>the standard input to the subprocess was
+     *         {@linkplain #redirectInput redirected from a file}
+     *         and the security manager's
+     *         {@link SecurityManager#checkRead checkRead} method
+     *         denies read access to the file, or
+     *
+     *         <li>the standard output or standard error of the
+     *         subprocess was
+     *         {@linkplain #redirectOutput redirected to a file}
+     *         and the security manager's
+     *         {@link SecurityManager#checkWrite checkWrite} method
+     *         denies write access to the file
+     *
+     *         </ul>
+     *
+     * @throws IOException if an I/O error occurs
+     *
+     * @see Runtime#exec(String[], String[], java.io.File)
      */
     public Process start() throws IOException {
         // Must convert to array first -- a malicious user-supplied
@@ -467,6 +1010,7 @@
             return ProcessImpl.start(cmdarray,
                                      environment,
                                      dir,
+                                     redirects,
                                      redirectErrorStream);
         } catch (IOException e) {
             // It's much easier for us to create a high-quality error
--- a/src/share/classes/java/lang/StringCoding.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/StringCoding.java	Fri Mar 28 03:06:00 2008 -0700
@@ -53,22 +53,23 @@
 
     private StringCoding() { }
 
-    /* The cached coders for each thread
-     */
-    private static ThreadLocal decoder = new ThreadLocal();
-    private static ThreadLocal encoder = new ThreadLocal();
+    /** The cached coders for each thread */
+    private final static ThreadLocal<SoftReference<StringDecoder>> decoder =
+        new ThreadLocal<SoftReference<StringDecoder>>();
+    private final static ThreadLocal<SoftReference<StringEncoder>> encoder =
+        new ThreadLocal<SoftReference<StringEncoder>>();
 
     private static boolean warnUnsupportedCharset = true;
 
-    private static Object deref(ThreadLocal tl) {
-        SoftReference sr = (SoftReference)tl.get();
+    private static <T> T deref(ThreadLocal<SoftReference<T>> tl) {
+        SoftReference<T> sr = tl.get();
         if (sr == null)
             return null;
         return sr.get();
     }
 
-    private static void set(ThreadLocal tl, Object ob) {
-        tl.set(new SoftReference(ob));
+    private static <T> void set(ThreadLocal<SoftReference<T>> tl, T ob) {
+        tl.set(new SoftReference<T>(ob));
     }
 
     // Trim the given byte array to the given length
@@ -174,7 +175,7 @@
     static char[] decode(String charsetName, byte[] ba, int off, int len)
         throws UnsupportedEncodingException
     {
-        StringDecoder sd = (StringDecoder)deref(decoder);
+        StringDecoder sd = deref(decoder);
         String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
         if ((sd == null) || !(csn.equals(sd.requestedCharsetName())
                               || csn.equals(sd.charsetName()))) {
@@ -193,8 +194,7 @@
 
     static char[] decode(Charset cs, byte[] ba, int off, int len) {
         StringDecoder sd = new StringDecoder(cs, cs.name());
-        byte[] b = Arrays.copyOf(ba, ba.length);
-        return sd.decode(b, off, len);
+        return sd.decode(Arrays.copyOfRange(ba, off, off + len), 0, len);
     }
 
     static char[] decode(byte[] ba, int off, int len) {
@@ -273,7 +273,7 @@
     static byte[] encode(String charsetName, char[] ca, int off, int len)
         throws UnsupportedEncodingException
     {
-        StringEncoder se = (StringEncoder)deref(encoder);
+        StringEncoder se = deref(encoder);
         String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
         if ((se == null) || !(csn.equals(se.requestedCharsetName())
                               || csn.equals(se.charsetName()))) {
@@ -292,8 +292,7 @@
 
     static byte[] encode(Charset cs, char[] ca, int off, int len) {
         StringEncoder se = new StringEncoder(cs, cs.name());
-        char[] c = Arrays.copyOf(ca, ca.length);
-        return se.encode(c, off, len);
+        return se.encode(Arrays.copyOfRange(ca, off, off + len), 0, len);
     }
 
     static byte[] encode(char[] ca, int off, int len) {
--- a/src/share/classes/java/lang/ref/Finalizer.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/ref/Finalizer.java	Fri Mar 28 03:06:00 2008 -0700
@@ -121,8 +121,9 @@
        invokers of these methods from a stalled or deadlocked finalizer thread.
      */
     private static void forkSecondaryFinalizer(final Runnable proc) {
-        PrivilegedAction pa = new PrivilegedAction() {
-            public Object run() {
+        AccessController.doPrivileged(
+            new PrivilegedAction<Void>() {
+                public Void run() {
                 ThreadGroup tg = Thread.currentThread().getThreadGroup();
                 for (ThreadGroup tgn = tg;
                      tgn != null;
@@ -135,8 +136,7 @@
                     /* Ignore */
                 }
                 return null;
-            }};
-        AccessController.doPrivileged(pa);
+                }});
     }
 
     /* Called by Runtime.runFinalization() */
--- a/src/share/classes/java/lang/reflect/AccessibleObject.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/reflect/AccessibleObject.java	Fri Mar 28 03:06:00 2008 -0700
@@ -165,9 +165,9 @@
     // Reflection factory used by subclasses for creating field,
     // method, and constructor accessors. Note that this is called
     // very early in the bootstrapping process.
-    static final ReflectionFactory reflectionFactory = (ReflectionFactory)
-        AccessController.doPrivileged
-            (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
+    static final ReflectionFactory reflectionFactory =
+        AccessController.doPrivileged(
+            new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
 
     /**
      * @throws NullPointerException {@inheritDoc}
--- a/src/share/classes/java/lang/reflect/Modifier.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/reflect/Modifier.java	Fri Mar 28 03:06:00 2008 -0700
@@ -58,9 +58,8 @@
      */
     static {
         sun.reflect.ReflectionFactory factory =
-            (sun.reflect.ReflectionFactory) AccessController.doPrivileged(
-                new ReflectionFactory.GetReflectionFactoryAction()
-            );
+            AccessController.doPrivileged(
+                new ReflectionFactory.GetReflectionFactoryAction());
         factory.setLangReflectAccess(new java.lang.reflect.ReflectAccess());
     }
 
--- a/src/share/classes/java/lang/reflect/Proxy.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/lang/reflect/Proxy.java	Fri Mar 28 03:06:00 2008 -0700
@@ -33,6 +33,7 @@
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
+import java.util.List;
 import java.util.WeakHashMap;
 import sun.misc.ProxyGenerator;
 
@@ -230,7 +231,8 @@
         { InvocationHandler.class };
 
     /** maps a class loader to the proxy class cache for that loader */
-    private static Map loaderToCache = new WeakHashMap();
+    private static Map<ClassLoader, Map<List<String>, Object>> loaderToCache
+        = new WeakHashMap<ClassLoader, Map<List<String>, Object>>();
 
     /** marks that a particular proxy class is currently being generated */
     private static Object pendingGenerationMarker = new Object();
@@ -240,8 +242,8 @@
     private static Object nextUniqueNumberLock = new Object();
 
     /** set of all generated proxy classes, for isProxyClass implementation */
-    private static Map proxyClasses =
-        Collections.synchronizedMap(new WeakHashMap());
+    private static Map<Class<?>, Void> proxyClasses =
+        Collections.synchronizedMap(new WeakHashMap<Class<?>, Void>());
 
     /**
      * the invocation handler for this proxy instance.
@@ -353,7 +355,8 @@
         /* collect interface names to use as key for proxy class cache */
         String[] interfaceNames = new String[interfaces.length];
 
-        Set interfaceSet = new HashSet();       // for detecting duplicates
+        // for detecting duplicates
+        Set<Class<?>> interfaceSet = new HashSet<Class<?>>();
 
         for (int i = 0; i < interfaces.length; i++) {
             /*
@@ -401,16 +404,16 @@
          * representation of a class makes for an implicit weak
          * reference to the class.
          */
-        Object key = Arrays.asList(interfaceNames);
+        List<String> key = Arrays.asList(interfaceNames);
 
         /*
          * Find or create the proxy class cache for the class loader.
          */
-        Map cache;
+        Map<List<String>, Object> cache;
         synchronized (loaderToCache) {
-            cache = (Map) loaderToCache.get(loader);
+            cache = loaderToCache.get(loader);
             if (cache == null) {
-                cache = new HashMap();
+                cache = new HashMap<List<String>, Object>();
                 loaderToCache.put(loader, cache);
             }
             /*
@@ -442,7 +445,7 @@
             do {
                 Object value = cache.get(key);
                 if (value instanceof Reference) {
-                    proxyClass = (Class) ((Reference) value).get();
+                    proxyClass = (Class<?>) ((Reference) value).get();
                 }
                 if (proxyClass != null) {
                     // proxy class already generated: return it
@@ -544,7 +547,7 @@
              */
             synchronized (cache) {
                 if (proxyClass != null) {
-                    cache.put(key, new WeakReference(proxyClass));
+                    cache.put(key, new WeakReference<Class<?>>(proxyClass));
                 } else {
                     cache.remove(key);
                 }
@@ -595,14 +598,14 @@
         /*
          * Look up or generate the designated proxy class.
          */
-        Class cl = getProxyClass(loader, interfaces);
+        Class<?> cl = getProxyClass(loader, interfaces);
 
         /*
          * Invoke its constructor with the designated invocation handler.
          */
         try {
             Constructor cons = cl.getConstructor(constructorParams);
-            return (Object) cons.newInstance(new Object[] { h });
+            return cons.newInstance(new Object[] { h });
         } catch (NoSuchMethodException e) {
             throw new InternalError(e.toString());
         } catch (IllegalAccessException e) {
--- a/src/share/classes/java/net/AbstractPlainSocketImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/AbstractPlainSocketImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -664,7 +664,6 @@
     abstract void socketSetOption(int cmd, boolean on, Object value)
         throws SocketException;
     abstract int socketGetOption(int opt, Object iaContainerObj) throws SocketException;
-    abstract int socketGetOption1(int opt, Object iaContainerObj, FileDescriptor fd) throws SocketException;
     abstract void socketSendUrgentData(int data)
         throws IOException;
 
--- a/src/share/classes/java/net/DatagramSocket.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/DatagramSocket.java	Fri Mar 28 03:06:00 2008 -0700
@@ -287,8 +287,9 @@
         // DatagramSocketImpl.peekdata() is a protected method, therefore we need to use
         // getDeclaredMethod, therefore we need permission to access the member
         try {
-            AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                    public Object run() throws NoSuchMethodException {
+            AccessController.doPrivileged(
+                new PrivilegedExceptionAction<Void>() {
+                    public Void run() throws NoSuchMethodException {
                         Class[] cl = new Class[1];
                         cl[0] = DatagramPacket.class;
                         impl.getClass().getDeclaredMethod("peekData", cl);
--- a/src/share/classes/java/net/InterfaceAddress.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/InterfaceAddress.java	Fri Mar 28 03:06:00 2008 -0700
@@ -103,11 +103,9 @@
             return false;
         }
         InterfaceAddress cmp = (InterfaceAddress) obj;
-        if ((address != null & cmp.address == null) ||
-            (!address.equals(cmp.address)))
+        if ( !(address == null ? cmp.address == null : address.equals(cmp.address)) )
             return false;
-        if ((broadcast != null & cmp.broadcast == null) ||
-            (!broadcast.equals(cmp.broadcast)))
+        if ( !(broadcast  == null ? cmp.broadcast == null : broadcast.equals(cmp.broadcast)) )
             return false;
         if (maskLength != cmp.maskLength)
             return false;
--- a/src/share/classes/java/net/NetworkInterface.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/NetworkInterface.java	Fri Mar 28 03:06:00 2008 -0700
@@ -425,8 +425,6 @@
         return virtual;
     }
 
-    private native static long getSubnet0(String name, int ind) throws SocketException;
-    private native static Inet4Address getBroadcast0(String name, int ind) throws SocketException;
     private native static boolean isUp0(String name, int ind) throws SocketException;
     private native static boolean isLoopback0(String name, int ind) throws SocketException;
     private native static boolean supportsMulticast0(String name, int ind) throws SocketException;
--- a/src/share/classes/java/net/ServerSocket.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/ServerSocket.java	Fri Mar 28 03:06:00 2008 -0700
@@ -247,8 +247,9 @@
         // SocketImpl.connect() is a protected method, therefore we need to use
         // getDeclaredMethod, therefore we need permission to access the member
         try {
-            AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                    public Object run() throws NoSuchMethodException {
+            AccessController.doPrivileged(
+                new PrivilegedExceptionAction<Void>() {
+                    public Void run() throws NoSuchMethodException {
                         Class[] cl = new Class[2];
                         cl[0] = SocketAddress.class;
                         cl[1] = Integer.TYPE;
--- a/src/share/classes/java/net/Socket.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/Socket.java	Fri Mar 28 03:06:00 2008 -0700
@@ -731,7 +731,8 @@
      * then this method will continue to return the connected address
      * after the socket is closed.
      *
-     * @return a <code>SocketAddress</code> reprensenting the remote endpoint of this
+
+     * @return a <code>SocketAddress</code> representing the remote endpoint of this
      *         socket, or <code>null</code> if it is not connected yet.
      * @see #getInetAddress()
      * @see #getPort()
@@ -847,9 +848,9 @@
         final Socket s = this;
         InputStream is = null;
         try {
-            is = (InputStream)
-                AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                    public Object run() throws IOException {
+            is = AccessController.doPrivileged(
+                new PrivilegedExceptionAction<InputStream>() {
+                    public InputStream run() throws IOException {
                         return impl.getInputStream();
                     }
                 });
@@ -887,9 +888,9 @@
         final Socket s = this;
         OutputStream os = null;
         try {
-            os = (OutputStream)
-                AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                    public Object run() throws IOException {
+            os = AccessController.doPrivileged(
+                new PrivilegedExceptionAction<OutputStream>() {
+                    public OutputStream run() throws IOException {
                         return impl.getOutputStream();
                     }
                 });
--- a/src/share/classes/java/net/SocksSocketImpl.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/SocksSocketImpl.java	Fri Mar 28 03:06:00 2008 -0700
@@ -78,8 +78,8 @@
     {
         try {
             AccessController.doPrivileged(
-                  new java.security.PrivilegedExceptionAction() {
-                          public Object run() throws IOException {
+                new java.security.PrivilegedExceptionAction<Void>() {
+                    public Void run() throws IOException {
                               superConnectServer(host, port, timeout);
                               cmdIn = getInputStream();
                               cmdOut = getOutputStream();
@@ -129,10 +129,10 @@
             String userName;
             String password = null;
             final InetAddress addr = InetAddress.getByName(server);
-            PasswordAuthentication pw = (PasswordAuthentication)
+            PasswordAuthentication pw =
                 java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
-                            public Object run() {
+                    new java.security.PrivilegedAction<PasswordAuthentication>() {
+                        public PasswordAuthentication run() {
                                 return Authenticator.requestPasswordAuthentication(
                                        server, addr, port, "SOCKS5", "SOCKS authentication", null);
                             }
@@ -339,10 +339,9 @@
             // This is the general case
             // server is not null only when the socket was created with a
             // specified proxy in which case it does bypass the ProxySelector
-            ProxySelector sel = (ProxySelector)
-                java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
-                        public Object run() {
+            ProxySelector sel = java.security.AccessController.doPrivileged(
+                new java.security.PrivilegedAction<ProxySelector>() {
+                    public ProxySelector run() {
                             return ProxySelector.getDefault();
                         }
                     });
@@ -652,10 +651,9 @@
             // This is the general case
             // server is not null only when the socket was created with a
             // specified proxy in which case it does bypass the ProxySelector
-            ProxySelector sel = (ProxySelector)
-                java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
-                        public Object run() {
+            ProxySelector sel = java.security.AccessController.doPrivileged(
+                new java.security.PrivilegedAction<ProxySelector>() {
+                    public ProxySelector run() {
                             return ProxySelector.getDefault();
                         }
                     });
@@ -701,8 +699,9 @@
 
                 // Connects to the SOCKS server
                 try {
-                    AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                            public Object run() throws Exception {
+                    AccessController.doPrivileged(
+                        new PrivilegedExceptionAction<Void>() {
+                            public Void run() throws Exception {
                                 cmdsock = new Socket(new PlainSocketImpl());
                                 cmdsock.connect(new InetSocketAddress(server, port));
                                 cmdIn = cmdsock.getInputStream();
@@ -731,8 +730,9 @@
             }
         } else {
             try {
-                AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                        public Object run() throws Exception {
+                AccessController.doPrivileged(
+                    new PrivilegedExceptionAction<Void>() {
+                        public Void run() throws Exception {
                             cmdsock = new Socket(new PlainSocketImpl());
                             cmdsock.connect(new InetSocketAddress(server, port));
                             cmdIn = cmdsock.getInputStream();
--- a/src/share/classes/java/net/URLClassLoader.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/URLClassLoader.java	Fri Mar 28 03:06:00 2008 -0700
@@ -205,9 +205,9 @@
          throws ClassNotFoundException
     {
         try {
-            return (Class)
-                AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                    public Object run() throws ClassNotFoundException {
+            return AccessController.doPrivileged(
+                new PrivilegedExceptionAction<Class>() {
+                    public Class run() throws ClassNotFoundException {
                         String path = name.replace('.', '/').concat(".class");
                         Resource res = ucp.getResource(path, false);
                         if (res != null) {
@@ -376,9 +376,9 @@
         /*
          * The same restriction to finding classes applies to resources
          */
-        URL url =
-            (URL) AccessController.doPrivileged(new PrivilegedAction() {
-                public Object run() {
+        URL url = AccessController.doPrivileged(
+            new PrivilegedAction<URL>() {
+                public URL run() {
                     return ucp.findResource(name, true);
                 }
             }, acc);
@@ -397,7 +397,7 @@
     public Enumeration<URL> findResources(final String name)
         throws IOException
     {
-        final Enumeration e = ucp.findResources(name, true);
+        final Enumeration<URL> e = ucp.findResources(name, true);
 
         return new Enumeration<URL>() {
             private URL url = null;
@@ -407,9 +407,9 @@
                     return true;
                 }
                 do {
-                    URL u = (URL)
-                        AccessController.doPrivileged(new PrivilegedAction() {
-                            public Object run() {
+                    URL u = AccessController.doPrivileged(
+                        new PrivilegedAction<URL>() {
+                            public URL run() {
                                 if (!e.hasMoreElements())
                                     return null;
                                 return e.nextElement();
@@ -515,8 +515,8 @@
             final SecurityManager sm = System.getSecurityManager();
             if (sm != null) {
                 final Permission fp = p;
-                AccessController.doPrivileged(new PrivilegedAction() {
-                    public Object run() throws SecurityException {
+                AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                    public Void run() throws SecurityException {
                         sm.checkPermission(fp);
                         return null;
                     }
@@ -544,9 +544,9 @@
         // Save the caller's context
         AccessControlContext acc = AccessController.getContext();
         // Need a privileged block to create the class loader
-        URLClassLoader ucl =
-            (URLClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
-                public Object run() {
+        URLClassLoader ucl = AccessController.doPrivileged(
+            new PrivilegedAction<URLClassLoader>() {
+                public URLClassLoader run() {
                     return new FactoryURLClassLoader(urls, parent);
                 }
             });
@@ -571,9 +571,9 @@
         // Save the caller's context
         AccessControlContext acc = AccessController.getContext();
         // Need a privileged block to create the class loader
-        URLClassLoader ucl = (URLClassLoader)
-            AccessController.doPrivileged(new PrivilegedAction() {
-                public Object run() {
+        URLClassLoader ucl = AccessController.doPrivileged(
+            new PrivilegedAction<URLClassLoader>() {
+                public URLClassLoader run() {
                     return new FactoryURLClassLoader(urls);
                 }
             });
--- a/src/share/classes/java/net/URLConnection.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/net/URLConnection.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1072,7 +1072,7 @@
      * properties to be appended into a single property.
      *
      * @param   key     the keyword by which the request is known
-     *                  (e.g., "<code>accept</code>").
+     *                  (e.g., "<code>Accept</code>").
      * @param   value   the value associated with it.
      * @throws IllegalStateException if already connected
      * @throws NullPointerException if key is <CODE>null</CODE>
@@ -1096,7 +1096,7 @@
      * existing values associated with the same key.
      *
      * @param   key     the keyword by which the request is known
-     *                  (e.g., "<code>accept</code>").
+     *                  (e.g., "<code>Accept</code>").
      * @param   value  the value associated with it.
      * @throws IllegalStateException if already connected
      * @throws NullPointerException if key is null
@@ -1120,7 +1120,7 @@
      * Returns the value of the named general request property for this
      * connection.
      *
-     * @param key the keyword by which the request is known (e.g., "accept").
+     * @param key the keyword by which the request is known (e.g., "Accept").
      * @return  the value of the named general request property for this
      *           connection. If key is null, then null is returned.
      * @throws IllegalStateException if already connected
@@ -1164,7 +1164,7 @@
      * these properties.
      *
      * @param   key     the keyword by which the request is known
-     *                  (e.g., "<code>accept</code>").
+     *                  (e.g., "<code>Accept</code>").
      * @param   value   the value associated with the key.
      *
      * @see java.net.URLConnection#setRequestProperty(java.lang.String,java.lang.String)
@@ -1183,7 +1183,7 @@
      * Returns the value of the default request property. Default request
      * properties are set for every connection.
      *
-     * @param key the keyword by which the request is known (e.g., "accept").
+     * @param key the keyword by which the request is known (e.g., "Accept").
      * @return  the value of the default request property
      * for the specified key.
      *
--- a/src/share/classes/java/nio/StringCharBuffer.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/nio/StringCharBuffer.java	Fri Mar 28 03:06:00 2008 -0700
@@ -60,16 +60,9 @@
         str = s;
     }
 
-    private StringCharBuffer(CharSequence s, int mark,
-                             int pos, int limit, int cap)
-    {
-        super(mark, pos, limit, cap);
-        str = s;
-    }
-
     public CharBuffer duplicate() {
         return new StringCharBuffer(str, markValue(),
-                                    position(), limit(), capacity());
+                                    position(), limit(), capacity(), offset);
     }
 
     public CharBuffer asReadOnlyBuffer() {
@@ -77,11 +70,11 @@
     }
 
     public final char get() {
-        return str.charAt(nextGetIndex());
+        return str.charAt(nextGetIndex() + offset);
     }
 
     public final char get(int index) {
-        return str.charAt(checkIndex(index));
+        return str.charAt(checkIndex(index) + offset);
     }
 
     // ## Override bulk get methods for better performance
@@ -103,15 +96,16 @@
     }
 
     final String toString(int start, int end) {
-        return str.toString().substring(start, end);
+        return str.toString().substring(start + offset, end + offset);
     }
 
     public final CharSequence subSequence(int start, int end) {
         try {
             int pos = position();
-            return new StringCharBuffer(str,
+            return new StringCharBuffer(str, -1,
                                         pos + checkIndex(start, pos),
-                                        pos + checkIndex(end, pos));
+                                        pos + checkIndex(end, pos),
+                                        remaining(), offset);
         } catch (IllegalArgumentException x) {
             throw new IndexOutOfBoundsException();
         }
--- a/src/share/classes/java/nio/channels/Channels.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/nio/channels/Channels.java	Fri Mar 28 03:06:00 2008 -0700
@@ -66,7 +66,27 @@
     private Channels() { }              // No instantiation
 
 
-    private static int write(WritableByteChannel ch, ByteBuffer bb)
+    /**
+     * Write all remaining bytes in buffer to the given channel.
+     * If the channel is selectable then it must be configured blocking.
+     */
+    private static void writeFullyImpl(WritableByteChannel ch, ByteBuffer bb)
+        throws IOException
+    {
+        while (bb.remaining() > 0) {
+            int n = ch.write(bb);
+            if (n <= 0)
+                throw new RuntimeException("no bytes written");
+        }
+    }
+
+    /**
+     * Write all remaining bytes in buffer to the given channel.
+     *
+     * @throws  IllegalBlockingException
+     *          If the channel is selectable and configured non-blocking.
+     */
+    private static void writeFully(WritableByteChannel ch, ByteBuffer bb)
         throws IOException
     {
         if (ch instanceof SelectableChannel) {
@@ -74,14 +94,13 @@
             synchronized (sc.blockingLock()) {
                 if (!sc.isBlocking())
                     throw new IllegalBlockingModeException();
-                return ch.write(bb);
+                writeFullyImpl(ch, bb);
             }
         } else {
-            return ch.write(bb);
+            writeFullyImpl(ch, bb);
         }
     }
 
-
     // -- Byte streams from channels --
 
     /**
@@ -148,7 +167,7 @@
                     bb.position(off);
                     this.bb = bb;
                     this.bs = bs;
-                    Channels.write(ch, bb);
+                    Channels.writeFully(ch, bb);
                 }
 
                 public void close() throws IOException {
--- a/src/share/classes/java/nio/channels/spi/SelectorProvider.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/nio/channels/spi/SelectorProvider.java	Fri Mar 28 03:06:00 2008 -0700
@@ -167,9 +167,9 @@
         synchronized (lock) {
             if (provider != null)
                 return provider;
-            return (SelectorProvider)AccessController
-                .doPrivileged(new PrivilegedAction() {
-                        public Object run() {
+            return AccessController.doPrivileged(
+                new PrivilegedAction<SelectorProvider>() {
+                    public SelectorProvider run() {
                             if (loadProviderFromProperty())
                                 return provider;
                             if (loadProviderAsService())
--- a/src/share/classes/java/nio/charset/Charset.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/nio/charset/Charset.java	Fri Mar 28 03:06:00 2008 -0700
@@ -212,36 +212,47 @@
  *
  * <h4>Terminology</h4>
  *
- * <p> The name of this class is taken from the terms used in <a
- * href="http://www.ietf.org/rfc/rfc2278.txt""><i>RFC&nbsp;2278</i></a>.  In that
- * document a <i>charset</i> is defined as the combination of a coded character
- * set and a character-encoding scheme.
+ * <p> The name of this class is taken from the terms used in
+ * <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
+ * In that document a <i>charset</i> is defined as the combination of
+ * one or more coded character sets and a character-encoding scheme.
+ * (This definition is confusing; some other software systems define
+ * <i>charset</i> as a synonym for <i>coded character set</i>.)
  *
  * <p> A <i>coded character set</i> is a mapping between a set of abstract
  * characters and a set of integers.  US-ASCII, ISO&nbsp;8859-1,
- * JIS&nbsp;X&nbsp;0201, and full Unicode, which is the same as
- * ISO&nbsp;10646-1, are examples of coded character sets.
+ * JIS&nbsp;X&nbsp;0201, and Unicode are examples of coded character sets.
  *
- * <p> A <i>character-encoding scheme</i> is a mapping between a coded
- * character set and a set of octet (eight-bit byte) sequences.  UTF-8, UCS-2,
- * UTF-16, ISO&nbsp;2022, and EUC are examples of character-encoding schemes.
- * Encoding schemes are often associated with a particular coded character set;
- * UTF-8, for example, is used only to encode Unicode.  Some schemes, however,
- * are associated with multiple character sets; EUC, for example, can be used
- * to encode characters in a variety of Asian character sets.
+ * <p> Some standards have defined a <i>character set</i> to be simply a
+ * set of abstract characters without an associated assigned numbering.
+ * An alphabet is an example of such a character set.  However, the subtle
+ * distinction between <i>character set</i> and <i>coded character set</i>
+ * is rarely used in practice; the former has become a short form for the
+ * latter, including in the Java API specification.
+ *
+ * <p> A <i>character-encoding scheme</i> is a mapping between one or more
+ * coded character sets and a set of octet (eight-bit byte) sequences.
+ * UTF-8, UTF-16, ISO&nbsp;2022, and EUC are examples of
+ * character-encoding schemes.  Encoding schemes are often associated with
+ * a particular coded character set; UTF-8, for example, is used only to
+ * encode Unicode.  Some schemes, however, are associated with multiple
+ * coded character sets; EUC, for example, can be used to encode
+ * characters in a variety of Asian coded character sets.
  *
  * <p> When a coded character set is used exclusively with a single
- * character-encoding scheme then the corresponding charset is usually named
- * for the character set; otherwise a charset is usually named for the encoding
- * scheme and, possibly, the locale of the character sets that it supports.
- * Hence <tt>US-ASCII</tt> is the name of the charset for US-ASCII while
+ * character-encoding scheme then the corresponding charset is usually
+ * named for the coded character set; otherwise a charset is usually named
+ * for the encoding scheme and, possibly, the locale of the coded
+ * character sets that it supports.  Hence <tt>US-ASCII</tt> is both the
+ * name of a coded character set and of the charset that encodes it, while
  * <tt>EUC-JP</tt> is the name of the charset that encodes the
  * JIS&nbsp;X&nbsp;0201, JIS&nbsp;X&nbsp;0208, and JIS&nbsp;X&nbsp;0212
- * character sets.
+ * coded character sets for the Japanese language.
  *
  * <p> The native character encoding of the Java programming language is
- * UTF-16.  A charset in the Java platform therefore defines a mapping between
- * sequences of sixteen-bit UTF-16 code units and sequences of bytes. </p>
+ * UTF-16.  A charset in the Java platform therefore defines a mapping
+ * between sequences of sixteen-bit UTF-16 code units (that is, sequences
+ * of chars) and sequences of bytes. </p>
  *
  *
  * @author Mark Reinhold
--- a/src/share/classes/java/rmi/activation/ActivationGroupDesc.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/rmi/activation/ActivationGroupDesc.java	Fri Mar 28 03:06:00 2008 -0700
@@ -263,7 +263,7 @@
          * @since 1.2
          */
         public String[] getCommandOptions() {
-            return (String[]) options.clone();
+            return options.clone();
         }
 
         /**
--- a/src/share/classes/java/rmi/dgc/VMID.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/rmi/dgc/VMID.java	Fri Mar 28 03:06:00 2008 -0700
@@ -136,9 +136,9 @@
         /*
          * Get the local host's IP address.
          */
-        byte[] addr = (byte[]) java.security.AccessController.doPrivileged(
-            new PrivilegedAction() {
-            public Object run() {
+        byte[] addr = java.security.AccessController.doPrivileged(
+            new PrivilegedAction<byte[]>() {
+            public byte[] run() {
                 try {
                     return InetAddress.getLocalHost().getAddress();
                 } catch (Exception e) {
--- a/src/share/classes/java/security/AccessControlContext.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/security/AccessControlContext.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2008 Sun Microsystems, Inc.  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
@@ -322,7 +322,7 @@
                     debug.println("access denied " + perm);
                 }
 
-                if (Debug.isOn("failure")) {
+                if (Debug.isOn("failure") && debug != null) {
                     // Want to make sure this is always displayed for failure,
                     // but do not want to display again if already displayed
                     // above.
--- a/src/share/classes/java/security/KeyStore.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/security/KeyStore.java	Fri Mar 28 03:06:00 2008 -0700
@@ -789,7 +789,7 @@
      * @param alias the alias name
      *
      * @return the certificate chain (ordered with the user's certificate first
-     * and the root certificate authority last), or null if the given alias
+     * followed by zero or more certificate authorities), or null if the given alias
      * does not exist or does not contain a certificate chain
      *
      * @exception KeyStoreException if the keystore has not been initialized
--- a/src/share/classes/java/security/cert/TrustAnchor.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/security/cert/TrustAnchor.java	Fri Mar 28 03:06:00 2008 -0700
@@ -275,7 +275,7 @@
             ncBytes = null;
             nc = null;
         } else {
-            ncBytes = (byte []) bytes.clone();
+            ncBytes = bytes.clone();
             // validate DER encoding
             try {
                 nc = new NameConstraintsExtension(Boolean.FALSE, bytes);
@@ -309,7 +309,7 @@
      *         or <code>null</code> if not set.
      */
     public final byte [] getNameConstraints() {
-        return (ncBytes == null ? null : (byte []) ncBytes.clone());
+        return ncBytes == null ? null : ncBytes.clone();
     }
 
     /**
--- a/src/share/classes/java/security/cert/X509CertSelector.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/security/cert/X509CertSelector.java	Fri Mar 28 03:06:00 2008 -0700
@@ -381,7 +381,7 @@
         if (subjectKeyID == null) {
             this.subjectKeyID = null;
         } else {
-            this.subjectKeyID = (byte[])subjectKeyID.clone();
+            this.subjectKeyID = subjectKeyID.clone();
         }
     }
 
@@ -442,7 +442,7 @@
         if (authorityKeyID == null) {
             this.authorityKeyID = null;
         } else {
-            this.authorityKeyID = (byte[])authorityKeyID.clone();
+            this.authorityKeyID = authorityKeyID.clone();
         }
     }
 
@@ -566,7 +566,7 @@
             subjectPublicKey = null;
             subjectPublicKeyBytes = null;
         } else {
-            subjectPublicKeyBytes = (byte[])key.clone();
+            subjectPublicKeyBytes = key.clone();
             subjectPublicKey = X509Key.parse(new DerValue(subjectPublicKeyBytes));
         }
     }
@@ -590,7 +590,7 @@
         if (keyUsage == null) {
             this.keyUsage = null;
         } else {
-            this.keyUsage = (boolean[])keyUsage.clone();
+            this.keyUsage = keyUsage.clone();
         }
     }
 
@@ -1041,7 +1041,7 @@
             ncBytes = null;
             nc = null;
         } else {
-            ncBytes = (byte[])bytes.clone();
+            ncBytes = bytes.clone();
             nc = new NameConstraintsExtension(FALSE, bytes);
         }
     }
@@ -1438,7 +1438,7 @@
         if (subjectKeyID == null) {
             return null;
         }
-        return (byte[])subjectKeyID.clone();
+        return subjectKeyID.clone();
     }
 
     /**
@@ -1457,7 +1457,7 @@
         if (authorityKeyID == null) {
           return null;
         }
-        return (byte[])authorityKeyID.clone();
+        return authorityKeyID.clone();
     }
 
     /**
@@ -1546,7 +1546,7 @@
         if (keyUsage == null) {
             return null;
         }
-        return (boolean[])keyUsage.clone();
+        return keyUsage.clone();
     }
 
     /**
@@ -1736,7 +1736,7 @@
         if (ncBytes == null) {
             return null;
         } else {
-            return (byte[]) ncBytes.clone();
+            return ncBytes.clone();
         }
     }
 
--- a/src/share/classes/java/util/ArrayList.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/ArrayList.java	Fri Mar 28 03:06:00 2008 -0700
@@ -892,7 +892,7 @@
         private final AbstractList<E> parent;
         private final int parentOffset;
         private final int offset;
-        private int size;
+        int size;
 
         SubList(AbstractList<E> parent,
                 int offset, int fromIndex, int toIndex) {
@@ -971,6 +971,7 @@
         public ListIterator<E> listIterator(final int index) {
             checkForComodification();
             rangeCheckForAdd(index);
+            final int offset = this.offset;
 
             return new ListIterator<E>() {
                 int cursor = index;
--- a/src/share/classes/java/util/Arrays.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/Arrays.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1088,7 +1088,7 @@
      *          <i>mutually comparable</i> (for example, strings and integers).
      */
     public static void sort(Object[] a) {
-        Object[] aux = (Object[])a.clone();
+        Object[] aux = a.clone();
         mergeSort(aux, a, 0, a.length, 0);
     }
 
@@ -1216,7 +1216,7 @@
      *          not <i>mutually comparable</i> using the specified comparator.
      */
     public static <T> void sort(T[] a, Comparator<? super T> c) {
-        T[] aux = (T[])a.clone();
+        T[] aux = a.clone();
         if (c==null)
             mergeSort(aux, a, 0, a.length, 0);
         else
@@ -1257,7 +1257,7 @@
     public static <T> void sort(T[] a, int fromIndex, int toIndex,
                                 Comparator<? super T> c) {
         rangeCheck(a.length, fromIndex, toIndex);
-        T[] aux = (T[])copyOfRange(a, fromIndex, toIndex);
+        T[] aux = copyOfRange(a, fromIndex, toIndex);
         if (c==null)
             mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
         else
@@ -4128,7 +4128,7 @@
         if (a.length != 0 && bufLen <= 0)
             bufLen = Integer.MAX_VALUE;
         StringBuilder buf = new StringBuilder(bufLen);
-        deepToString(a, buf, new HashSet());
+        deepToString(a, buf, new HashSet<Object[]>());
         return buf.toString();
     }
 
--- a/src/share/classes/java/util/EnumMap.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/EnumMap.java	Fri Mar 28 03:06:00 2008 -0700
@@ -140,7 +140,7 @@
     public EnumMap(EnumMap<K, ? extends V> m) {
         keyType = m.keyType;
         keyUniverse = m.keyUniverse;
-        vals = (Object[]) m.vals.clone();
+        vals = m.vals.clone();
         size = m.size;
     }
 
@@ -161,7 +161,7 @@
             EnumMap<K, ? extends V> em = (EnumMap<K, ? extends V>) m;
             keyType = em.keyType;
             keyUniverse = em.keyUniverse;
-            vals = (Object[]) em.vals.clone();
+            vals = em.vals.clone();
             size = em.size;
         } else {
             if (m.isEmpty())
@@ -257,7 +257,7 @@
     public V put(K key, V value) {
         typeCheck(key);
 
-        int index = ((Enum)key).ordinal();
+        int index = key.ordinal();
         Object oldValue = vals[index];
         vals[index] = maskNull(value);
         if (oldValue == null)
@@ -662,7 +662,7 @@
         } catch(CloneNotSupportedException e) {
             throw new AssertionError();
         }
-        result.vals = (Object[]) result.vals.clone();
+        result.vals = result.vals.clone();
         return result;
     }
 
--- a/src/share/classes/java/util/HashMap.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/HashMap.java	Fri Mar 28 03:06:00 2008 -0700
@@ -173,7 +173,7 @@
      * rehash).  This field is used to make iterators on Collection-views of
      * the HashMap fail-fast.  (See ConcurrentModificationException).
      */
-    transient volatile int modCount;
+    transient int modCount;
 
     /**
      * Constructs an empty <tt>HashMap</tt> with the specified initial
--- a/src/share/classes/java/util/Hashtable.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/Hashtable.java	Fri Mar 28 03:06:00 2008 -0700
@@ -27,7 +27,7 @@
 import java.io.*;
 
 /**
- * This class implements a hashtable, which maps keys to values. Any
+ * This class implements a hash table, which maps keys to values. Any
  * non-<code>null</code> object can be used as a key or as a value. <p>
  *
  * To successfully store and retrieve objects from a hashtable, the
@@ -100,9 +100,15 @@
  *
  * <p>As of the Java 2 platform v1.2, this class was retrofitted to
  * implement the {@link Map} interface, making it a member of the
- * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java
- * Collections Framework</a>.  Unlike the new collection
- * implementations, {@code Hashtable} is synchronized.
+ * <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ *
+ * Java Collections Framework</a>.  Unlike the new collection
+ * implementations, {@code Hashtable} is synchronized.  If a
+ * thread-safe implementation is not needed, it is recommended to use
+ * {@link HashMap} in place of {@code Hashtable}.  If a thread-safe
+ * highly-concurrent implementation is desired, then it is recommended
+ * to use {@link java.util.concurrent.ConcurrentHashMap} in place of
+ * {@code Hashtable}.
  *
  * @author  Arthur van Hoff
  * @author  Josh Bloch
--- a/src/share/classes/java/util/IdentityHashMap.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/IdentityHashMap.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2008 Sun Microsystems, Inc.  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
@@ -173,7 +173,7 @@
     /**
      * The number of modifications, to support fast-fail iterators
      */
-    private transient volatile int modCount;
+    private transient int modCount;
 
     /**
      * The next size value at which to resize (capacity * load factor).
@@ -701,7 +701,7 @@
         try {
             IdentityHashMap<K,V> m = (IdentityHashMap<K,V>) super.clone();
             m.entrySet = null;
-            m.table = (Object[])table.clone();
+            m.table = table.clone();
             return m;
         } catch (CloneNotSupportedException e) {
             throw new InternalError();
@@ -749,7 +749,6 @@
             expectedModCount = ++modCount;
             int deletedSlot = lastReturnedIndex;
             lastReturnedIndex = -1;
-            size--;
             // back up index to revisit new contents after deletion
             index = deletedSlot;
             indexValid = false;
@@ -782,6 +781,8 @@
                 return;
             }
 
+            size--;
+
             Object item;
             for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
                  i = nextKeyIndex(i, len)) {
@@ -975,7 +976,7 @@
          */
         public boolean removeAll(Collection<?> c) {
             boolean modified = false;
-            for (Iterator i = iterator(); i.hasNext(); ) {
+            for (Iterator<K> i = iterator(); i.hasNext(); ) {
                 if (c.contains(i.next())) {
                     i.remove();
                     modified = true;
@@ -1033,7 +1034,7 @@
             return containsValue(o);
         }
         public boolean remove(Object o) {
-            for (Iterator i = iterator(); i.hasNext(); ) {
+            for (Iterator<V> i = iterator(); i.hasNext(); ) {
                 if (i.next() == o) {
                     i.remove();
                     return true;
@@ -1121,7 +1122,7 @@
          */
         public boolean removeAll(Collection<?> c) {
             boolean modified = false;
-            for (Iterator i = iterator(); i.hasNext(); ) {
+            for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); ) {
                 if (c.contains(i.next())) {
                     i.remove();
                     modified = true;
--- a/src/share/classes/java/util/JumboEnumSet.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/JumboEnumSet.java	Fri Mar 28 03:06:00 2008 -0700
@@ -364,7 +364,7 @@
 
     public EnumSet<E> clone() {
         JumboEnumSet<E> result = (JumboEnumSet<E>) super.clone();
-        result.elements = (long[]) result.elements.clone();
+        result.elements = result.elements.clone();
         return result;
     }
 }
--- a/src/share/classes/java/util/Random.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/Random.java	Fri Mar 28 03:06:00 2008 -0700
@@ -504,7 +504,7 @@
 
         // The seed is read in as {@code long} for
         // historical reasons, but it is converted to an AtomicLong.
-        long seedVal = (long) fields.get("seed", -1L);
+        long seedVal = fields.get("seed", -1L);
         if (seedVal < 0)
           throw new java.io.StreamCorruptedException(
                               "Random: invalid seed");
--- a/src/share/classes/java/util/TreeSet.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/TreeSet.java	Fri Mar 28 03:06:00 2008 -0700
@@ -195,7 +195,7 @@
      * @since 1.6
      */
     public NavigableSet<E> descendingSet() {
-        return new TreeSet(m.descendingMap());
+        return new TreeSet<E>(m.descendingMap());
     }
 
     /**
@@ -505,8 +505,8 @@
         s.writeInt(m.size());
 
         // Write out all elements in the proper order.
-        for (Iterator i=m.keySet().iterator(); i.hasNext(); )
-            s.writeObject(i.next());
+        for (E e : m.keySet())
+            s.writeObject(e);
     }
 
     /**
--- a/src/share/classes/java/util/Vector.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/Vector.java	Fri Mar 28 03:06:00 2008 -0700
@@ -64,15 +64,15 @@
  *
  * <p>As of the Java 2 platform v1.2, this class was retrofitted to
  * implement the {@link List} interface, making it a member of the
- * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java
- * Collections Framework</a>.  Unlike the new collection
- * implementations, {@code Vector} is synchronized.
+ * <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ * Java Collections Framework</a>.  Unlike the new collection
+ * implementations, {@code Vector} is synchronized.  If a thread-safe
+ * implementation is not needed, it is recommended to use {@link
+ * ArrayList} in place of {@code Vector}.
  *
  * @author  Lee Boynton
  * @author  Jonathan Payne
  * @see Collection
- * @see List
- * @see ArrayList
  * @see LinkedList
  * @since   JDK1.0
  */
--- a/src/share/classes/java/util/WeakHashMap.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/WeakHashMap.java	Fri Mar 28 03:06:00 2008 -0700
@@ -29,7 +29,8 @@
 
 
 /**
- * A hashtable-based <tt>Map</tt> implementation with <em>weak keys</em>.
+ * Hash table based implementation of the <tt>Map</tt> interface, with
+ * <em>weak keys</em>.
  * An entry in a <tt>WeakHashMap</tt> will automatically be removed when
  * its key is no longer in ordinary use.  More precisely, the presence of a
  * mapping for a given key will not prevent the key from being discarded by the
@@ -181,7 +182,7 @@
      *
      * @see ConcurrentModificationException
      */
-    volatile int modCount;
+    int modCount;
 
     @SuppressWarnings("unchecked")
     private Entry<K,V>[] newTable(int n) {
--- a/src/share/classes/java/util/concurrent/DelayQueue.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/concurrent/DelayQueue.java	Fri Mar 28 03:06:00 2008 -0700
@@ -69,10 +69,34 @@
     implements BlockingQueue<E> {
 
     private transient final ReentrantLock lock = new ReentrantLock();
-    private transient final Condition available = lock.newCondition();
     private final PriorityQueue<E> q = new PriorityQueue<E>();
 
     /**
+     * Thread designated to wait for the element at the head of
+     * the queue.  This variant of the Leader-Follower pattern
+     * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
+     * minimize unnecessary timed waiting.  When a thread becomes
+     * the leader, it waits only for the next delay to elapse, but
+     * other threads await indefinitely.  The leader thread must
+     * signal some other thread before returning from take() or
+     * poll(...), unless some other thread becomes leader in the
+     * interim.  Whenever the head of the queue is replaced with
+     * an element with an earlier expiration time, the leader
+     * field is invalidated by being reset to null, and some
+     * waiting thread, but not necessarily the current leader, is
+     * signalled.  So waiting threads must be prepared to acquire
+     * and lose leadership while waiting.
+     */
+    private Thread leader = null;
+
+    /**
+     * Condition signalled when a newer element becomes available
+     * at the head of the queue or a new thread may need to
+     * become leader.
+     */
+    private final Condition available = lock.newCondition();
+
+    /**
      * Creates a new <tt>DelayQueue</tt> that is initially empty.
      */
     public DelayQueue() {}
@@ -111,10 +135,11 @@
         final ReentrantLock lock = this.lock;
         lock.lock();
         try {
-            E first = q.peek();
             q.offer(e);
-            if (first == null || e.compareTo(first) < 0)
-                available.signalAll();
+            if (q.peek() == e) {
+                leader = null;
+                available.signal();
+            }
             return true;
         } finally {
             lock.unlock();
@@ -160,13 +185,8 @@
             E first = q.peek();
             if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
                 return null;
-            else {
-                E x = q.poll();
-                assert x != null;
-                if (q.size() != 0)
-                    available.signalAll();
-                return x;
-            }
+            else
+                return q.poll();
         } finally {
             lock.unlock();
         }
@@ -185,23 +205,29 @@
         try {
             for (;;) {
                 E first = q.peek();
-                if (first == null) {
+                if (first == null)
                     available.await();
-                } else {
-                    long delay =  first.getDelay(TimeUnit.NANOSECONDS);
-                    if (delay > 0) {
-                        long tl = available.awaitNanos(delay);
-                    } else {
-                        E x = q.poll();
-                        assert x != null;
-                        if (q.size() != 0)
-                            available.signalAll(); // wake up other takers
-                        return x;
-
+                else {
+                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                    if (delay <= 0)
+                        return q.poll();
+                    else if (leader != null)
+                        available.await();
+                    else {
+                        Thread thisThread = Thread.currentThread();
+                        leader = thisThread;
+                        try {
+                            available.awaitNanos(delay);
+                        } finally {
+                            if (leader == thisThread)
+                                leader = null;
+                        }
                     }
                 }
             }
         } finally {
+            if (leader == null && q.peek() != null)
+                available.signal();
             lock.unlock();
         }
     }
@@ -230,23 +256,28 @@
                         nanos = available.awaitNanos(nanos);
                 } else {
                     long delay = first.getDelay(TimeUnit.NANOSECONDS);
-                    if (delay > 0) {
-                        if (nanos <= 0)
-                            return null;
-                        if (delay > nanos)
-                            delay = nanos;
-                        long timeLeft = available.awaitNanos(delay);
-                        nanos -= delay - timeLeft;
-                    } else {
-                        E x = q.poll();
-                        assert x != null;
-                        if (q.size() != 0)
-                            available.signalAll();
-                        return x;
+                    if (delay <= 0)
+                        return q.poll();
+                    if (nanos <= 0)
+                        return null;
+                    if (nanos < delay || leader != null)
+                        nanos = available.awaitNanos(nanos);
+                    else {
+                        Thread thisThread = Thread.currentThread();
+                        leader = thisThread;
+                        try {
+                            long timeLeft = available.awaitNanos(delay);
+                            nanos -= delay - timeLeft;
+                        } finally {
+                            if (leader == thisThread)
+                                leader = null;
+                        }
                     }
                 }
             }
         } finally {
+            if (leader == null && q.peek() != null)
+                available.signal();
             lock.unlock();
         }
     }
@@ -303,8 +334,6 @@
                 c.add(q.poll());
                 ++n;
             }
-            if (n > 0)
-                available.signalAll();
             return n;
         } finally {
             lock.unlock();
@@ -335,8 +364,6 @@
                 c.add(q.poll());
                 ++n;
             }
-            if (n > 0)
-                available.signalAll();
             return n;
         } finally {
             lock.unlock();
@@ -485,6 +512,7 @@
             return cursor < array.length;
         }
 
+        @SuppressWarnings("unchecked")
         public E next() {
             if (cursor >= array.length)
                 throw new NoSuchElementException();
--- a/src/share/classes/java/util/concurrent/ExecutorService.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/concurrent/ExecutorService.java	Fri Mar 28 03:06:00 2008 -0700
@@ -145,6 +145,10 @@
      * tasks are executed, but no new tasks will be accepted.
      * Invocation has no additional effect if already shut down.
      *
+     * <p>This method does not wait for previously submitted tasks to
+     * complete execution.  Use {@link #awaitTermination awaitTermination}
+     * to do that.
+     *
      * @throws SecurityException if a security manager exists and
      *         shutting down this ExecutorService may manipulate
      *         threads that the caller is not permitted to modify
@@ -157,8 +161,12 @@
 
     /**
      * Attempts to stop all actively executing tasks, halts the
-     * processing of waiting tasks, and returns a list of the tasks that were
-     * awaiting execution.
+     * processing of waiting tasks, and returns a list of the tasks
+     * that were awaiting execution.
+     *
+     * <p>This method does not wait for actively executing tasks to
+     * terminate.  Use {@link #awaitTermination awaitTermination} to
+     * do that.
      *
      * <p>There are no guarantees beyond best-effort attempts to stop
      * processing actively executing tasks.  For example, typical
--- a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java	Fri Mar 28 03:06:00 2008 -0700
@@ -35,6 +35,7 @@
 
 package java.util.concurrent;
 import java.util.concurrent.atomic.*;
+import java.util.concurrent.locks.*;
 import java.util.*;
 
 /**
@@ -45,12 +46,21 @@
  * flexibility or capabilities of {@link ThreadPoolExecutor} (which
  * this class extends) are required.
  *
- * <p> Delayed tasks execute no sooner than they are enabled, but
+ * <p>Delayed tasks execute no sooner than they are enabled, but
  * without any real-time guarantees about when, after they are
  * enabled, they will commence. Tasks scheduled for exactly the same
  * execution time are enabled in first-in-first-out (FIFO) order of
  * submission.
  *
+ * <p>When a submitted task is cancelled before it is run, execution
+ * is suppressed. By default, such a cancelled task is not
+ * automatically removed from the work queue until its delay
+ * elapses. While this enables further inspection and monitoring, it
+ * may also cause unbounded retention of cancelled tasks. To avoid
+ * this, set {@link #setRemoveOnCancelPolicy} to {@code true}, which
+ * causes tasks to be immediately removed from the work queue at
+ * time of cancellation.
+ *
  * <p>While this class inherits from {@link ThreadPoolExecutor}, a few
  * of the inherited tuning methods are not useful for it. In
  * particular, because it acts as a fixed-sized pool using
@@ -111,21 +121,11 @@
      *    ScheduledExecutorService methods) which are treated as
      *    delayed tasks with a delay of zero.
      *
-     * 2. Using a custom queue (DelayedWorkQueue) based on an
+     * 2. Using a custom queue (DelayedWorkQueue), a variant of
      *    unbounded DelayQueue. The lack of capacity constraint and
      *    the fact that corePoolSize and maximumPoolSize are
      *    effectively identical simplifies some execution mechanics
-     *    (see delayedExecute) compared to ThreadPoolExecutor
-     *    version.
-     *
-     *    The DelayedWorkQueue class is defined below for the sake of
-     *    ensuring that all elements are instances of
-     *    RunnableScheduledFuture.  Since DelayQueue otherwise
-     *    requires type be Delayed, but not necessarily Runnable, and
-     *    the workQueue requires the opposite, we need to explicitly
-     *    define a class that requires both to ensure that users don't
-     *    add objects that aren't RunnableScheduledFutures via
-     *    getQueue().add() etc.
+     *    (see delayedExecute) compared to ThreadPoolExecutor.
      *
      * 3. Supporting optional run-after-shutdown parameters, which
      *    leads to overrides of shutdown methods to remove and cancel
@@ -150,6 +150,11 @@
     private volatile boolean executeExistingDelayedTasksAfterShutdown = true;
 
     /**
+     * True if ScheduledFutureTask.cancel should remove from queue
+     */
+    private volatile boolean removeOnCancel = false;
+
+    /**
      * Sequence number to break scheduling ties, and in turn to
      * guarantee FIFO order among tied entries.
      */
@@ -167,8 +172,10 @@
 
         /** Sequence number to break ties FIFO */
         private final long sequenceNumber;
+
         /** The time the task is enabled to execute in nanoTime units */
         private long time;
+
         /**
          * Period in nanoseconds for repeating tasks.  A positive
          * value indicates fixed-rate execution.  A negative value
@@ -181,6 +188,11 @@
         RunnableScheduledFuture<V> outerTask = this;
 
         /**
+         * Index into delay queue, to support faster cancellation.
+         */
+        int heapIndex;
+
+        /**
          * Creates a one-shot action with given nanoTime-based trigger time.
          */
         ScheduledFutureTask(Runnable r, V result, long ns) {
@@ -255,6 +267,13 @@
                 time = now() - p;
         }
 
+        public boolean cancel(boolean mayInterruptIfRunning) {
+            boolean cancelled = super.cancel(mayInterruptIfRunning);
+            if (cancelled && removeOnCancel && heapIndex >= 0)
+                remove(this);
+            return cancelled;
+        }
+
         /**
          * Overrides FutureTask version so as to reset/requeue if periodic.
          */
@@ -655,14 +674,47 @@
     }
 
     /**
+     * Sets the policy on whether cancelled tasks should be immediately
+     * removed from the work queue at time of cancellation.  This value is
+     * by default {@code false}.
+     *
+     * @param value if {@code true}, remove on cancellation, else don't
+     * @see #getRemoveOnCancelPolicy
+     * @since 1.7
+     */
+    public void setRemoveOnCancelPolicy(boolean value) {
+        removeOnCancel = value;
+    }
+
+    /**
+     * Gets the policy on whether cancelled tasks should be immediately
+     * removed from the work queue at time of cancellation.  This value is
+     * by default {@code false}.
+     *
+     * @return {@code true} if cancelled tasks are immediately removed
+     *         from the queue
+     * @see #setRemoveOnCancelPolicy
+     * @since 1.7
+     */
+    public boolean getRemoveOnCancelPolicy() {
+        return removeOnCancel;
+    }
+
+    /**
      * Initiates an orderly shutdown in which previously submitted
-     * tasks are executed, but no new tasks will be accepted.  If the
-     * {@code ExecuteExistingDelayedTasksAfterShutdownPolicy} has
-     * been set {@code false}, existing delayed tasks whose delays
-     * have not yet elapsed are cancelled.  And unless the
-     * {@code ContinueExistingPeriodicTasksAfterShutdownPolicy} has
-     * been set {@code true}, future executions of existing periodic
-     * tasks will be cancelled.
+     * tasks are executed, but no new tasks will be accepted.
+     * Invocation has no additional effect if already shut down.
+     *
+     * <p>This method does not wait for previously submitted tasks to
+     * complete execution.  Use {@link #awaitTermination awaitTermination}
+     * to do that.
+     *
+     * <p>If the {@code ExecuteExistingDelayedTasksAfterShutdownPolicy}
+     * has been set {@code false}, existing delayed tasks whose delays
+     * have not yet elapsed are cancelled.  And unless the {@code
+     * ContinueExistingPeriodicTasksAfterShutdownPolicy} has been set
+     * {@code true}, future executions of existing periodic tasks will
+     * be cancelled.
      *
      * @throws SecurityException {@inheritDoc}
      */
@@ -675,6 +727,10 @@
      * processing of waiting tasks, and returns a list of the tasks
      * that were awaiting execution.
      *
+     * <p>This method does not wait for actively executing tasks to
+     * terminate.  Use {@link #awaitTermination awaitTermination} to
+     * do that.
+     *
      * <p>There are no guarantees beyond best-effort attempts to stop
      * processing actively executing tasks.  This implementation
      * cancels tasks via {@link Thread#interrupt}, so any task that
@@ -707,56 +763,478 @@
     }
 
     /**
-     * An annoying wrapper class to convince javac to use a
-     * DelayQueue<RunnableScheduledFuture> as a BlockingQueue<Runnable>
+     * Specialized delay queue. To mesh with TPE declarations, this
+     * class must be declared as a BlockingQueue<Runnable> even though
+     * it can only hold RunnableScheduledFutures.
      */
-    private static class DelayedWorkQueue
-        extends AbstractCollection<Runnable>
+    static class DelayedWorkQueue extends AbstractQueue<Runnable>
         implements BlockingQueue<Runnable> {
 
-        private final DelayQueue<RunnableScheduledFuture> dq = new DelayQueue<RunnableScheduledFuture>();
-        public Runnable poll() { return dq.poll(); }
-        public Runnable peek() { return dq.peek(); }
-        public Runnable take() throws InterruptedException { return dq.take(); }
-        public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
-            return dq.poll(timeout, unit);
+        /*
+         * A DelayedWorkQueue is based on a heap-based data structure
+         * like those in DelayQueue and PriorityQueue, except that
+         * every ScheduledFutureTask also records its index into the
+         * heap array. This eliminates the need to find a task upon
+         * cancellation, greatly speeding up removal (down from O(n)
+         * to O(log n)), and reducing garbage retention that would
+         * otherwise occur by waiting for the element to rise to top
+         * before clearing. But because the queue may also hold
+         * RunnableScheduledFutures that are not ScheduledFutureTasks,
+         * we are not guaranteed to have such indices available, in
+         * which case we fall back to linear search. (We expect that
+         * most tasks will not be decorated, and that the faster cases
+         * will be much more common.)
+         *
+         * All heap operations must record index changes -- mainly
+         * within siftUp and siftDown. Upon removal, a task's
+         * heapIndex is set to -1. Note that ScheduledFutureTasks can
+         * appear at most once in the queue (this need not be true for
+         * other kinds of tasks or work queues), so are uniquely
+         * identified by heapIndex.
+         */
+
+        private static final int INITIAL_CAPACITY = 16;
+        private RunnableScheduledFuture[] queue =
+            new RunnableScheduledFuture[INITIAL_CAPACITY];
+        private final ReentrantLock lock = new ReentrantLock();
+        private int size = 0;
+
+        /**
+         * Thread designated to wait for the task at the head of the
+         * queue.  This variant of the Leader-Follower pattern
+         * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
+         * minimize unnecessary timed waiting.  When a thread becomes
+         * the leader, it waits only for the next delay to elapse, but
+         * other threads await indefinitely.  The leader thread must
+         * signal some other thread before returning from take() or
+         * poll(...), unless some other thread becomes leader in the
+         * interim.  Whenever the head of the queue is replaced with a
+         * task with an earlier expiration time, the leader field is
+         * invalidated by being reset to null, and some waiting
+         * thread, but not necessarily the current leader, is
+         * signalled.  So waiting threads must be prepared to acquire
+         * and lose leadership while waiting.
+         */
+        private Thread leader = null;
+
+        /**
+         * Condition signalled when a newer task becomes available at the
+         * head of the queue or a new thread may need to become leader.
+         */
+        private final Condition available = lock.newCondition();
+
+        /**
+         * Set f's heapIndex if it is a ScheduledFutureTask.
+         */
+        private void setIndex(RunnableScheduledFuture f, int idx) {
+            if (f instanceof ScheduledFutureTask)
+                ((ScheduledFutureTask)f).heapIndex = idx;
         }
 
-        public boolean add(Runnable x) {
-            return dq.add((RunnableScheduledFuture)x);
-        }
-        public boolean offer(Runnable x) {
-            return dq.offer((RunnableScheduledFuture)x);
-        }
-        public void put(Runnable x) {
-            dq.put((RunnableScheduledFuture)x);
-        }
-        public boolean offer(Runnable x, long timeout, TimeUnit unit) {
-            return dq.offer((RunnableScheduledFuture)x, timeout, unit);
+        /**
+         * Sift element added at bottom up to its heap-ordered spot.
+         * Call only when holding lock.
+         */
+        private void siftUp(int k, RunnableScheduledFuture key) {
+            while (k > 0) {
+                int parent = (k - 1) >>> 1;
+                RunnableScheduledFuture e = queue[parent];
+                if (key.compareTo(e) >= 0)
+                    break;
+                queue[k] = e;
+                setIndex(e, k);
+                k = parent;
+            }
+            queue[k] = key;
+            setIndex(key, k);
         }
 
-        public Runnable remove() { return dq.remove(); }
-        public Runnable element() { return dq.element(); }
-        public void clear() { dq.clear(); }
-        public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); }
-        public int drainTo(Collection<? super Runnable> c, int maxElements) {
-            return dq.drainTo(c, maxElements);
+        /**
+         * Sift element added at top down to its heap-ordered spot.
+         * Call only when holding lock.
+         */
+        private void siftDown(int k, RunnableScheduledFuture key) {
+            int half = size >>> 1;
+            while (k < half) {
+                int child = (k << 1) + 1;
+                RunnableScheduledFuture c = queue[child];
+                int right = child + 1;
+                if (right < size && c.compareTo(queue[right]) > 0)
+                    c = queue[child = right];
+                if (key.compareTo(c) <= 0)
+                    break;
+                queue[k] = c;
+                setIndex(c, k);
+                k = child;
+            }
+            queue[k] = key;
+            setIndex(key, k);
         }
 
-        public int remainingCapacity() { return dq.remainingCapacity(); }
-        public boolean remove(Object x) { return dq.remove(x); }
-        public boolean contains(Object x) { return dq.contains(x); }
-        public int size() { return dq.size(); }
-        public boolean isEmpty() { return dq.isEmpty(); }
-        public Object[] toArray() { return dq.toArray(); }
-        public <T> T[] toArray(T[] array) { return dq.toArray(array); }
+        /**
+         * Resize the heap array.  Call only when holding lock.
+         */
+        private void grow() {
+            int oldCapacity = queue.length;
+            int newCapacity = oldCapacity + (oldCapacity >> 1); // grow 50%
+            if (newCapacity < 0) // overflow
+                newCapacity = Integer.MAX_VALUE;
+            queue = Arrays.copyOf(queue, newCapacity);
+        }
+
+        /**
+         * Find index of given object, or -1 if absent
+         */
+        private int indexOf(Object x) {
+            if (x != null) {
+                if (x instanceof ScheduledFutureTask) {
+                    int i = ((ScheduledFutureTask) x).heapIndex;
+                    // Sanity check; x could conceivably be a
+                    // ScheduledFutureTask from some other pool.
+                    if (i >= 0 && i < size && queue[i] == x)
+                        return i;
+                } else {
+                    for (int i = 0; i < size; i++)
+                        if (x.equals(queue[i]))
+                            return i;
+                }
+            }
+            return -1;
+        }
+
+        public boolean contains(Object x) {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                return indexOf(x) != -1;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public boolean remove(Object x) {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                int i = indexOf(x);
+                if (i < 0)
+                    return false;
+
+                setIndex(queue[i], -1);
+                int s = --size;
+                RunnableScheduledFuture replacement = queue[s];
+                queue[s] = null;
+                if (s != i) {
+                    siftDown(i, replacement);
+                    if (queue[i] == replacement)
+                        siftUp(i, replacement);
+                }
+                return true;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public int size() {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                return size;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public boolean isEmpty() {
+            return size() == 0;
+        }
+
+        public int remainingCapacity() {
+            return Integer.MAX_VALUE;
+        }
+
+        public RunnableScheduledFuture peek() {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                return queue[0];
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public boolean offer(Runnable x) {
+            if (x == null)
+                throw new NullPointerException();
+            RunnableScheduledFuture e = (RunnableScheduledFuture)x;
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                int i = size;
+                if (i >= queue.length)
+                    grow();
+                size = i + 1;
+                if (i == 0) {
+                    queue[0] = e;
+                    setIndex(e, 0);
+                } else {
+                    siftUp(i, e);
+                }
+                if (queue[0] == e) {
+                    leader = null;
+                    available.signal();
+                }
+            } finally {
+                lock.unlock();
+            }
+            return true;
+        }
+
+        public void put(Runnable e) {
+            offer(e);
+        }
+
+        public boolean add(Runnable e) {
+            return offer(e);
+        }
+
+        public boolean offer(Runnable e, long timeout, TimeUnit unit) {
+            return offer(e);
+        }
+
+        /**
+         * Performs common bookkeeping for poll and take: Replaces
+         * first element with last and sifts it down.  Call only when
+         * holding lock.
+         * @param f the task to remove and return
+         */
+        private RunnableScheduledFuture finishPoll(RunnableScheduledFuture f) {
+            int s = --size;
+            RunnableScheduledFuture x = queue[s];
+            queue[s] = null;
+            if (s != 0)
+                siftDown(0, x);
+            setIndex(f, -1);
+            return f;
+        }
+
+        public RunnableScheduledFuture poll() {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                RunnableScheduledFuture first = queue[0];
+                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
+                    return null;
+                else
+                    return finishPoll(first);
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public RunnableScheduledFuture take() throws InterruptedException {
+            final ReentrantLock lock = this.lock;
+            lock.lockInterruptibly();
+            try {
+                for (;;) {
+                    RunnableScheduledFuture first = queue[0];
+                    if (first == null)
+                        available.await();
+                    else {
+                        long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                        if (delay <= 0)
+                            return finishPoll(first);
+                        else if (leader != null)
+                            available.await();
+                        else {
+                            Thread thisThread = Thread.currentThread();
+                            leader = thisThread;
+                            try {
+                                available.awaitNanos(delay);
+                            } finally {
+                                if (leader == thisThread)
+                                    leader = null;
+                            }
+                        }
+                    }
+                }
+            } finally {
+                if (leader == null && queue[0] != null)
+                    available.signal();
+                lock.unlock();
+            }
+        }
+
+        public RunnableScheduledFuture poll(long timeout, TimeUnit unit)
+            throws InterruptedException {
+            long nanos = unit.toNanos(timeout);
+            final ReentrantLock lock = this.lock;
+            lock.lockInterruptibly();
+            try {
+                for (;;) {
+                    RunnableScheduledFuture first = queue[0];
+                    if (first == null) {
+                        if (nanos <= 0)
+                            return null;
+                        else
+                            nanos = available.awaitNanos(nanos);
+                    } else {
+                        long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                        if (delay <= 0)
+                            return finishPoll(first);
+                        if (nanos <= 0)
+                            return null;
+                        if (nanos < delay || leader != null)
+                            nanos = available.awaitNanos(nanos);
+                        else {
+                            Thread thisThread = Thread.currentThread();
+                            leader = thisThread;
+                            try {
+                                long timeLeft = available.awaitNanos(delay);
+                                nanos -= delay - timeLeft;
+                            } finally {
+                                if (leader == thisThread)
+                                    leader = null;
+                            }
+                        }
+                    }
+                }
+            } finally {
+                if (leader == null && queue[0] != null)
+                    available.signal();
+                lock.unlock();
+            }
+        }
+
+        public void clear() {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                for (int i = 0; i < size; i++) {
+                    RunnableScheduledFuture t = queue[i];
+                    if (t != null) {
+                        queue[i] = null;
+                        setIndex(t, -1);
+                    }
+                }
+                size = 0;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        /**
+         * Return and remove first element only if it is expired.
+         * Used only by drainTo.  Call only when holding lock.
+         */
+        private RunnableScheduledFuture pollExpired() {
+            RunnableScheduledFuture first = queue[0];
+            if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
+                return null;
+            return finishPoll(first);
+        }
+
+        public int drainTo(Collection<? super Runnable> c) {
+            if (c == null)
+                throw new NullPointerException();
+            if (c == this)
+                throw new IllegalArgumentException();
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                RunnableScheduledFuture first;
+                int n = 0;
+                while ((first = pollExpired()) != null) {
+                    c.add(first);
+                    ++n;
+                }
+                return n;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public int drainTo(Collection<? super Runnable> c, int maxElements) {
+            if (c == null)
+                throw new NullPointerException();
+            if (c == this)
+                throw new IllegalArgumentException();
+            if (maxElements <= 0)
+                return 0;
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                RunnableScheduledFuture first;
+                int n = 0;
+                while (n < maxElements && (first = pollExpired()) != null) {
+                    c.add(first);
+                    ++n;
+                }
+                return n;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public Object[] toArray() {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                return Arrays.copyOf(queue, size, Object[].class);
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        @SuppressWarnings("unchecked")
+        public <T> T[] toArray(T[] a) {
+            final ReentrantLock lock = this.lock;
+            lock.lock();
+            try {
+                if (a.length < size)
+                    return (T[]) Arrays.copyOf(queue, size, a.getClass());
+                System.arraycopy(queue, 0, a, 0, size);
+                if (a.length > size)
+                    a[size] = null;
+                return a;
+            } finally {
+                lock.unlock();
+            }
+        }
+
         public Iterator<Runnable> iterator() {
-            return new Iterator<Runnable>() {
-                private Iterator<RunnableScheduledFuture> it = dq.iterator();
-                public boolean hasNext() { return it.hasNext(); }
-                public Runnable next() { return it.next(); }
-                public void remove() { it.remove(); }
-            };
+            return new Itr(Arrays.copyOf(queue, size));
+        }
+
+        /**
+         * Snapshot iterator that works off copy of underlying q array.
+         */
+        private class Itr implements Iterator<Runnable> {
+            final RunnableScheduledFuture[] array;
+            int cursor = 0;     // index of next element to return
+            int lastRet = -1;   // index of last element, or -1 if no such
+
+            Itr(RunnableScheduledFuture[] array) {
+                this.array = array;
+            }
+
+            public boolean hasNext() {
+                return cursor < array.length;
+            }
+
+            public Runnable next() {
+                if (cursor >= array.length)
+                    throw new NoSuchElementException();
+                lastRet = cursor;
+                return array[cursor++];
+            }
+
+            public void remove() {
+                if (lastRet < 0)
+                    throw new IllegalStateException();
+                DelayedWorkQueue.this.remove(array[lastRet]);
+                lastRet = -1;
+            }
         }
     }
 }
--- a/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Fri Mar 28 03:06:00 2008 -0700
@@ -1342,6 +1342,10 @@
      * tasks are executed, but no new tasks will be accepted.
      * Invocation has no additional effect if already shut down.
      *
+     * <p>This method does not wait for previously submitted tasks to
+     * complete execution.  Use {@link #awaitTermination awaitTermination}
+     * to do that.
+     *
      * @throws SecurityException {@inheritDoc}
      */
     public void shutdown() {
@@ -1364,6 +1368,10 @@
      * that were awaiting execution. These tasks are drained (removed)
      * from the task queue upon return from this method.
      *
+     * <p>This method does not wait for actively executing tasks to
+     * terminate.  Use {@link #awaitTermination awaitTermination} to
+     * do that.
+     *
      * <p>There are no guarantees beyond best-effort attempts to stop
      * processing actively executing tasks.  This implementation
      * cancels tasks via {@link Thread#interrupt}, so any task that
--- a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java	Fri Mar 28 03:06:00 2008 -0700
@@ -222,7 +222,7 @@
     /** Inner class providing writelock */
     private final ReentrantReadWriteLock.WriteLock writerLock;
     /** Performs all synchronization mechanics */
-    private final Sync sync;
+    final Sync sync;
 
     /**
      * Creates a new {@code ReentrantReadWriteLock} with
@@ -239,7 +239,7 @@
      * @param fair {@code true} if this lock should use a fair ordering policy
      */
     public ReentrantReadWriteLock(boolean fair) {
-        sync = (fair)? new FairSync() : new NonfairSync();
+        sync = fair ? new FairSync() : new NonfairSync();
         readerLock = new ReadLock(this);
         writerLock = new WriteLock(this);
     }
@@ -256,8 +256,8 @@
 
         /*
          * Read vs write count extraction constants and functions.
-         * Lock state is logically divided into two shorts: The lower
-         * one representing the exclusive (writer) lock hold count,
+         * Lock state is logically divided into two unsigned shorts:
+         * The lower one representing the exclusive (writer) lock hold count,
          * and the upper the shared (reader) hold count.
          */
 
@@ -279,13 +279,6 @@
             int count;
             // Use id, not reference, to avoid garbage retention
             final long tid = Thread.currentThread().getId();
-            /** Decrement if positive; return previous value */
-            int tryDecrement() {
-                int c = count;
-                if (c > 0)
-                    count = c - 1;
-                return c;
-            }
         }
 
         /**
@@ -303,7 +296,7 @@
          * The number of read locks held by current thread.
          * Initialized only in constructor and readObject.
          */
-        transient ThreadLocalHoldCounter readHolds;
+        private transient ThreadLocalHoldCounter readHolds;
 
         /**
          * The hold count of the last thread to successfully acquire
@@ -312,7 +305,17 @@
          * acquire. This is non-volatile since it is just used
          * as a heuristic, and would be great for threads to cache.
          */
-        transient HoldCounter cachedHoldCounter;
+        private transient HoldCounter cachedHoldCounter;
+
+        /**
+         * firstReader is the first thread to have acquired the read lock.
+         * firstReaderHoldCount is firstReader's hold count.
+         * This allows tracking of read holds for uncontended read
+         * locks to be very cheap.
+         */
+        private final static long INVALID_THREAD_ID = -1;
+        private transient long firstReader = INVALID_THREAD_ID;
+        private transient int firstReaderHoldCount;
 
         Sync() {
             readHolds = new ThreadLocalHoldCounter();
@@ -390,12 +393,25 @@
         }
 
         protected final boolean tryReleaseShared(int unused) {
-            HoldCounter rh = cachedHoldCounter;
-            Thread current = Thread.currentThread();
-            if (rh == null || rh.tid != current.getId())
-                rh = readHolds.get();
-            if (rh.tryDecrement() <= 0)
-                throw new IllegalMonitorStateException();
+            long tid = Thread.currentThread().getId();
+            if (firstReader == tid) {
+                // assert firstReaderHoldCount > 0;
+                if (firstReaderHoldCount == 1)
+                    firstReader = INVALID_THREAD_ID;
+                else
+                    firstReaderHoldCount--;
+            } else {
+                HoldCounter rh = cachedHoldCounter;
+                if (rh == null || rh.tid != tid)
+                    rh = readHolds.get();
+                int count = rh.count;
+                if (count <= 1) {
+                    readHolds.remove();
+                    if (count <= 0)
+                        throw unmatchedUnlockException();
+                }
+                --rh.count;
+            }
             for (;;) {
                 int c = getState();
                 int nextc = c - SHARED_UNIT;
@@ -404,12 +420,16 @@
             }
         }
 
+        private IllegalMonitorStateException unmatchedUnlockException() {
+            return new IllegalMonitorStateException(
+                "attempt to unlock read lock, not locked by current thread");
+        }
+
         protected final int tryAcquireShared(int unused) {
             /*
              * Walkthrough:
              * 1. If write lock held by another thread, fail.
-             * 2. If count saturated, throw error.
-             * 3. Otherwise, this thread is eligible for
+             * 2. Otherwise, this thread is eligible for
              *    lock wrt state, so ask if it should block
              *    because of queue policy. If not, try
              *    to grant by CASing state and updating count.
@@ -417,23 +437,33 @@
              *    acquires, which is postponed to full version
              *    to avoid having to check hold count in
              *    the more typical non-reentrant case.
-             * 4. If step 3 fails either because thread
-             *    apparently not eligible or CAS fails,
-             *    chain to version with full retry loop.
+             * 3. If step 2 fails either because thread
+             *    apparently not eligible or CAS fails or count
+             *    saturated, chain to version with full retry loop.
              */
             Thread current = Thread.currentThread();
             int c = getState();
             if (exclusiveCount(c) != 0 &&
                 getExclusiveOwnerThread() != current)
                 return -1;
-            if (sharedCount(c) == MAX_COUNT)
-                throw new Error("Maximum lock count exceeded");
+            int r = sharedCount(c);
             if (!readerShouldBlock() &&
+                r < MAX_COUNT &&
                 compareAndSetState(c, c + SHARED_UNIT)) {
-                HoldCounter rh = cachedHoldCounter;
-                if (rh == null || rh.tid != current.getId())
-                    cachedHoldCounter = rh = readHolds.get();
-                rh.count++;
+                long tid = current.getId();
+                if (r == 0) {
+                    firstReader = tid;
+                    firstReaderHoldCount = 1;
+                } else if (firstReader == tid) {
+                    firstReaderHoldCount++;
+                } else {
+                    HoldCounter rh = cachedHoldCounter;
+                    if (rh == null || rh.tid != tid)
+                        cachedHoldCounter = rh = readHolds.get();
+                    else if (rh.count == 0)
+                        readHolds.set(rh);
+                    rh.count++;
+                }
                 return 1;
             }
             return fullTryAcquireShared(current);
@@ -450,20 +480,56 @@
              * complicating tryAcquireShared with interactions between
              * retries and lazily reading hold counts.
              */
-            HoldCounter rh = cachedHoldCounter;
-            if (rh == null || rh.tid != current.getId())
-                rh = readHolds.get();
+            HoldCounter rh = null;
             for (;;) {
                 int c = getState();
-                int w = exclusiveCount(c);
-                if ((w != 0 && getExclusiveOwnerThread() != current) ||
-                    ((rh.count | w) == 0 && readerShouldBlock()))
-                    return -1;
+                if (exclusiveCount(c) != 0) {
+                    if (getExclusiveOwnerThread() != current)
+                        //if (removeNeeded) readHolds.remove();
+                        return -1;
+                    // else we hold the exclusive lock; blocking here
+                    // would cause deadlock.
+                } else if (readerShouldBlock()) {
+                    // Make sure we're not acquiring read lock reentrantly
+                    long tid = current.getId();
+                    if (firstReader == tid) {
+                        // assert firstReaderHoldCount > 0;
+                    } else {
+                        if (rh == null) {
+                            rh = cachedHoldCounter;
+                            if (rh == null || rh.tid != tid) {
+                                rh = readHolds.get();
+                                if (rh.count == 0)
+                                    readHolds.remove();
+                            }
+                        }
+                        if (rh.count == 0)
+                            return -1;
+                    }
+                }
                 if (sharedCount(c) == MAX_COUNT)
                     throw new Error("Maximum lock count exceeded");
                 if (compareAndSetState(c, c + SHARED_UNIT)) {
-                    cachedHoldCounter = rh; // cache for release
-                    rh.count++;
+                    long tid = current.getId();
+                    if (sharedCount(c) == 0) {
+                        firstReader = tid;
+                        firstReaderHoldCount = 1;
+                    } else if (firstReader == tid) {
+                        firstReaderHoldCount++;
+                    } else {
+                        if (rh == null) {
+                            rh = cachedHoldCounter;
+                            if (rh != null && rh.tid == tid) {
+                                if (rh.count == 0)
+                                    readHolds.set(rh);
+                            } else {
+                                rh = readHolds.get();
+                            }
+                        } else if (rh.count == 0)
+                            readHolds.set(rh);
+                        cachedHoldCounter = rh; // cache for release
+                        rh.count++;
+                    }
                     return 1;
                 }
             }
@@ -472,14 +538,14 @@
         /**
          * Performs tryLock for write, enabling barging in both modes.
          * This is identical in effect to tryAcquire except for lack
-         * of calls to writerShouldBlock
+         * of calls to writerShouldBlock.
          */
         final boolean tryWriteLock() {
             Thread current = Thread.currentThread();
             int c = getState();
             if (c != 0) {
                 int w = exclusiveCount(c);
-                if (w == 0 ||current != getExclusiveOwnerThread())
+                if (w == 0 || current != getExclusiveOwnerThread())
                     return false;
                 if (w == MAX_COUNT)
                     throw new Error("Maximum lock count exceeded");
@@ -493,7 +559,7 @@
         /**
          * Performs tryLock for read, enabling barging in both modes.
          * This is identical in effect to tryAcquireShared except for
-         * lack of calls to readerShouldBlock
+         * lack of calls to readerShouldBlock.
          */
         final boolean tryReadLock() {
             Thread current = Thread.currentThread();
@@ -502,13 +568,24 @@
                 if (exclusiveCount(c) != 0 &&
                     getExclusiveOwnerThread() != current)
                     return false;
-                if (sharedCount(c) == MAX_COUNT)
+                int r = sharedCount(c);
+                if (r == MAX_COUNT)
                     throw new Error("Maximum lock count exceeded");
                 if (compareAndSetState(c, c + SHARED_UNIT)) {
-                    HoldCounter rh = cachedHoldCounter;
-                    if (rh == null || rh.tid != current.getId())
-                        cachedHoldCounter = rh = readHolds.get();
-                    rh.count++;
+                    long tid = current.getId();
+                    if (r == 0) {
+                        firstReader = tid;
+                        firstReaderHoldCount = 1;
+                    } else if (firstReader == tid) {
+                        firstReaderHoldCount++;
+                    } else {
+                        HoldCounter rh = cachedHoldCounter;
+                        if (rh == null || rh.tid != tid)
+                            cachedHoldCounter = rh = readHolds.get();
+                        else if (rh.count == 0)
+                            readHolds.set(rh);
+                        rh.count++;
+                    }
                     return true;
                 }
             }
@@ -546,7 +623,20 @@
         }
 
         final int getReadHoldCount() {
-            return getReadLockCount() == 0? 0 : readHolds.get().count;
+            if (getReadLockCount() == 0)
+                return 0;
+
+            long tid = Thread.currentThread().getId();
+            if (firstReader == tid)
+                return firstReaderHoldCount;
+
+            HoldCounter rh = cachedHoldCounter;
+            if (rh != null && rh.tid == tid)
+                return rh.count;
+
+            int count = readHolds.get().count;
+            if (count == 0) readHolds.remove();
+            return count;
         }
 
         /**
@@ -557,6 +647,7 @@
             throws java.io.IOException, ClassNotFoundException {
             s.defaultReadObject();
             readHolds = new ThreadLocalHoldCounter();
+            firstReader = INVALID_THREAD_ID;
             setState(0); // reset to unlocked state
         }
 
--- a/src/share/classes/java/util/prefs/AbstractPreferences.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/prefs/AbstractPreferences.java	Fri Mar 28 03:06:00 2008 -0700
@@ -155,7 +155,8 @@
      * All known unremoved children of this node.  (This "cache" is consulted
      * prior to calling childSpi() or getChild().
      */
-    private Map kidCache  = new HashMap();
+    private Map<String, AbstractPreferences> kidCache
+        = new HashMap<String, AbstractPreferences>();
 
     /**
      * This field is used to keep track of whether or not this node has
@@ -712,11 +713,10 @@
             if (removed)
                 throw new IllegalStateException("Node has been removed.");
 
-            Set s = new TreeSet(kidCache.keySet());
-            String[] kids = childrenNamesSpi();
-            for(int i=0; i<kids.length; i++)
-                s.add(kids[i]);
-            return (String[]) s.toArray(EMPTY_STRING_ARRAY);
+            Set<String> s = new TreeSet<String>(kidCache.keySet());
+            for (String kid : childrenNamesSpi())
+                s.add(kid);
+            return s.toArray(EMPTY_STRING_ARRAY);
         }
     }
 
@@ -728,8 +728,7 @@
      * @return all known unremoved children of this node.
      */
     protected final AbstractPreferences[] cachedChildren() {
-        return (AbstractPreferences[]) kidCache.values().
-            toArray(EMPTY_ABSTRACT_PREFS_ARRAY);
+        return kidCache.values().toArray(EMPTY_ABSTRACT_PREFS_ARRAY);
     }
 
     private static final AbstractPreferences[] EMPTY_ABSTRACT_PREFS_ARRAY
@@ -825,7 +824,7 @@
         if (token.equals("/"))  // Check for consecutive slashes
             throw new IllegalArgumentException("Consecutive slashes in path");
         synchronized(lock) {
-            AbstractPreferences child=(AbstractPreferences)kidCache.get(token);
+            AbstractPreferences child = kidCache.get(token);
             if (child == null) {
                 if (token.length() > MAX_NAME_LENGTH)
                     throw new IllegalArgumentException(
@@ -893,7 +892,7 @@
         if (token.equals("/"))  // Check for consecutive slashes
             throw new IllegalArgumentException("Consecutive slashes in path");
         synchronized(lock) {
-            AbstractPreferences child=(AbstractPreferences)kidCache.get(token);
+            AbstractPreferences child = kidCache.get(token);
             if (child == null)
                 child = getChild(token);
             if (child==null)
@@ -964,9 +963,10 @@
                     kidCache.put(kidNames[i], childSpi(kidNames[i]));
 
             // Recursively remove all cached children
-            for (Iterator i = kidCache.values().iterator(); i.hasNext();) {
+            for (Iterator<AbstractPreferences> i = kidCache.values().iterator();
+                 i.hasNext();) {
                 try {
-                    ((AbstractPreferences)i.next()).removeNode2();
+                    i.next().removeNode2();
                     i.remove();
                 } catch (BackingStoreException x) { }
             }
@@ -1020,13 +1020,12 @@
      *         preference tree.
      */
     public boolean isUserNode() {
-        Boolean result = (Boolean)
-          AccessController.doPrivileged( new PrivilegedAction() {
-            public Object run() {
-                return Boolean.valueOf(root == Preferences.userRoot());
+        return AccessController.doPrivileged(
+            new PrivilegedAction<Boolean>() {
+                public Boolean run() {
+                    return root == Preferences.userRoot();
             }
-        });
-        return result.booleanValue();
+            }).booleanValue();
     }
 
     public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
@@ -1443,7 +1442,8 @@
      * event delivery from preference activity, greatly simplifying
      * locking and reducing opportunity for deadlock.
      */
-    private static final List eventQueue = new LinkedList();
+    private static final List<EventObject> eventQueue
+        = new LinkedList<EventObject>();
 
     /**
      * These two classes are used to distinguish NodeChangeEvents on
@@ -1476,7 +1476,7 @@
                     try {
                         while (eventQueue.isEmpty())
                             eventQueue.wait();
-                        event = (EventObject) eventQueue.remove(0);
+                        event = eventQueue.remove(0);
                     } catch (InterruptedException e) {
                         // XXX Log "Event dispatch thread interrupted. Exiting"
                         return;
--- a/src/share/classes/java/util/prefs/Preferences.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/prefs/Preferences.java	Fri Mar 28 03:06:00 2008 -0700
@@ -32,9 +32,8 @@
 import java.security.Permission;
 import java.security.PrivilegedAction;
 import java.util.Iterator;
-import sun.misc.Service;
-import sun.misc.ServiceConfigurationError;
-
+import java.util.ServiceLoader;
+import java.util.ServiceConfigurationError;
 
 // These imports needed only as a workaround for a JavaDoc bug
 import java.lang.RuntimePermission;
@@ -274,12 +273,14 @@
 
     private static PreferencesFactory factory1() {
         // 2. Try service provider interface
-        Iterator i = Service.providers(PreferencesFactory.class,
-                                       ClassLoader.getSystemClassLoader());
+        Iterator<PreferencesFactory> itr = ServiceLoader
+            .load(PreferencesFactory.class, ClassLoader.getSystemClassLoader())
+            .iterator();
+
         // choose first provider instance
-        while (i.hasNext()) {
+        while (itr.hasNext()) {
             try {
-                return (PreferencesFactory) i.next();
+                return itr.next();
             } catch (ServiceConfigurationError sce) {
                 if (sce.getCause() instanceof SecurityException) {
                     // Ignore the security exception, try the next provider
--- a/src/share/classes/java/util/regex/Matcher.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/java/util/regex/Matcher.java	Fri Mar 28 03:06:00 2008 -0700
@@ -249,7 +249,7 @@
         Matcher result = new Matcher(this.parentPattern, text.toString());
         result.first = this.first;
         result.last = this.last;
-        result.groups = (int[])(this.groups.clone());
+        result.groups = this.groups.clone();
         return result;
     }
 
--- a/src/share/classes/javax/management/AndQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/AndQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -104,4 +104,25 @@
      return "(" + exp1 + ") and (" + exp2 + ")";
    }
 
- }
+   @Override
+   String toQueryString() {
+        // Parentheses are only added if needed to disambiguate.
+        return parens(exp1) + " and " + parens(exp2);
+   }
+
+   // Add parens if needed to disambiguate an expression such as
+   // Query.and(Query.or(a, b), c).  We need to return
+   // (a or b) and c
+   // in such a case, because
+   // a or b and c
+   // would mean
+   // a or (b and c)
+   private static String parens(QueryExp exp) {
+       String s = Query.toString(exp);
+       if (exp instanceof OrQueryExp)
+           return "(" + s + ")";
+       else
+           return s;
+   }
+
+}
--- a/src/share/classes/javax/management/AttributeValueExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/AttributeValueExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -26,12 +26,17 @@
 package javax.management;
 
 
-// RI import
-import javax.management.MBeanServer;
+import com.sun.jmx.mbeanserver.Introspector;
+import java.io.IOException;
+import java.io.ObjectInputStream;
 
 /**
- * Represents attributes used as arguments to relational constraints.
- * An <CODE>AttributeValueExp</CODE> may be used anywhere a <CODE>ValueExp</CODE> is required.
+ * <p>Represents attributes used as arguments to relational constraints.
+ * Instances of this class are usually obtained using {@link Query#attr(String)
+ * Query.attr}.</p>
+ *
+ * <p>An <CODE>AttributeValueExp</CODE> may be used anywhere a
+ * <CODE>ValueExp</CODE> is required.
  *
  * @since 1.5
  */
@@ -46,6 +51,8 @@
      */
     private String attr;
 
+    private transient int dotIndex;
+
     /**
      * An <code>AttributeValueExp</code> with a null attribute.
      * @deprecated An instance created with this constructor cannot be
@@ -64,6 +71,18 @@
      */
     public AttributeValueExp(String attr) {
         this.attr = attr;
+        setDotIndex();
+    }
+
+    private void setDotIndex() {
+        if (attr != null)
+            dotIndex = attr.indexOf('.');
+    }
+
+    private void readObject(ObjectInputStream in)
+    throws ClassNotFoundException, IOException {
+        in.defaultReadObject();
+        setDotIndex();
     }
 
     /**
@@ -76,7 +95,13 @@
     }
 
     /**
-     * Applies the <CODE>AttributeValueExp</CODE> on an MBean.
+     * <p>Applies the <CODE>AttributeValueExp</CODE> on an MBean.
+     * This method calls {@link #getAttribute getAttribute(name)} and wraps
+     * the result as a {@code ValueExp}.  The value returned by
+     * {@code getAttribute} must be a {@code Number}, {@code String},
+     * or {@code Boolean}; otherwise this method throws a
+     * {@code BadAttributeValueExpException}, which will cause
+     * the containing query to be false for this {@code name}.</p>
      *
      * @param name The name of the MBean on which the <CODE>AttributeValueExp</CODE> will be applied.
      *
@@ -88,6 +113,7 @@
      * @exception BadBinaryOpValueExpException
      *
      */
+    @Override
     public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException,
         BadAttributeValueExpException, InvalidApplicationException {
         Object result = getAttribute(name);
@@ -106,8 +132,9 @@
     /**
      * Returns the string representing its value.
      */
+    @Override
     public String toString()  {
-        return attr;
+        return QueryParser.quoteId(attr);
     }
 
 
@@ -115,18 +142,38 @@
      * Sets the MBean server on which the query is to be performed.
      *
      * @param s The MBean server on which the query is to be performed.
+     *
+     * @deprecated This method has no effect.  The MBean Server used to
+     * obtain an attribute value is {@link QueryEval#getMBeanServer()}.
      */
     /* There is no need for this method, because if a query is being
        evaluted an AttributeValueExp can only appear inside a QueryExp,
        and that QueryExp will itself have done setMBeanServer.  */
+    @Deprecated
+    @Override
     public void setMBeanServer(MBeanServer s)  {
     }
 
 
     /**
-     * Return the value of the given attribute in the named MBean.
+     * <p>Return the value of the given attribute in the named MBean.
      * If the attempt to access the attribute generates an exception,
-     * return null.
+     * return null.</p>
+     *
+     * <p>Let <em>n</em> be the {@linkplain #getAttributeName attribute
+     * name}. Then this method proceeds as follows. First it calls
+     * {@link MBeanServer#getAttribute getAttribute(name, <em>n</em>)}. If that
+     * generates an {@link AttributeNotFoundException}, and if <em>n</em>
+     * contains at least one dot ({@code .}), then the method calls {@code
+     * getAttribute(name, }<em>n</em>{@code .substring(0, }<em>n</em>{@code
+     * .indexOf('.')))}; in other words it calls {@code getAttribute}
+     * with the substring of <em>n</em> before the first dot. Then it
+     * extracts a component from the retrieved value, as described in the <a
+     * href="monitor/package-summary.html#complex">documentation for the {@code
+     * monitor} package</a>.</p>
+     *
+     * <p>The MBean Server used is the one returned by {@link
+     * QueryEval#getMBeanServer()}.</p>
      *
      * @param name the name of the MBean whose attribute is to be returned.
      *
@@ -139,10 +186,34 @@
 
             MBeanServer server = QueryEval.getMBeanServer();
 
+            try {
             return server.getAttribute(name, attr);
+            } catch (AttributeNotFoundException e) {
+                if (dotIndex < 0)
+                    throw e;
+            }
+
+            String toGet = attr.substring(0, dotIndex);
+
+            Object value = server.getAttribute(name, toGet);
+
+            return extractElement(value, attr.substring(dotIndex + 1));
         } catch (Exception re) {
             return null;
         }
     }
 
+    private Object extractElement(Object value, String elementWithDots)
+    throws AttributeNotFoundException {
+        while (true) {
+            int dot = elementWithDots.indexOf('.');
+            String element = (dot < 0) ?
+                elementWithDots : elementWithDots.substring(0, dot);
+            value = Introspector.elementFromComplex(value, element);
+            if (dot < 0)
+                return value;
+            elementWithDots = elementWithDots.substring(dot + 1);
+        }
+    }
+
 }
--- a/src/share/classes/javax/management/BetweenQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/BetweenQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -109,34 +109,25 @@
         ValueExp val1 = exp1.apply(name);
         ValueExp val2 = exp2.apply(name);
         ValueExp val3 = exp3.apply(name);
-        String sval1;
-        String sval2;
-        String sval3;
-        double dval1;
-        double dval2;
-        double dval3;
-        long lval1;
-        long lval2;
-        long lval3;
         boolean numeric = val1 instanceof NumericValueExp;
 
         if (numeric) {
             if (((NumericValueExp)val1).isLong()) {
-                lval1 = ((NumericValueExp)val1).longValue();
-                lval2 = ((NumericValueExp)val2).longValue();
-                lval3 = ((NumericValueExp)val3).longValue();
+                long lval1 = ((NumericValueExp)val1).longValue();
+                long lval2 = ((NumericValueExp)val2).longValue();
+                long lval3 = ((NumericValueExp)val3).longValue();
                 return lval2 <= lval1 && lval1 <= lval3;
             } else {
-                dval1 = ((NumericValueExp)val1).doubleValue();
-                dval2 = ((NumericValueExp)val2).doubleValue();
-                dval3 = ((NumericValueExp)val3).doubleValue();
+                double dval1 = ((NumericValueExp)val1).doubleValue();
+                double dval2 = ((NumericValueExp)val2).doubleValue();
+                double dval3 = ((NumericValueExp)val3).doubleValue();
                 return dval2 <= dval1 && dval1 <= dval3;
             }
 
         } else {
-            sval1 = ((StringValueExp)val1).toString();
-            sval2 = ((StringValueExp)val2).toString();
-            sval3 = ((StringValueExp)val3).toString();
+            String sval1 = ((StringValueExp)val1).getValue();
+            String sval2 = ((StringValueExp)val2).getValue();
+            String sval3 = ((StringValueExp)val3).getValue();
             return sval2.compareTo(sval1) <= 0 && sval1.compareTo(sval3) <= 0;
         }
     }
@@ -148,4 +139,8 @@
         return "(" + exp1 + ") between (" + exp2 + ") and (" + exp3 + ")";
     }
 
- }
+    @Override
+    String toQueryString() {
+        return exp1 + " between " + exp2 + " and " + exp3;
+    }
+}
--- a/src/share/classes/javax/management/BinaryOpValueExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/BinaryOpValueExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -167,12 +167,74 @@
      */
     public String toString()  {
         try {
-            return exp1 + " " + opString() + " " + exp2;
+            return parens(exp1, true) + " " + opString() + " " + parens(exp2, false);
         } catch (BadBinaryOpValueExpException ex) {
             return "invalid expression";
         }
     }
 
+    /*
+     * Add parentheses to the given subexpression if necessary to
+     * preserve meaning.  Suppose this BinaryOpValueExp is
+     * Query.times(Query.plus(Query.attr("A"), Query.attr("B")), Query.attr("C")).
+     * Then the original toString() logic would return A + B * C.
+     * We check precedences in order to return (A + B) * C, which is the
+     * meaning of the ValueExp.
+     *
+     * We need to add parentheses if the unparenthesized expression would
+     * be parsed as a different ValueExp from the original.
+     * We cannot omit parentheses even when mathematically
+     * the result would be equivalent, because we do not know whether the
+     * numeric values will be integer or floating-point.  Addition and
+     * multiplication are associative for integers but not always for
+     * floating-point.
+     *
+     * So the rule is that we omit parentheses if the ValueExp
+     * is (A op1 B) op2 C and the precedence of op1 is greater than or
+     * equal to that of op2; or if the ValueExp is A op1 (B op2 C) and
+     * the precedence of op2 is greater than that of op1.  (There are two
+     * precedences: that of * and / is greater than that of + and -.)
+     * The case of (A op1 B) op2 (C op3 D) applies each rule in turn.
+     *
+     * The following examples show the rules in action.  On the left,
+     * the original ValueExp.  On the right, the string representation.
+     *
+     * (A + B) + C     A + B + C
+     * (A * B) + C     A * B + C
+     * (A + B) * C     (A + B) * C
+     * (A * B) * C     A * B * C
+     * A + (B + C)     A + (B + C)
+     * A + (B * C)     A + B * C
+     * A * (B + C)     A * (B + C)
+     * A * (B * C)     A * (B * C)
+     */
+    private String parens(ValueExp subexp, boolean left)
+    throws BadBinaryOpValueExpException {
+        boolean omit;
+        if (subexp instanceof BinaryOpValueExp) {
+            int subop = ((BinaryOpValueExp) subexp).op;
+            if (left)
+                omit = (precedence(subop) >= precedence(op));
+            else
+                omit = (precedence(subop) > precedence(op));
+        } else
+            omit = true;
+
+        if (omit)
+            return subexp.toString();
+        else
+            return "(" + subexp + ")";
+    }
+
+    private int precedence(int xop) throws BadBinaryOpValueExpException {
+        switch (xop) {
+            case Query.PLUS: case Query.MINUS: return 0;
+            case Query.TIMES: case Query.DIV: return 1;
+            default:
+                throw new BadBinaryOpValueExpException(this);
+        }
+    }
+
     private String opString() throws BadBinaryOpValueExpException {
         switch (op) {
         case Query.PLUS:
@@ -188,4 +250,10 @@
         throw new BadBinaryOpValueExpException(this);
     }
 
+    @Deprecated
+    public void setMBeanServer(MBeanServer s) {
+        super.setMBeanServer(s);
  }
+
+
+ }
--- a/src/share/classes/javax/management/BinaryRelQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/BinaryRelQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -108,20 +108,12 @@
         BadAttributeValueExpException, InvalidApplicationException  {
         Object val1 = exp1.apply(name);
         Object val2 = exp2.apply(name);
-        String sval1;
-        String sval2;
-        double dval1;
-        double dval2;
-        long   lval1;
-        long   lval2;
-        boolean bval1;
-        boolean bval2;
         boolean numeric = val1 instanceof NumericValueExp;
         boolean bool = val1 instanceof BooleanValueExp;
         if (numeric) {
             if (((NumericValueExp)val1).isLong()) {
-                lval1 = ((NumericValueExp)val1).longValue();
-                lval2 = ((NumericValueExp)val2).longValue();
+                long lval1 = ((NumericValueExp)val1).longValue();
+                long lval2 = ((NumericValueExp)val2).longValue();
 
                 switch (relOp) {
                 case Query.GT:
@@ -136,8 +128,8 @@
                     return lval1 == lval2;
                 }
             } else {
-                dval1 = ((NumericValueExp)val1).doubleValue();
-                dval2 = ((NumericValueExp)val2).doubleValue();
+                double dval1 = ((NumericValueExp)val1).doubleValue();
+                double dval2 = ((NumericValueExp)val2).doubleValue();
 
                 switch (relOp) {
                 case Query.GT:
@@ -155,8 +147,8 @@
 
         } else if (bool) {
 
-            bval1 = ((BooleanValueExp)val1).getValue().booleanValue();
-            bval2 = ((BooleanValueExp)val2).getValue().booleanValue();
+            boolean bval1 = ((BooleanValueExp)val1).getValue().booleanValue();
+            boolean bval2 = ((BooleanValueExp)val2).getValue().booleanValue();
 
             switch (relOp) {
             case Query.GT:
@@ -172,8 +164,8 @@
             }
 
         } else {
-            sval1 = ((StringValueExp)val1).getValue();
-            sval2 = ((StringValueExp)val2).getValue();
+            String sval1 = ((StringValueExp)val1).getValue();
+            String sval2 = ((StringValueExp)val2).getValue();
 
             switch (relOp) {
             case Query.GT:
@@ -199,6 +191,11 @@
         return "(" + exp1 + ") " + relOpString() + " (" + exp2 + ")";
     }
 
+    @Override
+    String toQueryString() {
+        return exp1 + " " + relOpString() + " " + exp2;
+    }
+
     private String relOpString() {
         switch (relOp) {
         case Query.GT:
--- a/src/share/classes/javax/management/BooleanValueExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/BooleanValueExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -84,4 +84,10 @@
         return this;
     }
 
+    @Deprecated
+    public void setMBeanServer(MBeanServer s) {
+        super.setMBeanServer(s);
+    }
+
+
  }
--- a/src/share/classes/javax/management/InQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/InQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -91,21 +91,23 @@
      * @exception BadAttributeValueExpException
      * @exception InvalidApplicationException
      */
-    public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException,
+    public boolean apply(ObjectName name)
+    throws BadStringOperationException, BadBinaryOpValueExpException,
         BadAttributeValueExpException, InvalidApplicationException  {
         if (valueList != null) {
             ValueExp v      = val.apply(name);
             boolean numeric = v instanceof NumericValueExp;
 
-            for (int i = 0; i < valueList.length; i++) {
+            for (ValueExp element : valueList) {
+                element = element.apply(name);
                 if (numeric) {
-                    if (((NumericValueExp)valueList[i]).doubleValue() ==
-                        ((NumericValueExp)v).doubleValue()) {
+                    if (((NumericValueExp) element).doubleValue() ==
+                        ((NumericValueExp) v).doubleValue()) {
                         return true;
                     }
                 } else {
-                    if (((StringValueExp)valueList[i]).getValue().equals(
-                        ((StringValueExp)v).getValue())) {
+                    if (((StringValueExp) element).getValue().equals(
+                        ((StringValueExp) v).getValue())) {
                         return true;
                     }
                 }
--- a/src/share/classes/javax/management/MatchQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/MatchQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -113,7 +113,32 @@
     }
 
     private static String likeTranslate(String s) {
-        return s.replace('?', '_').replace('*', '%');
+        StringBuilder sb = new StringBuilder();
+        int c;
+        for (int i = 0; i < s.length(); i += Character.charCount(c)) {
+            c = s.codePointAt(i);
+            switch (c) {
+                case '\\':
+                    i += Character.charCount(c);
+                    sb.append('\\');
+                    if (i < s.length()) {
+                        c = s.codePointAt(i);
+                        sb.appendCodePoint(c);
+    }
+                    break;
+                case '*':
+                    sb.append('%'); break;
+                case '?':
+                    sb.append('_'); break;
+                case '%':
+                    sb.append("\\%"); break;
+                case '_':
+                    sb.append("\\_"); break;
+                default:
+                    sb.appendCodePoint(c); break;
+            }
+        }
+        return sb.toString();
     }
 
     /*
--- a/src/share/classes/javax/management/NotQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/NotQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -86,8 +86,14 @@
     /**
      * Returns the string representing the object.
      */
+    @Override
     public String toString()  {
         return "not (" + exp + ")";
     }
 
+    @Override
+    String toQueryString() {
+        return "not (" + Query.toString(exp) + ")";
+    }
+
  }
--- a/src/share/classes/javax/management/NumericValueExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/NumericValueExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -151,11 +151,18 @@
      * Returns the string representing the object
      */
     public String toString()  {
+      if (val == null)
+        return "null";
       if (val instanceof Long || val instanceof Integer)
       {
-        return String.valueOf(val.longValue());
+        return Long.toString(val.longValue());
       }
-      return String.valueOf(val.doubleValue());
+      double d = val.doubleValue();
+      if (Double.isInfinite(d))
+          return (d > 0) ? "(1.0 / 0.0)" : "(-1.0 / 0.0)";
+      if (Double.isNaN(d))
+          return "(0.0 / 0.0)";
+      return Double.toString(d);
     }
 
     /**
@@ -244,4 +251,10 @@
         out.defaultWriteObject();
       }
     }
+
+    @Deprecated
+    public void setMBeanServer(MBeanServer s) {
+        super.setMBeanServer(s);
+    }
+
  }
--- a/src/share/classes/javax/management/ObjectName.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/ObjectName.java	Fri Mar 28 03:06:00 2008 -0700
@@ -222,7 +222,8 @@
  * @since 1.5
  */
 @SuppressWarnings("serial") // don't complain serialVersionUID not constant
-public class ObjectName implements Comparable<ObjectName>, QueryExp {
+public class ObjectName extends ToQueryString
+        implements Comparable<ObjectName>, QueryExp {
 
     /**
      * A structure recording property structure and
@@ -1779,10 +1780,16 @@
      *
      * @return a string representation of this object name.
      */
+    @Override
     public String toString()  {
         return getSerializedNameString();
     }
 
+    @Override
+    String toQueryString() {
+        return "LIKE " + Query.value(toString());
+    }
+
     /**
      * Compares the current object name with another object name.  Two
      * ObjectName instances are equal if and only if their canonical
--- a/src/share/classes/javax/management/OrQueryExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/OrQueryExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -98,9 +98,29 @@
     }
 
     /**
-     * Returns a string representation of this AndQueryExp
+     * Returns a string representation of this OrQueryExp
      */
     public String toString() {
         return "(" + exp1 + ") or (" + exp2 + ")";
     }
+
+    @Override
+    String toQueryString() {
+        return parens(exp1) + " or " + parens(exp2);
+    }
+
+    // Add parentheses to avoid possible confusion.  If we have an expression
+    // such as Query.or(Query.and(a, b), c), then we return
+    // (a and b) or c
+    // rather than just
+    // a and b or c
+    // In fact the precedence rules are such that the parentheses are not
+    // strictly necessary, but omitting them would be confusing.
+    private static String parens(QueryExp exp) {
+        String s = Query.toString(exp);
+        if (exp instanceof AndQueryExp)
+            return "(" + s + ")";
+        else
+            return s;
+    }
 }
--- a/src/share/classes/javax/management/QualifiedAttributeValueExp.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/QualifiedAttributeValueExp.java	Fri Mar 28 03:06:00 2008 -0700
@@ -27,9 +27,11 @@
 
 
 /**
- * This class represents indexed attributes used as arguments to relational
- * constraints. An QualifiedAttributeValueExp may be used anywhere a
- * ValueExp is required.
+ * <p>Represents attributes used as arguments to relational constraints,
+ * where the attribute must be in an MBean of a specified {@linkplain
+ * MBeanInfo#getClassName() class}. A QualifiedAttributeValueExp may be used
+ * anywhere a ValueExp is required.
+ *
  * @serial include
  *
  * @since 1.5
@@ -48,7 +50,9 @@
 
     /**
      * Basic Constructor.
+     * @deprecated see {@link AttributeValueExp#AttributeValueExp()}
      */
+    @Deprecated
     public QualifiedAttributeValueExp() {
     }
 
@@ -81,6 +85,7 @@
      * @exception BadAttributeValueExpException
      * @exception InvalidApplicationException
      */
+    @Override
     public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException,
         BadAttributeValueExpException, InvalidApplicationException  {
         try {
@@ -105,9 +110,11 @@
     /**
      * Returns the string representing its value
      */
+    @Override
     public String toString()  {
         if (className != null) {
-            return className + "." + super.toString();
+            return QueryParser.quoteId(className) + "#" +
+                QueryParser.quoteId(super.toString());
         } else {
             return super.toString();
         }
--- a/src/share/classes/javax/management/Query.java	Thu Mar 27 12:31:18 2008 +0300
+++ b/src/share/classes/javax/management/Query.java	Fri Mar 28 03:06:00 2008 -0700
@@ -27,19 +27,346 @@
 
 
 /**
- * <p>Constructs query object constraints. The static methods provided
- * return query expressions that may be used in listing and
- * enumerating MBeans. Individual constraint construction methods
- * allow only appropriate types as arguments. Composition of calls can
- * construct arbitrary nestings of constraints, as the following
- * example illustrates:</p>
+ * <p>Constructs query object constraints.</p>
+ *
+ * <p>The MBean Server can be queried for MBeans that meet a particular
+ * condition, using its {@link MBeanServer#queryNames queryNames} or
+ * {@link MBeanServer#queryMBeans queryMBeans} method.  The {@link QueryExp}
+ * parameter to the method can be any implementation of the interface
+ * {@code QueryExp}, but it is usually best to obtain the {@code QueryExp}
+ * value by calling the static methods in this class.  This is particularly
+ * true when querying a remote MBean Server: a custom implementation of the
+ * {@code QueryExp} interface might not be present in the remote MBean Server,
+ * but the methods in this class return only standard classes that are
+ * part of the JMX implementation.</p>
+ *
+ * <p>There are two ways to create {@code QueryExp} objects using the methods
+ * in this class.  The first is to build them by chaining together calls to
+ * the various methods.  The second is to use the Query Language described
+ * <a href="#ql">below</a> and produce the {@code QueryExp} by calling
+ * {@link #fromString Query.fromString}.  The two ways are equivalent:
+ * every {@code QueryExp} returned by {@code fromString} can also be
+ * constructed by chaining method calls.</p>
+ *
+ * <p>As an example, suppose you wanted to find all MBeans where the {@code
+ * Enabled} attribute is {@code true} and the {@code Owner} attribute is {@code
+ * "Duke"}. Here is how you could construct the appropriate {@code QueryExp} by
+ * chaining together method calls:</p>
  *
  * <pre>
- * QueryExp exp = Query.and(Query.gt(Query.attr("age"),Query.value(5)),
- *                          Query.match(Query.attr("name"),
- *                                      Query.value("Smith")));
+ * QueryExp query =
+ *     Query.and(Query.eq(Query.attr("Enabled"), Query.value(true)),
+ *               Query.eq(Query.attr("Owner"), Query.value("Duke")));
  * </pre>
  *
+ * <p>Here is how you could construct the same {@code QueryExp} using the
+ * Query Language:</p>
+ *
+ * <pre>
+ * QueryExp query = Query.fromString("Enabled = true and Owner = 'Duke'");
+ * </pre>
+ *
+ * <p>The principal advantage of the method-chaining approach is that the
+ * compiler will check that the query makes sense.  The principal advantage
+ * of the Query Language approach is that it is easier to write and especially
+ * read.</p>
+ *
+ *
+ * <h4 id="ql">Query Language</h4>
+ *
+ * <p>The query language is closely modeled on the WHERE clause of
+ * SQL SELECT statements. The formal specification of the language
+ * appears <a href="#formal-ql">below</a>, but it is probably easier to
+ * understand it with examples such as the following.</p>
+ *
+ * <dl>
+ * <dt>{@code Message = 'OK'}
+ * <dd>Selects MBeans that have a {@code Message} attribute whose value
+ *     is the string {@code OK}.
+ *
+ * <dt>{@code FreeSpacePercent < 10}
+ * <dd>Selects MBeans that have a {@code FreeSpacePercent} attribute whose
+ *     value is a number less than 10.
+ *
+ * <dt>{@code FreeSpacePercent < 10 and WarningSent = false}
+ * <dd>Selects the same MBeans as the previous example, but they must
+ *     also have a boolean attribute {@code WarningSent} whose value
+ *     is false.
+ *
+ * <dt>{@code SpaceUsed > TotalSpace * (2.0 / 3.0)}
+ * <dd>Selects MBeans that have {@code SpaceUsed} and {@code TotalSpace}
+ *     attributes where the first is more than two-thirds the second.
+ *
+ * <dt>{@code not (FreeSpacePercent between 10 and 90)}
+ * <dd>Selects MBeans that have a {@code FreeSpacePercent} attribute whose
+ *     value is not between 10 and 90, inclusive.
+ *
+ * <dt>{@code FreeSpacePercent not between 10 and 90}
+ * <dd>Another way of writing the previous query.
+ *
+ * <dt>{@code Status in ('STOPPED', 'STARTING', 'STARTED')}
+ * <dd>Selects MBeans that have a {@code Status} attribute whose value
+ *     is one of those three strings.
+ *
+ * <dt>{@code Message like 'OK: %'}
+ * <dd>Selects MBeans that have a {@code Message} attribute whose value
+ *     is a string beginning with {@code "OK: "}.  <b>Notice that the
+ *     wildcard characters are SQL's ones.</b>  In the query language,
+ *     {@code %} means "any sequence of characters" and {@code _}
+ *     means "any single character".  In the rest of the JMX API, these
+ *     correspond to {@code *} and {@code %} respectively.
+ *
+ * <dt>{@code instanceof 'javax.management.NotificationBroadcaster'}
+ * <dd>Selects MBeans that are instances of
+ *     {@link javax.management.NotificationBroadcaster}, as reported by
+ *     {@link javax.management.MBeanServer#isInstanceOf MBeanServer.isInstanceOf}.
+ *
+ * <dt>{@code like 'mydomain:*'}
+ * <dd>Selects MBeans whose {@link ObjectName}s have the domain {@code mydomain}.
+ *
+ * </dl>
+ *
+ * <p>The last two examples do not correspond to valid SQL syntax, but all
+ * the others do.</p>
+ *
+ * <p>The remainder of this description is a formal specification of the
+ * query language.</p>
+ *
+ *
+ * <h4 id="formal-ql">Lexical elements</h4>
+ *
+ * <p>Keywords such as <b>and</b>, <b>like</b>, and <b>between</b> are not
+ * case sensitive.  You can write <b>between</b>, <b>BETWEEN</b>, or
+ * <b>BeTwEeN</b> with the same effect.</p>
+ *
+ * <p>On the other hand, attribute names <i>are</i> case sensitive.  The
+ * attribute {@code Name} is not the same as the attribute {@code name}.</p>
+ *
+ * <p>To access an attribute whose name, ignoring case, is the same as one of
+ * the keywords {@code not}, {@code instanceof}, {@code like}, {@code true},
+ * or {@code false}, you can use double quotes, for example {@code "not"}.
+ * Double quotes can also be used to include non-identifier characters in
+ * the name of an attribute, for example {@code "attribute-name-with-hyphens"}.
+ * To include the double quote character in the attribute name, write it
+ * twice.  {@code "foo""bar""baz"} represents the attribute called
+ * {@code foo"bar"baz}.
+ *
+ * <p>String constants are written with single quotes like {@code 'this'}.  A
+ * single quote within a string constant must be doubled, for example
+ * {@code 'can''t'}.</p>
+ *
+ * <p>Integer constants are written as a sequence of decimal digits,
+ * optionally preceded by a plus or minus sign.  An integer constant must be
+ * a valid input to {@link Long#valueOf(String)}.</p>
+ *
+ * <p>Floating-point constants are written using the Java syntax.  A
+ * floating-point constant must be a valid input to
+ * {@link Double#valueOf(String)}.</p>
+ *
+ * <p>A boolean constant is either {@code true} or {@code false}, ignoring
+ * case.</p>
+ *
+ * <p>Spaces cannot appear inside identifiers (unless written with double
+ * quotes) or keywords or multi-character tokens such as {@code <=}. Spaces can
+ * appear anywhere else, but are not required except to separate tokens. For
+ * example, the query {@code a < b and 5 = c} could also be written {@code a<b
+ * and 5=c}, but no further spaces can be removed.</p>
+ *
+ *
+ * <h4 id="grammar-ql">Grammar</h4>
+ *
+ * <dl>
+ * <dt id="query">query:
+ * <dd><a href="#andquery">andquery</a> [<b>OR</b> <a href="#query">query</a>]
+ *
+ * <dt id="andquery">andquery:
+ * <dd><a href="#predicate">predicate</a> [<b>AND</b> <a href="#andquery">andquery</a>]
+ *
+ * <dt id="predicate">predicate:
+ * <dd><b>(</b> <a href="#query">query</a> <b>)</b> |<br>
+ *     <b>NOT</b> <a href="#predicate">predicate</a> |<br>
+ *     <b>INSTANCEOF</b> <a href="#stringvalue">stringvalue</a> |<br>
+ *     <b>LIKE</b> <a href="#objectnamepattern">objectnamepattern</a> |<br>
+ *     <a href="#value">value</a> <a href="#predrhs">predrhs</a>
+ *
+ * <dt id="predrhs">predrhs:
+ * <dd><a href="#compare">compare</a> <a href="#value">value</a> |<br>
+ *     [<b>NOT</b>] <b>BETWEEN</b> <a href="#value">value</a> <b>AND</b>
+ *         <a href="#value">value</a> |<br>
+ *     [<b>NOT</b>] <b>IN (</b> <a href="#value">value</a>
+ *           <a href="#commavalues">commavalues</a> <b>)</b> |<br>
+ *     [<b>NOT</b>] <b>LIKE</b> <a href="#stringvalue">stringvalue</a>
+ *
+ * <dt id="commavalues">commavalues:
+ * <dd>[ <b>,</b> <a href="#value">value</a> <a href="#commavalues">commavalues</a> ]
+ *
+ * <dt id="compare">compare:
+ * <dd><b>=</b> | <b>&lt;</b> | <b>&gt;</b> |
+ *     <b>&lt;=</b> | <b>&gt;=</b> | <b>&lt;&gt;</b> | <b>!=</b>
+ *
+ * <dt id="value">value:
+ * <dd><a href="#factor">factor</a> [<a href="#plusorminus">plusorminus</a>
+ *     <a href="#value">value</a>]
+ *
+ * <dt id="plusorminus">plusorminus:
+ * <dd><b>+</b> | <b>-</b>
+ *
+ * <dt id="factor">factor:
+ * <dd><a href="#term">term</a> [<a href="#timesordivide">timesordivide</a>
+ *     <a href="#factor">factor</a>]
+ *
+ * <dt id="timesordivide">timesordivide:
+ * <dd><b>*</b> | <b>/</b>
+ *
+ * <dt id="term">term:
+ * <dd><a href="#attr">attr</a> | <a href="#literal">literal</a> |
+ *     <b>(</b> <a href="#value">value</a> <b>)</b>
+ *
+ * <dt id="attr">attr:
+ * <dd><a href="#name">name</a> [<b>#</b> <a href="#name">name</a>]
+ *
+ * <dt id="name">name:
+ * <dd><a href="#identifier">identifier</a> [<b>.</b><a href="#name">name</a>]
+ *
+ * <dt id="identifier">identifier:
+ * <dd><i>Java-identifier</i> | <i>double-quoted-identifier</i>
+ *
+ * <dt id="literal">literal:
+ * <dd><a href="#booleanlit">booleanlit</a> | <i>longlit</i> |
+ *     <i>doublelit</i> | <i>stringlit</i>
+ *
+ * <dt id="booleanlit">booleanlit:
+ * <dd><b>FALSE</b> | <b>TRUE</b>
+ *
+ * <dt id="stringvalue">stringvalue:
+ * <dd><i>stringlit</i>
+ *
+ * <dt id="objectnamepattern">objectnamepattern:
+ * <dd><i>stringlit</i>
+ *
+ * </dl>
+ *
+ *
+ * <h4>Semantics</h4>
+ *
+ * <p>The meaning of the grammar is described in the table below.
+ * This defines a function <i>q</i> that maps a string to a Java object
+ * such as a {@link QueryExp} or a {@link ValueExp}.</p>
+ *
+ * <table border="1" cellpadding="5">
+ * <tr><th>String <i>s</i></th><th><i>q(s)</th></tr>
+ *
+ * <tr><td><i>query1</i> <b>OR</b> <i>query2</i>
+ *     <td>{@link Query#or Query.or}(<i>q(query1)</i>, <i>q(query2)</i>)
+ *
+ * <tr><td><i>query1</i> <b>AND</b> <i>query2</i>
+ *     <td>{@link Query#and Query.and}(<i>q(query1)</i>, <i>q(query2)</i>)
+ *
+ * <tr><td><b>(</b> <i>queryOrValue</i> <b>)</b>
+ *     <td><i>q(queryOrValue)</i>
+ *
+ * <tr><td><b>NOT</b> <i>query</i>
+ *     <td>{@link Query#not Query.not}(<i>q(query)</i>)
+ *
+ * <tr><td><b>INSTANCEOF</b> <i>stringLiteral</i>
+ *     <td>{@link Query#isInstanceOf Query.isInstanceOf}(<!--
+ * -->{@link Query#value(String) Query.value}(<i>q(stringLiteral)</i>))
+ *
+ * <tr><td><b>LIKE</b> <i>stringLiteral</i>
+ *     <td>{@link ObjectName#ObjectName(String) new ObjectName}(<!--
+ * --><i>q(stringLiteral)</i>)
+ *
+ * <tr><td><i>value1</i> <b>=</b> <i>value2</i>
+ *     <td>{@link Query#eq Query.eq}(<i>q(value1)</i>, <i>q(value2)</i>)
+ *
+ * <tr><td><i>value1</i> <b>&lt;</b> <i>value2</i>
+ *     <td>{@link Query#lt Query.lt}(<i>q(value1)</i>, <i>q(value2)</i>)
+ *
+ * <tr><td><i>value1</i> <b>&gt;</b> <i>value2</i>
+ *     <td>{@link Query#gt Query.gt}(<i>q(value1)</i>, <i>q(value2)</i>)
+ *
+ * <tr><td><i>value1</i> <b>&lt;=</b> <i>value2</i>
+ *     <td>{@link Query#leq Query.leq}(<i>q(value1)</i>, <i>q(value2)</i>)
+ *
+ * <tr><td><i>value1</i> <b>&gt;=</b> <i>value2</i>
+ *     <td>{@link Query#geq Query.geq}(<i>q(value1)</i>, <i>q(value2)</i>)
+ *
+ * <tr><td><i>value1</i> <b>&lt;&gt;</b> <i>value2</i>
+ *     <td>{@link Query#not Query.not}({@link Query#eq Query.eq}(<!--
+ * --><i>q(value1)</i>, <i>q(value2)</i>))
+ *
+ * <tr><td><i>value1</i> <b>!=</b> <i>value2</i>
+ *     <td>{@link Query#not Query.not}({@link Query#eq Query.eq}(<!--
+ * --><i>q(value1)</i>, <i>q(value2)</i>))
+ *
+ * <tr><td><i>value1</i> <b>BETWEEN</b> <i>value2</i> AND <i>value3</i>
+ *     <td>{@link Query#between Query.between}(<i>q(value1)</i>,
+ *         <i>q(value2)</i>, <i>q(value3)</i>)
+ *
+ * <tr><td><i>value1</i> <b>NOT BETWEEN</b> <i>value2</i> AND <i>value3</i>
+ *     <td>{@link Query#not Query.not}({@link Query#between Query.between}(<!--
+ * --><i>q(value1)</i>, <i>q(value2)</i>, <i>q(value3)</i>))
+ *
+ * <tr><td><i>value1</i> <b>IN (</b> <i>value2</i>, <i>value3</i> <b>)</b>
+ *     <td>{@link Query#in Query.in}(<i>q(value1)</i>,
+ *         &l