--- a/.hgtags-top-repo Thu Jul 17 09:50:06 2014 -0700
+++ b/.hgtags-top-repo Wed Jul 05 19:50:57 2017 +0200
@@ -265,3 +265,4 @@
ee4fd72b2ec3d92497f37163352f294aa695c6fb jdk9-b20
9052803f4d01feda28b3d65f2b64dd457d21c7b6 jdk9-b21
8e4bdab4c362aadde2d321f968cd503a2f779e2f jdk9-b22
+88567461a2cd9b7fb431fee6440005a694df1f47 jdk9-b23
--- a/common/autoconf/flags.m4 Thu Jul 17 09:50:06 2014 -0700
+++ b/common/autoconf/flags.m4 Wed Jul 05 19:50:57 2017 +0200
@@ -407,11 +407,7 @@
C_O_FLAG_HI="-O3"
C_O_FLAG_NORM="-O2"
fi
- if test "x$HAS_CFLAG_OPTIMIZE_DEBUG" = "xtrue"; then
- C_O_FLAG_DEBUG="$CFLAG_OPTIMIZE_DEBUG_FLAG"
- else
- C_O_FLAG_DEBUG="-O0"
- fi
+ C_O_FLAG_DEBUG="-O0"
C_O_FLAG_NONE="-O0"
elif test "x$TOOLCHAIN_TYPE" = xclang; then
if test "x$OPENJDK_TARGET_OS" = xmacosx; then
--- a/common/autoconf/generated-configure.sh Thu Jul 17 09:50:06 2014 -0700
+++ b/common/autoconf/generated-configure.sh Wed Jul 05 19:50:57 2017 +0200
@@ -4311,7 +4311,7 @@
#CUSTOM_AUTOCONF_INCLUDE
# Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1403557683
+DATE_WHEN_GENERATED=1404942241
###############################################################################
#
@@ -42011,11 +42011,7 @@
C_O_FLAG_HI="-O3"
C_O_FLAG_NORM="-O2"
fi
- if test "x$HAS_CFLAG_OPTIMIZE_DEBUG" = "xtrue"; then
- C_O_FLAG_DEBUG="$CFLAG_OPTIMIZE_DEBUG_FLAG"
- else
- C_O_FLAG_DEBUG="-O0"
- fi
+ C_O_FLAG_DEBUG="-O0"
C_O_FLAG_NONE="-O0"
elif test "x$TOOLCHAIN_TYPE" = xclang; then
if test "x$OPENJDK_TARGET_OS" = xmacosx; then
--- a/hotspot/.hgtags Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/.hgtags Wed Jul 05 19:50:57 2017 +0200
@@ -425,3 +425,4 @@
c1af79d122ec9f715fa29312b5e91763f3a4dfc4 jdk9-b20
17b4a5e831b398738feedb0afe75245744510153 jdk9-b21
518d1fcc0799494f013e00e0a94a91b6f212d54f jdk9-b22
+dd472cdacc32e3afc7c5bfa7ef16ea0e0befb7fa jdk9-b23
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_implementation/g1/HeapRegion.java Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/gc_implementation/g1/HeapRegion.java Wed Jul 05 19:50:57 2017 +0200
@@ -24,23 +24,26 @@
package sun.jvm.hotspot.gc_implementation.g1;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Observable;
import java.util.Observer;
-
import sun.jvm.hotspot.debugger.Address;
-import sun.jvm.hotspot.memory.ContiguousSpace;
+import sun.jvm.hotspot.memory.CompactibleSpace;
+import sun.jvm.hotspot.memory.MemRegion;
import sun.jvm.hotspot.runtime.VM;
+import sun.jvm.hotspot.types.AddressField;
import sun.jvm.hotspot.types.CIntegerField;
import sun.jvm.hotspot.types.Type;
import sun.jvm.hotspot.types.TypeDataBase;
// Mirror class for HeapRegion. Currently we don't actually include
-// any of its fields but only iterate over it (which we get "for free"
-// as HeapRegion ultimately inherits from ContiguousSpace).
+// any of its fields but only iterate over it.
-public class HeapRegion extends ContiguousSpace {
+public class HeapRegion extends CompactibleSpace {
// static int GrainBytes;
static private CIntegerField grainBytesField;
+ static private AddressField topField;
static {
VM.registerVMInitializedObserver(new Observer() {
@@ -54,6 +57,8 @@
Type type = db.lookupType("HeapRegion");
grainBytesField = type.getCIntegerField("GrainBytes");
+ topField = type.getAddressField("_top");
+
}
static public long grainBytes() {
@@ -63,4 +68,25 @@
public HeapRegion(Address addr) {
super(addr);
}
+
+ public Address top() {
+ return topField.getValue(addr);
+ }
+
+ @Override
+ public List getLiveRegions() {
+ List res = new ArrayList();
+ res.add(new MemRegion(bottom(), top()));
+ return res;
+ }
+
+ @Override
+ public long used() {
+ return top().minus(bottom());
+ }
+
+ @Override
+ public long free() {
+ return end().minus(top());
+ }
}
--- a/hotspot/make/bsd/makefiles/gcc.make Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/bsd/makefiles/gcc.make Wed Jul 05 19:50:57 2017 +0200
@@ -280,16 +280,7 @@
# optimization control flags (Used by fastdebug and release variants)
OPT_CFLAGS/NOOPT=-O0
-ifeq ($(USE_CLANG), true)
- # Clang does not support -Og
- OPT_CFLAGS/DEBUG=-O0
-else ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
- # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
- OPT_CFLAGS/DEBUG=-Og
-else
- # Allow no optimizations.
- OPT_CFLAGS/DEBUG=-O0
-endif
+OPT_CFLAGS/DEBUG=-O0
OPT_CFLAGS/SIZE=-Os
OPT_CFLAGS/SPEED=-O3
@@ -457,16 +448,8 @@
CFLAGS += -flimit-debug-info
endif
-ifeq ($(USE_CLANG), true)
- # Clang does not support -Og
- DEBUG_CFLAGS=-O0
-else ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
- # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
- DEBUG_CFLAGS=-Og
-else
- # Allow no optimizations.
- DEBUG_CFLAGS=-O0
-endif
+# Allow no optimizations.
+DEBUG_CFLAGS=-O0
# DEBUG_BINARIES uses full -g debug information for all configs
ifeq ($(DEBUG_BINARIES), true)
--- a/hotspot/make/excludeSrc.make Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/excludeSrc.make Wed Jul 05 19:50:57 2017 +0200
@@ -93,6 +93,7 @@
ageTable.cpp \
collectorCounters.cpp \
cSpaceCounters.cpp \
+ gcId.cpp \
gcPolicyCounters.cpp \
gcStats.cpp \
gcTimer.cpp \
--- a/hotspot/make/linux/Makefile Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/linux/Makefile Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -67,8 +67,12 @@
endif
endif
# C1 is not ported on ppc64, so we cannot build a tiered VM:
-ifeq ($(ARCH),ppc64)
- FORCE_TIERED=0
+# Notice: after 8046471 ARCH will be 'ppc' for top-level ppc64 builds but
+# 'ppc64' for HotSpot-only ppc64 builds. Need to detect both variants here!
+ifneq (,$(findstring $(ARCH), ppc ppc64))
+ ifeq ($(ARCH_DATA_MODEL), 64)
+ FORCE_TIERED=0
+ endif
endif
ifdef LP64
--- a/hotspot/make/linux/makefiles/defs.make Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/linux/makefiles/defs.make Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -108,7 +108,9 @@
endif
# PPC
-ifneq (,$(findstring $(ARCH), ppc))
+# Notice: after 8046471 ARCH will be 'ppc' for top-level ppc64 builds but
+# 'ppc64' for HotSpot-only ppc64 builds. Need to detect both variants here!
+ifneq (,$(findstring $(ARCH), ppc ppc64))
ifeq ($(ARCH_DATA_MODEL), 64)
MAKE_ARGS += LP64=1
PLATFORM = linux-ppc64
--- a/hotspot/make/linux/makefiles/dtrace.make Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/linux/makefiles/dtrace.make Wed Jul 05 19:50:57 2017 +0200
@@ -40,7 +40,14 @@
ifneq ($(ALT_SDT_H),)
SDT_H_FILE = $(ALT_SDT_H)
else
- SDT_H_FILE = /usr/include/sys/sdt.h
+ ifeq ($(USE_CLANG), true)
+ # Clang doesn't support the -print-sysroot option and there is no known equivalent
+ # option, so fall back to using / as sysroot
+ SDT_SYSROOT=
+ else
+ SDT_SYSROOT=$(shell $(CXX) -print-sysroot)
+ endif
+ SDT_H_FILE = $(SDT_SYSROOT)/usr/include/sys/sdt.h
endif
DTRACE_ENABLED = $(shell test -f $(SDT_H_FILE) && echo $(SDT_H_FILE))
--- a/hotspot/make/linux/makefiles/gcc.make Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/linux/makefiles/gcc.make Wed Jul 05 19:50:57 2017 +0200
@@ -231,13 +231,7 @@
# optimization control flags (Used by fastdebug and release variants)
OPT_CFLAGS/NOOPT=-O0
-ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
- # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
- OPT_CFLAGS/DEBUG=-Og
-else
- # Allow no optimizations.
- OPT_CFLAGS/DEBUG=-O0
-endif
+OPT_CFLAGS/DEBUG=-O0
OPT_CFLAGS/SIZE=-Os
OPT_CFLAGS/SPEED=-O3
@@ -344,13 +338,8 @@
CFLAGS += -flimit-debug-info
endif
-ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
- # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
- DEBUG_CFLAGS=-Og
-else
- # Allow no optimizations.
- DEBUG_CFLAGS=-O0
-endif
+# Allow no optimizations.
+DEBUG_CFLAGS=-O0
# DEBUG_BINARIES uses full -g debug information for all configs
ifeq ($(DEBUG_BINARIES), true)
--- a/hotspot/make/solaris/makefiles/gcc.make Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/make/solaris/makefiles/gcc.make Wed Jul 05 19:50:57 2017 +0200
@@ -127,13 +127,7 @@
# optimization control flags (Used by fastdebug and release variants)
OPT_CFLAGS/NOOPT=-O0
-ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
- # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
- OPT_CFLAGS/DEBUG=-Og
-+else
- # Allow no optimizations.
- OPT_CFLAGS/DEBUG=-O0
-endif
+OPT_CFLAGS/DEBUG=-O0
OPT_CFLAGS/SIZE=-Os
OPT_CFLAGS/SPEED=-O3
@@ -229,14 +223,8 @@
#------------------------------------------------------------------------
# Debug flags
-ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 8 \) \))" "1"
- # Allow basic optimizations which don't distrupt debugging. (Principally dead code elimination)
- DEBUG_CFLAGS=-Og
-else
- # Allow no optimizations.
- DEBUG_CFLAGS=-O0
-endif
-
+# Allow no optimizations.
+DEBUG_CFLAGS=-O0
# Use the stabs format for debugging information (this is the default
# on gcc-2.91). It's good enough, has all the information about line
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -32,12 +32,6 @@
#include "runtime/stubCodeGenerator.hpp"
#include "utilities/defaultStream.hpp"
#include "vm_version_ppc.hpp"
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
# include <sys/sysinfo.h>
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -34,7 +34,7 @@
#include "runtime/biasedLocking.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/objectMonitor.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubRoutines.hpp"
#include "utilities/macros.hpp"
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -28,12 +28,6 @@
#include "runtime/java.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "vm_version_sparc.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
int VM_Version::_features = VM_Version::unknown_m;
const char* VM_Version::_features_str = "";
--- a/hotspot/src/cpu/x86/vm/frame_x86.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/frame_x86.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -33,7 +33,7 @@
#include "runtime/handles.inline.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/monitorChunk.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/signature.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "runtime/stubRoutines.hpp"
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,18 +29,6 @@
#include "runtime/java.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "vm_version_x86.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
int VM_Version::_cpu;
--- a/hotspot/src/cpu/zero/vm/vm_version_zero.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/cpu/zero/vm/vm_version_zero.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright 2009 Red Hat, Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -29,11 +29,5 @@
#include "runtime/java.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "vm_version_zero.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
// This file is intentionally empty
--- a/hotspot/src/os/aix/vm/attachListener_aix.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/aix/vm/attachListener_aix.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright 2012, 2013 SAP AG. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -25,7 +25,7 @@
#include "precompiled.hpp"
#include "runtime/interfaceSupport.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "services/attachListener.hpp"
#include "services/dtraceAttacher.hpp"
--- a/hotspot/src/os/aix/vm/os_aix.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/aix/vm/os_aix.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -42,6 +42,7 @@
#include "memory/filemap.hpp"
#include "mutex_aix.inline.hpp"
#include "oops/oop.inline.hpp"
+#include "os_aix.inline.hpp"
#include "os_share_aix.hpp"
#include "porting_aix.hpp"
#include "prims/jniFastGetField.hpp"
@@ -2807,12 +2808,10 @@
return DontYieldALot;
}
-void os::yield() {
+void os::naked_yield() {
sched_yield();
}
-os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; }
-
////////////////////////////////////////////////////////////////////////////////
// thread priority support
@@ -3069,7 +3068,7 @@
for (int n = 0; !osthread->sr.is_suspended(); n++) {
for (int i = 0; i < RANDOMLY_LARGE_INTEGER2 && !osthread->sr.is_suspended(); i++) {
- os::yield();
+ os::naked_yield();
}
// timeout, try to cancel the request
@@ -3103,7 +3102,7 @@
if (sr_notify(osthread) == 0) {
for (int n = 0; n < RANDOMLY_LARGE_INTEGER && !osthread->sr.is_running(); n++) {
for (int i = 0; i < 100 && !osthread->sr.is_running(); i++) {
- os::yield();
+ os::naked_yield();
}
}
} else {
--- a/hotspot/src/os/aix/vm/os_aix.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/aix/vm/os_aix.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright 2012, 2013 SAP AG. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -26,8 +26,6 @@
#ifndef OS_AIX_VM_OS_AIX_INLINE_HPP
#define OS_AIX_VM_OS_AIX_INLINE_HPP
-#include "runtime/atomic.inline.hpp"
-#include "runtime/orderAccess.inline.hpp"
#include "runtime/os.hpp"
// System includes
@@ -45,18 +43,6 @@
return pthread_getspecific((pthread_key_t)index);
}
-inline const char* os::file_separator() {
- return "/";
-}
-
-inline const char* os::line_separator() {
- return "\n";
-}
-
-inline const char* os::path_separator() {
- return ":";
-}
-
// File names are case-sensitive on windows only
inline int os::file_name_strcmp(const char* s1, const char* s2) {
return strcmp(s1, s2);
--- a/hotspot/src/os/bsd/vm/attachListener_bsd.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/bsd/vm/attachListener_bsd.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
#include "precompiled.hpp"
#include "runtime/interfaceSupport.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "services/attachListener.hpp"
#include "services/dtraceAttacher.hpp"
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -36,6 +36,7 @@
#include "memory/filemap.hpp"
#include "mutex_bsd.inline.hpp"
#include "oops/oop.inline.hpp"
+#include "os_bsd.inline.hpp"
#include "os_share_bsd.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm.h"
@@ -1171,10 +1172,6 @@
::abort();
}
-// unused on bsd for now.
-void os::set_error_file(const char *logfile) {}
-
-
// This method is a copy of JDK's sysGetLastErrorString
// from src/solaris/hpi/src/system_md.c
@@ -1831,6 +1828,7 @@
// determine if this is a legacy image or modules image
// modules image doesn't have "jre" subdirectory
len = strlen(buf);
+ assert(len < buflen, "Ran out of buffer space");
jrelib_p = buf + len;
// Add the appropriate library subdir
@@ -1864,7 +1862,7 @@
}
}
- strcpy(saved_jvm_path, buf);
+ strncpy(saved_jvm_path, buf, MAXPATHLEN);
}
void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
@@ -2595,12 +2593,10 @@
return DontYieldALot;
}
-void os::yield() {
+void os::naked_yield() {
sched_yield();
}
-os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; }
-
////////////////////////////////////////////////////////////////////////////////
// thread priority support
@@ -4217,22 +4213,12 @@
return abstime;
}
-
-// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
-// Conceptually TryPark() should be equivalent to park(0).
-
-int os::PlatformEvent::TryPark() {
- for (;;) {
- const int v = _Event;
- guarantee((v == 0) || (v == 1), "invariant");
- if (Atomic::cmpxchg(0, &_Event, v) == v) return v;
- }
-}
-
void os::PlatformEvent::park() { // AKA "down()"
// Invariant: Only the thread associated with the Event/PlatformEvent
// may call park().
// TODO: assert that _Assoc != NULL or _Assoc == Self
+ assert(_nParked == 0, "invariant");
+
int v;
for (;;) {
v = _Event;
@@ -4332,8 +4318,7 @@
// 1 :=> 1
// -1 :=> either 0 or 1; must signal target thread
// That is, we can safely transition _Event from -1 to either
- // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
- // unpark() calls.
+ // 0 or 1.
// See also: "Semaphores in Plan 9" by Mullender & Cox
//
// Note: Forcing a transition from "-1" to "1" on an unpark() means
@@ -4540,10 +4525,9 @@
}
void Parker::unpark() {
- int s, status;
- status = pthread_mutex_lock(_mutex);
+ int status = pthread_mutex_lock(_mutex);
assert(status == 0, "invariant");
- s = _counter;
+ const int s = _counter;
_counter = 1;
if (s < 1) {
if (WorkAroundNPTLTimedWaitHang) {
--- a/hotspot/src/os/bsd/vm/os_bsd.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -219,7 +219,6 @@
int fired() { return _Event; }
void park();
void unpark();
- int TryPark();
int park(jlong millis);
void SetAssociation(Thread * a) { _Assoc = a; }
};
--- a/hotspot/src/os/bsd/vm/os_bsd.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,8 +25,6 @@
#ifndef OS_BSD_VM_OS_BSD_INLINE_HPP
#define OS_BSD_VM_OS_BSD_INLINE_HPP
-#include "runtime/atomic.inline.hpp"
-#include "runtime/orderAccess.inline.hpp"
#include "runtime/os.hpp"
// System includes
@@ -40,18 +38,6 @@
return pthread_getspecific((pthread_key_t)index);
}
-inline const char* os::file_separator() {
- return "/";
-}
-
-inline const char* os::line_separator() {
- return "\n";
-}
-
-inline const char* os::path_separator() {
- return ":";
-}
-
// File names are case-sensitive on windows only
inline int os::file_name_strcmp(const char* s1, const char* s2) {
return strcmp(s1, s2);
--- a/hotspot/src/os/linux/vm/attachListener_linux.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
#include "precompiled.hpp"
#include "runtime/interfaceSupport.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "services/attachListener.hpp"
#include "services/dtraceAttacher.hpp"
--- a/hotspot/src/os/linux/vm/os_linux.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -36,6 +36,7 @@
#include "memory/filemap.hpp"
#include "mutex_linux.inline.hpp"
#include "oops/oop.inline.hpp"
+#include "os_linux.inline.hpp"
#include "os_share_linux.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm.h"
@@ -1552,9 +1553,6 @@
::abort();
}
-// unused on linux for now.
-void os::set_error_file(const char *logfile) {}
-
// This method is a copy of JDK's sysGetLastErrorString
// from src/solaris/hpi/src/system_md.c
@@ -2344,6 +2342,7 @@
// determine if this is a legacy image or modules image
// modules image doesn't have "jre" subdirectory
len = strlen(buf);
+ assert(len < buflen, "Ran out of buffer room");
jrelib_p = buf + len;
snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
if (0 != access(buf, F_OK)) {
@@ -2364,7 +2363,7 @@
}
}
- strcpy(saved_jvm_path, buf);
+ strncpy(saved_jvm_path, buf, MAXPATHLEN);
}
void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
@@ -3790,12 +3789,10 @@
return DontYieldALot;
}
-void os::yield() {
+void os::naked_yield() {
sched_yield();
}
-os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; }
-
////////////////////////////////////////////////////////////////////////////////
// thread priority support
@@ -5456,22 +5453,12 @@
return abstime;
}
-
-// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
-// Conceptually TryPark() should be equivalent to park(0).
-
-int os::PlatformEvent::TryPark() {
- for (;;) {
- const int v = _Event;
- guarantee((v == 0) || (v == 1), "invariant");
- if (Atomic::cmpxchg(0, &_Event, v) == v) return v;
- }
-}
-
void os::PlatformEvent::park() { // AKA "down()"
// Invariant: Only the thread associated with the Event/PlatformEvent
// may call park().
// TODO: assert that _Assoc != NULL or _Assoc == Self
+ assert(_nParked == 0, "invariant");
+
int v;
for (;;) {
v = _Event;
@@ -5571,8 +5558,7 @@
// 1 :=> 1
// -1 :=> either 0 or 1; must signal target thread
// That is, we can safely transition _Event from -1 to either
- // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
- // unpark() calls.
+ // 0 or 1.
// See also: "Semaphores in Plan 9" by Mullender & Cox
//
// Note: Forcing a transition from "-1" to "1" on an unpark() means
@@ -5800,10 +5786,9 @@
}
void Parker::unpark() {
- int s, status;
- status = pthread_mutex_lock(_mutex);
+ int status = pthread_mutex_lock(_mutex);
assert(status == 0, "invariant");
- s = _counter;
+ const int s = _counter;
_counter = 1;
if (s < 1) {
// thread might be parked
--- a/hotspot/src/os/linux/vm/os_linux.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -315,7 +315,6 @@
int fired() { return _Event; }
void park();
void unpark();
- int TryPark();
int park(jlong millis); // relative timed-wait only
void SetAssociation(Thread * a) { _Assoc = a; }
};
--- a/hotspot/src/os/linux/vm/os_linux.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,8 +25,6 @@
#ifndef OS_LINUX_VM_OS_LINUX_INLINE_HPP
#define OS_LINUX_VM_OS_LINUX_INLINE_HPP
-#include "runtime/atomic.inline.hpp"
-#include "runtime/orderAccess.inline.hpp"
#include "runtime/os.hpp"
// System includes
@@ -40,18 +38,6 @@
return pthread_getspecific((pthread_key_t)index);
}
-inline const char* os::file_separator() {
- return "/";
-}
-
-inline const char* os::line_separator() {
- return "\n";
-}
-
-inline const char* os::path_separator() {
- return ":";
-}
-
// File names are case-sensitive on windows only
inline int os::file_name_strcmp(const char* s1, const char* s2) {
return strcmp(s1, s2);
--- a/hotspot/src/os/posix/vm/os_posix.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/posix/vm/os_posix.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -22,8 +22,16 @@
*
*/
+#include "runtime/os.hpp"
+
#ifndef OS_POSIX_VM_OS_POSIX_HPP
#define OS_POSIX_VM_OS_POSIX_HPP
+
+// File conventions
+static const char* file_separator() { return "/"; }
+static const char* line_separator() { return "\n"; }
+static const char* path_separator() { return ":"; }
+
class Posix {
friend class os;
--- a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
#include "precompiled.hpp"
#include "runtime/interfaceSupport.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "services/attachListener.hpp"
#include "services/dtraceAttacher.hpp"
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -37,6 +37,7 @@
#include "mutex_solaris.inline.hpp"
#include "oops/oop.inline.hpp"
#include "os_share_solaris.hpp"
+#include "os_solaris.inline.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm.h"
#include "prims/jvm_misc.hpp"
@@ -1542,9 +1543,6 @@
::abort(); // dump core (for debugging)
}
-// unused
-void os::set_error_file(const char *logfile) {}
-
// DLL functions
const char* os::dll_file_extension() { return ".so"; }
@@ -2184,6 +2182,7 @@
// determine if this is a legacy image or modules image
// modules image doesn't have "jre" subdirectory
len = strlen(buf);
+ assert(len < buflen, "Ran out of buffer space");
jrelib_p = buf + len;
snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
if (0 != access(buf, F_OK)) {
@@ -2202,7 +2201,7 @@
}
}
- strcpy(saved_jvm_path, buf);
+ strncpy(saved_jvm_path, buf, MAXPATHLEN);
}
@@ -3172,20 +3171,14 @@
}
}
-// Caveat: Solaris os::yield() causes a thread-state transition whereas
-// the linux and win32 implementations do not. This should be checked.
-
-void os::yield() {
- // Yields to all threads with same or greater priority
- os::sleep(Thread::current(), 0, false);
-}
-
// Note that yield semantics are defined by the scheduling class to which
// the thread currently belongs. Typically, yield will _not yield to
// other equal or higher priority threads that reside on the dispatch queues
// of other CPUs.
-os::YieldResult os::NakedYield() { thr_yield(); return os::YIELD_UNKNOWN; }
+void os::naked_yield() {
+ thr_yield();
+}
// Interface for setting lwp priorities. If we are using T2 libthread,
// which forces the use of BoundThreads or we manually set UseBoundThreads,
@@ -5439,20 +5432,11 @@
return abstime;
}
-// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
-// Conceptually TryPark() should be equivalent to park(0).
-
-int os::PlatformEvent::TryPark() {
- for (;;) {
- const int v = _Event;
- guarantee((v == 0) || (v == 1), "invariant");
- if (Atomic::cmpxchg(0, &_Event, v) == v) return v;
- }
-}
-
void os::PlatformEvent::park() { // AKA: down()
// Invariant: Only the thread associated with the Event/PlatformEvent
// may call park().
+ assert(_nParked == 0, "invariant");
+
int v;
for (;;) {
v = _Event;
@@ -5539,8 +5523,7 @@
// 1 :=> 1
// -1 :=> either 0 or 1; must signal target thread
// That is, we can safely transition _Event from -1 to either
- // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
- // unpark() calls.
+ // 0 or 1.
// See also: "Semaphores in Plan 9" by Mullender & Cox
//
// Note: Forcing a transition from "-1" to "1" on an unpark() means
@@ -5744,10 +5727,9 @@
}
void Parker::unpark() {
- int s, status;
- status = os::Solaris::mutex_lock(_mutex);
+ int status = os::Solaris::mutex_lock(_mutex);
assert(status == 0, "invariant");
- s = _counter;
+ const int s = _counter;
_counter = 1;
status = os::Solaris::mutex_unlock(_mutex);
assert(status == 0, "invariant");
--- a/hotspot/src/os/solaris/vm/os_solaris.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -332,7 +332,6 @@
int fired() { return _Event; }
void park();
int park(jlong millis);
- int TryPark();
void unpark();
};
--- a/hotspot/src/os/solaris/vm/os_solaris.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,8 +25,6 @@
#ifndef OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
#define OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
-#include "runtime/atomic.inline.hpp"
-#include "runtime/orderAccess.inline.hpp"
#include "runtime/os.hpp"
// System includes
@@ -39,10 +37,6 @@
#include <netdb.h>
#include <setjmp.h>
-inline const char* os::file_separator() { return "/"; }
-inline const char* os::line_separator() { return "\n"; }
-inline const char* os::path_separator() { return ":"; }
-
// File names are case-sensitive on windows only
inline int os::file_name_strcmp(const char* s1, const char* s2) {
return strcmp(s1, s2);
--- a/hotspot/src/os/windows/vm/decoder_windows.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/windows/vm/decoder_windows.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
#include "precompiled.hpp"
#include "prims/jvm.h"
#include "runtime/arguments.hpp"
+#include "runtime/os.hpp"
#include "decoder_windows.hpp"
WindowsDecoder::WindowsDecoder() {
--- a/hotspot/src/os/windows/vm/os_windows.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -40,6 +40,7 @@
#include "mutex_windows.inline.hpp"
#include "oops/oop.inline.hpp"
#include "os_share_windows.hpp"
+#include "os_windows.inline.hpp"
#include "prims/jniFastGetField.hpp"
#include "prims/jvm.h"
#include "prims/jvm_misc.hpp"
@@ -1823,7 +1824,9 @@
// looks like jvm.dll is installed there (append a fake suffix
// hotspot/jvm.dll).
char* java_home_var = ::getenv("JAVA_HOME");
- if (java_home_var != NULL && java_home_var[0] != 0) {
+ if (java_home_var != NULL && java_home_var[0] != 0 &&
+ strlen(java_home_var) < (size_t)buflen) {
+
strncpy(buf, java_home_var, buflen);
// determine if this is a legacy image or modules image
@@ -1842,7 +1845,7 @@
if (buf[0] == '\0') {
GetModuleFileName(vm_lib_handle, buf, buflen);
}
- strcpy(saved_jvm_path, buf);
+ strncpy(saved_jvm_path, buf, MAX_PATH);
}
@@ -2290,17 +2293,6 @@
return EXCEPTION_CONTINUE_SEARCH;
}
-// Fatal error reporting is single threaded so we can make this a
-// static and preallocated. If it's more than MAX_PATH silently ignore
-// it.
-static char saved_error_file[MAX_PATH] = {0};
-
-void os::set_error_file(const char *logfile) {
- if (strlen(logfile) <= MAX_PATH) {
- strncpy(saved_error_file, logfile, MAX_PATH);
- }
-}
-
static inline void report_error(Thread* t, DWORD exception_code,
address addr, void* siginfo, void* context) {
VMError err(t, exception_code, addr, siginfo, context);
@@ -3514,18 +3506,15 @@
typedef BOOL (WINAPI * STTSignature)(void);
-os::YieldResult os::NakedYield() {
+void os::naked_yield() {
// Use either SwitchToThread() or Sleep(0)
// Consider passing back the return value from SwitchToThread().
if (os::Kernel32Dll::SwitchToThreadAvailable()) {
- return SwitchToThread() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY;
+ SwitchToThread();
} else {
Sleep(0);
}
- return os::YIELD_UNKNOWN;
-}
-
-void os::yield() { os::NakedYield(); }
+}
// Win32 only gives you access to seven real priorities at a time,
// so we compress Java's ten down to seven. It would be better
@@ -4875,8 +4864,7 @@
// 1 :=> 1
// -1 :=> either 0 or 1; must signal target thread
// That is, we can safely transition _Event from -1 to either
- // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
- // unpark() calls.
+ // 0 or 1.
// See also: "Semaphores in Plan 9" by Mullender & Cox
//
// Note: Forcing a transition from "-1" to "1" on an unpark() means
--- a/hotspot/src/os/windows/vm/os_windows.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,6 +29,11 @@
// Information about the protection of the page at address '0' on this os.
static bool zero_page_read_protected() { return true; }
+// File conventions
+static const char* file_separator() { return "\\"; }
+static const char* line_separator() { return "\r\n"; }
+static const char* path_separator() { return ";"; }
+
class win32 {
friend class os;
--- a/hotspot/src/os/windows/vm/os_windows.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,13 +25,8 @@
#ifndef OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP
#define OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP
-#include "runtime/atomic.inline.hpp"
-#include "runtime/orderAccess.inline.hpp"
#include "runtime/os.hpp"
-inline const char* os::file_separator() { return "\\"; }
-inline const char* os::line_separator() { return "\r\n"; }
-inline const char* os::path_separator() { return ";"; }
inline const char* os::dll_file_extension() { return ".dll"; }
inline const int os::default_file_open_flags() { return O_BINARY | O_NOINHERIT;}
--- a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1997,7 +1997,13 @@
if (!UseInlineCaches && is_loaded && code == Bytecodes::_invokevirtual
&& !target->can_be_statically_bound()) {
// Find a vtable index if one is available
- vtable_index = target->resolve_vtable_index(calling_klass, callee_holder);
+ // For arrays, callee_holder is Object. Resolving the call with
+ // Object would allow an illegal call to finalize() on an
+ // array. We use holder instead: illegal calls to finalize() won't
+ // be compiled as vtable calls (IC call resolution will catch the
+ // illegal call) and the few legal calls on array types won't be
+ // either.
+ vtable_index = target->resolve_vtable_index(calling_klass, holder);
}
#endif
--- a/hotspot/src/share/vm/c1/c1_Runtime1.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_Runtime1.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1050,6 +1050,7 @@
n_copy->set_data((intx) (load_klass()));
} else {
assert(mirror() != NULL, "klass not set");
+ // Don't need a G1 pre-barrier here since we assert above that data isn't an oop.
n_copy->set_data(cast_from_oop<intx>(mirror()));
}
--- a/hotspot/src/share/vm/ci/ciEnv.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciEnv.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -185,6 +185,10 @@
}
}
+ void ensure_metadata_alive(ciMetadata* m) {
+ _factory->ensure_metadata_alive(m);
+ }
+
ciInstance* get_instance(oop o) {
if (o == NULL) return NULL;
return get_object(o)->as_instance();
--- a/hotspot/src/share/vm/ci/ciKlass.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciKlass.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -43,6 +43,7 @@
friend class ciMethod;
friend class ciMethodData;
friend class ciObjArrayKlass;
+ friend class ciReceiverTypeData;
private:
ciSymbol* _name;
--- a/hotspot/src/share/vm/ci/ciMethodData.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciMethodData.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -170,6 +170,7 @@
Klass* k = data->as_ReceiverTypeData()->receiver(row);
if (k != NULL) {
ciKlass* klass = CURRENT_ENV->get_klass(k);
+ CURRENT_ENV->ensure_metadata_alive(klass);
set_receiver(row, klass);
}
}
@@ -191,6 +192,7 @@
void ciSpeculativeTrapData::translate_from(const ProfileData* data) {
Method* m = data->as_SpeculativeTrapData()->method();
ciMethod* ci_m = CURRENT_ENV->get_method(m);
+ CURRENT_ENV->ensure_metadata_alive(ci_m);
set_method(ci_m);
}
--- a/hotspot/src/share/vm/ci/ciMethodData.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciMethodData.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -70,6 +70,7 @@
Klass* v = TypeEntries::valid_klass(k);
if (v != NULL) {
ciKlass* klass = CURRENT_ENV->get_klass(v);
+ CURRENT_ENV->ensure_metadata_alive(klass);
return with_status(klass, k);
}
return with_status(NULL, k);
--- a/hotspot/src/share/vm/ci/ciObjectFactory.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciObjectFactory.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -46,6 +46,9 @@
#include "oops/oop.inline.hpp"
#include "oops/oop.inline2.hpp"
#include "runtime/fieldType.hpp"
+#if INCLUDE_ALL_GCS
+# include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
+#endif
// ciObjectFactory
//
@@ -374,6 +377,37 @@
return NULL;
}
+// ------------------------------------------------------------------
+// ciObjectFactory::ensure_metadata_alive
+//
+// Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
+// This is primarily useful for metadata which is considered as weak roots
+// by the GC but need to be strong roots if reachable from a current compilation.
+//
+void ciObjectFactory::ensure_metadata_alive(ciMetadata* m) {
+ ASSERT_IN_VM; // We're handling raw oops here.
+
+#if INCLUDE_ALL_GCS
+ if (!UseG1GC) {
+ return;
+ }
+ Klass* metadata_owner_klass;
+ if (m->is_klass()) {
+ metadata_owner_klass = m->as_klass()->get_Klass();
+ } else if (m->is_method()) {
+ metadata_owner_klass = m->as_method()->get_Method()->constants()->pool_holder();
+ } else {
+ fatal("Not implemented for other types of metadata");
+ }
+
+ oop metadata_holder = metadata_owner_klass->klass_holder();
+ if (metadata_holder != NULL) {
+ G1SATBCardTableModRefBS::enqueue(metadata_holder);
+ }
+
+#endif
+}
+
//------------------------------------------------------------------
// ciObjectFactory::get_unloaded_method
//
--- a/hotspot/src/share/vm/ci/ciObjectFactory.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciObjectFactory.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -75,6 +75,8 @@
ciObject* create_new_object(oop o);
ciMetadata* create_new_object(Metadata* o);
+ void ensure_metadata_alive(ciMetadata* m);
+
static bool is_equal(NonPermObject* p, oop key) {
return p->object()->get_oop() == key;
}
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -919,7 +919,7 @@
"Wrong size %u for field's Signature attribute in class file %s",
attribute_length, CHECK);
}
- generic_signature_index = cfs->get_u2(CHECK);
+ generic_signature_index = parse_generic_signature_attribute(CHECK);
} else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
if (runtime_visible_annotations != NULL) {
classfile_parse_error(
@@ -2306,8 +2306,7 @@
"Invalid Signature attribute length %u in class file %s",
method_attribute_length, CHECK_(nullHandle));
}
- cfs->guarantee_more(2, CHECK_(nullHandle)); // generic_signature_index
- generic_signature_index = cfs->get_u2_fast();
+ generic_signature_index = parse_generic_signature_attribute(CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
if (runtime_visible_annotations != NULL) {
classfile_parse_error(
@@ -2644,6 +2643,17 @@
return method_ordering;
}
+// Parse generic_signature attribute for methods and fields
+u2 ClassFileParser::parse_generic_signature_attribute(TRAPS) {
+ ClassFileStream* cfs = stream();
+ cfs->guarantee_more(2, CHECK_0); // generic_signature_index
+ u2 generic_signature_index = cfs->get_u2_fast();
+ check_property(
+ valid_symbol_at(generic_signature_index),
+ "Invalid Signature attribute at constant pool index %u in class file %s",
+ generic_signature_index, CHECK_0);
+ return generic_signature_index;
+}
void ClassFileParser::parse_classfile_sourcefile_attribute(TRAPS) {
ClassFileStream* cfs = stream();
@@ -2798,17 +2808,19 @@
ClassFileStream* cfs = stream();
u1* current_start = cfs->current();
- cfs->guarantee_more(2, CHECK); // length
+ guarantee_property(attribute_byte_length >= sizeof(u2),
+ "Invalid BootstrapMethods attribute length %u in class file %s",
+ attribute_byte_length,
+ CHECK);
+
+ cfs->guarantee_more(attribute_byte_length, CHECK);
+
int attribute_array_length = cfs->get_u2_fast();
guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
"Short length on BootstrapMethods in class file %s",
CHECK);
- guarantee_property(attribute_byte_length >= sizeof(u2),
- "Invalid BootstrapMethods attribute length %u in class file %s",
- attribute_byte_length,
- CHECK);
// The attribute contains a counted array of counted tuples of shorts,
// represending bootstrap specifiers:
@@ -4590,8 +4602,9 @@
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_VerifyError(),
- "class %s overrides final method %s.%s",
+ "class %s overrides final method %s.%s%s",
this_klass->external_name(),
+ super_m->method_holder()->external_name(),
name->as_C_string(),
signature->as_C_string()
);
--- a/hotspot/src/share/vm/classfile/classFileParser.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classFileParser.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -266,6 +266,7 @@
u1* parse_stackmap_table(u4 code_attribute_length, TRAPS);
// Classfile attribute parsing
+ u2 parse_generic_signature_attribute(TRAPS);
void parse_classfile_sourcefile_attribute(TRAPS);
void parse_classfile_source_debug_extension_attribute(int length, TRAPS);
u2 parse_classfile_inner_classes_attribute(u1* inner_classes_attribute_start,
--- a/hotspot/src/share/vm/classfile/classLoader.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classLoader.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -52,6 +52,7 @@
#include "runtime/interfaceSupport.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
+#include "runtime/os.hpp"
#include "runtime/threadCritical.hpp"
#include "runtime/timer.hpp"
#include "services/management.hpp"
@@ -59,22 +60,6 @@
#include "utilities/events.hpp"
#include "utilities/hashtable.hpp"
#include "utilities/hashtable.inline.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
-
// Entry points in zip.dll for loading zip/jar file entries
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -332,6 +332,27 @@
}
}
+#ifdef ASSERT
+class AllAliveClosure : public OopClosure {
+ BoolObjectClosure* _is_alive_closure;
+ bool _found_dead;
+ public:
+ AllAliveClosure(BoolObjectClosure* is_alive_closure) : _is_alive_closure(is_alive_closure), _found_dead(false) {}
+ template <typename T> void do_oop_work(T* p) {
+ T heap_oop = oopDesc::load_heap_oop(p);
+ if (!oopDesc::is_null(heap_oop)) {
+ oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
+ if (!_is_alive_closure->do_object_b(obj)) {
+ _found_dead = true;
+ }
+ }
+ }
+ void do_oop(oop* p) { do_oop_work<oop>(p); }
+ void do_oop(narrowOop* p) { do_oop_work<narrowOop>(p); }
+ bool found_dead() { return _found_dead; }
+};
+#endif
+
oop ClassLoaderData::keep_alive_object() const {
assert(!keep_alive(), "Don't use with CLDs that are artificially kept alive");
return is_anonymous() ? _klasses->java_mirror() : class_loader();
@@ -341,7 +362,15 @@
bool alive = keep_alive() // null class loader and incomplete anonymous klasses.
|| is_alive_closure->do_object_b(keep_alive_object());
- assert(!alive || claimed(), "must be claimed");
+#ifdef ASSERT
+ if (alive) {
+ AllAliveClosure all_alive_closure(is_alive_closure);
+ KlassToOopClosure klass_closure(&all_alive_closure);
+ const_cast<ClassLoaderData*>(this)->oops_do(&all_alive_closure, &klass_closure, false);
+ assert(!all_alive_closure.found_dead(), err_msg("Found dead oop in alive cld: " PTR_FORMAT, p2i(this)));
+ }
+#endif
+
return alive;
}
@@ -620,9 +649,9 @@
void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
if (ClassUnloading) {
- ClassLoaderDataGraph::keep_alive_oops_do(f, klass_closure, must_claim);
+ keep_alive_oops_do(f, klass_closure, must_claim);
} else {
- ClassLoaderDataGraph::oops_do(f, klass_closure, must_claim);
+ oops_do(f, klass_closure, must_claim);
}
}
@@ -632,6 +661,27 @@
}
}
+void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
+ for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->_next) {
+ CLDClosure* closure = cld->keep_alive() ? strong : weak;
+ if (closure != NULL) {
+ closure->do_cld(cld);
+ }
+ }
+}
+
+void ClassLoaderDataGraph::keep_alive_cld_do(CLDClosure* cl) {
+ roots_cld_do(cl, NULL);
+}
+
+void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
+ if (ClassUnloading) {
+ keep_alive_cld_do(cl);
+ } else {
+ cld_do(cl);
+ }
+}
+
void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
cld->classes_do(klass_closure);
@@ -689,6 +739,16 @@
return array;
}
+bool ClassLoaderDataGraph::unload_list_contains(const void* x) {
+ assert(SafepointSynchronize::is_at_safepoint(), "only safe to call at safepoint");
+ for (ClassLoaderData* cld = _unloading; cld != NULL; cld = cld->next()) {
+ if (cld->metaspace_or_null() != NULL && cld->metaspace_or_null()->contains(x)) {
+ return true;
+ }
+ }
+ return false;
+}
+
#ifndef PRODUCT
bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
@@ -809,6 +869,60 @@
return _rw_metaspace;
}
+ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
+ : _next_klass(NULL) {
+ ClassLoaderData* cld = ClassLoaderDataGraph::_head;
+ Klass* klass = NULL;
+
+ // Find the first klass in the CLDG.
+ while (cld != NULL) {
+ klass = cld->_klasses;
+ if (klass != NULL) {
+ _next_klass = klass;
+ return;
+ }
+ cld = cld->next();
+ }
+}
+
+Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
+ Klass* next = klass->next_link();
+ if (next != NULL) {
+ return next;
+ }
+
+ // No more klasses in the current CLD. Time to find a new CLD.
+ ClassLoaderData* cld = klass->class_loader_data();
+ while (next == NULL) {
+ cld = cld->next();
+ if (cld == NULL) {
+ break;
+ }
+ next = cld->_klasses;
+ }
+
+ return next;
+}
+
+Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
+ Klass* head = (Klass*)_next_klass;
+
+ while (head != NULL) {
+ Klass* next = next_klass_in_cldg(head);
+
+ Klass* old_head = (Klass*)Atomic::cmpxchg_ptr(next, &_next_klass, head);
+
+ if (old_head == head) {
+ return head; // Won the CAS.
+ }
+
+ head = old_head;
+ }
+
+ // Nothing more for the iterator to hand out.
+ assert(head == NULL, err_msg("head is " PTR_FORMAT ", expected not null:", p2i(head)));
+ return NULL;
+}
ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
_data = ClassLoaderDataGraph::_head;
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -31,7 +31,6 @@
#include "memory/metaspaceCounters.hpp"
#include "runtime/mutex.hpp"
#include "utilities/growableArray.hpp"
-
#if INCLUDE_TRACE
# include "utilities/ticks.hpp"
#endif
@@ -59,6 +58,7 @@
class ClassLoaderDataGraph : public AllStatic {
friend class ClassLoaderData;
friend class ClassLoaderDataGraphMetaspaceIterator;
+ friend class ClassLoaderDataGraphKlassIteratorAtomic;
friend class VMStructs;
private:
// All CLDs (except the null CLD) can be reached by walking _head->_next->...
@@ -75,10 +75,16 @@
static ClassLoaderData* find_or_create(Handle class_loader, TRAPS);
static void purge();
static void clear_claimed_marks();
+ // oops do
static void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
+ static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
static void always_strong_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
- static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
+ // cld do
static void cld_do(CLDClosure* cl);
+ static void roots_cld_do(CLDClosure* strong, CLDClosure* weak);
+ static void keep_alive_cld_do(CLDClosure* cl);
+ static void always_strong_cld_do(CLDClosure* cl);
+ // klass do
static void classes_do(KlassClosure* klass_closure);
static void classes_do(void f(Klass* const));
static void methods_do(void f(Method*));
@@ -104,6 +110,7 @@
static void dump() { dump_on(tty); }
static void verify();
+ static bool unload_list_contains(const void* x);
#ifndef PRODUCT
static bool contains_loader_data(ClassLoaderData* loader_data);
#endif
@@ -136,6 +143,7 @@
};
friend class ClassLoaderDataGraph;
+ friend class ClassLoaderDataGraphKlassIteratorAtomic;
friend class ClassLoaderDataGraphMetaspaceIterator;
friend class MetaDataFactory;
friend class Method;
@@ -195,7 +203,6 @@
void unload();
bool keep_alive() const { return _keep_alive; }
- bool is_alive(BoolObjectClosure* is_alive_closure) const;
void classes_do(void f(Klass*));
void loaded_classes_do(KlassClosure* klass_closure);
void classes_do(void f(InstanceKlass*));
@@ -208,6 +215,9 @@
MetaWord* allocate(size_t size);
public:
+
+ bool is_alive(BoolObjectClosure* is_alive_closure) const;
+
// Accessors
Metaspace* metaspace_or_null() const { return _metaspace; }
@@ -293,6 +303,16 @@
void initialize_shared_metaspaces();
};
+// An iterator that distributes Klasses to parallel worker threads.
+class ClassLoaderDataGraphKlassIteratorAtomic : public StackObj {
+ volatile Klass* _next_klass;
+ public:
+ ClassLoaderDataGraphKlassIteratorAtomic();
+ Klass* next_klass();
+ private:
+ static Klass* next_klass_in_cldg(Klass* klass);
+};
+
class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
ClassLoaderData* _data;
public:
--- a/hotspot/src/share/vm/classfile/dictionary.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/dictionary.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -199,6 +199,26 @@
return class_was_unloaded;
}
+void Dictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
+ // Skip the strong roots probe marking if the closures are the same.
+ if (strong == weak) {
+ oops_do(strong);
+ return;
+ }
+
+ for (int index = 0; index < table_size(); index++) {
+ for (DictionaryEntry *probe = bucket(index);
+ probe != NULL;
+ probe = probe->next()) {
+ Klass* e = probe->klass();
+ ClassLoaderData* loader_data = probe->loader_data();
+ if (is_strongly_reachable(loader_data, e)) {
+ probe->set_strongly_reachable();
+ }
+ }
+ }
+ _pd_cache_table->roots_oops_do(strong, weak);
+}
void Dictionary::always_strong_oops_do(OopClosure* blk) {
// Follow all system classes and temporary placeholders in dictionary; only
@@ -490,6 +510,23 @@
}
}
+void ProtectionDomainCacheTable::roots_oops_do(OopClosure* strong, OopClosure* weak) {
+ for (int index = 0; index < table_size(); index++) {
+ for (ProtectionDomainCacheEntry* probe = bucket(index);
+ probe != NULL;
+ probe = probe->next()) {
+ if (probe->is_strongly_reachable()) {
+ probe->reset_strongly_reachable();
+ probe->oops_do(strong);
+ } else {
+ if (weak != NULL) {
+ probe->oops_do(weak);
+ }
+ }
+ }
+ }
+}
+
uint ProtectionDomainCacheTable::bucket_size() {
return sizeof(ProtectionDomainCacheEntry);
}
--- a/hotspot/src/share/vm/classfile/dictionary.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/dictionary.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -89,6 +89,7 @@
// GC support
void oops_do(OopClosure* f);
void always_strong_oops_do(OopClosure* blk);
+ void roots_oops_do(OopClosure* strong, OopClosure* weak);
void always_strong_classes_do(KlassClosure* closure);
@@ -218,6 +219,7 @@
// GC support
void oops_do(OopClosure* f);
void always_strong_oops_do(OopClosure* f);
+ void roots_oops_do(OopClosure* strong, OopClosure* weak);
static uint bucket_size();
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -618,6 +618,8 @@
assert(comp_mirror.not_null(), "must have a mirror");
// Two-way link between the array klass and its component mirror:
+ // (array_klass) k -> mirror -> component_mirror -> array_klass -> k
+ set_component_mirror(mirror(), comp_mirror());
ArrayKlass::cast(k())->set_component_mirror(comp_mirror());
set_array_klass(comp_mirror(), k());
} else {
@@ -679,6 +681,16 @@
java_class->obj_field_put(_protection_domain_offset, pd);
}
+void java_lang_Class::set_component_mirror(oop java_class, oop comp_mirror) {
+ if (_component_mirror_offset != 0) {
+ java_class->obj_field_put(_component_mirror_offset, comp_mirror);
+ }
+}
+oop java_lang_Class::component_mirror(oop java_class) {
+ assert(_component_mirror_offset != 0, "must be set");
+ return java_class->obj_field(_component_mirror_offset);
+}
+
oop java_lang_Class::init_lock(oop java_class) {
assert(_init_lock_offset != 0, "must be set");
return java_class->obj_field(_init_lock_offset);
@@ -875,6 +887,10 @@
klass_oop, vmSymbols::classLoader_name(),
vmSymbols::classloader_signature());
+ compute_optional_offset(_component_mirror_offset,
+ klass_oop, vmSymbols::componentType_name(),
+ vmSymbols::class_signature());
+
CLASS_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
}
@@ -3097,6 +3113,7 @@
int java_lang_Class::_static_oop_field_count_offset;
int java_lang_Class::_class_loader_offset;
int java_lang_Class::_protection_domain_offset;
+int java_lang_Class::_component_mirror_offset;
int java_lang_Class::_init_lock_offset;
int java_lang_Class::_signers_offset;
GrowableArray<Klass*>* java_lang_Class::_fixup_mirror_list = NULL;
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -241,6 +241,7 @@
static int _init_lock_offset;
static int _signers_offset;
static int _class_loader_offset;
+ static int _component_mirror_offset;
static bool offsets_computed;
static int classRedefinedCount_offset;
@@ -250,6 +251,7 @@
static void set_init_lock(oop java_class, oop init_lock);
static void set_protection_domain(oop java_class, oop protection_domain);
static void set_class_loader(oop java_class, oop class_loader);
+ static void set_component_mirror(oop java_class, oop comp_mirror);
static void initialize_mirror_fields(KlassHandle k, Handle mirror, Handle protection_domain, TRAPS);
public:
static void compute_offsets();
@@ -291,6 +293,7 @@
// Support for embedded per-class oops
static oop protection_domain(oop java_class);
static oop init_lock(oop java_class);
+ static oop component_mirror(oop java_class);
static objArrayOop signers(oop java_class);
static void set_signers(oop java_class, objArrayOop signers);
--- a/hotspot/src/share/vm/classfile/metadataOnStackMark.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/metadataOnStackMark.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -47,8 +47,11 @@
if (_marked_objects == NULL) {
_marked_objects = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(1000, true);
}
+
Threads::metadata_do(Metadata::mark_on_stack);
- CodeCache::alive_nmethods_do(nmethod::mark_on_stack);
+ if (JvmtiExport::has_redefined_a_class()) {
+ CodeCache::alive_nmethods_do(nmethod::mark_on_stack);
+ }
CompileBroker::mark_on_stack();
JvmtiCurrentBreakpoints::metadata_do(Metadata::mark_on_stack);
ThreadService::metadata_do(Metadata::mark_on_stack);
--- a/hotspot/src/share/vm/classfile/stackMapTable.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/stackMapTable.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -134,6 +134,7 @@
}
// check if uninitialized objects exist on backward branches
check_new_object(frame, target, CHECK_VERIFY(frame->verifier()));
+ frame->verifier()->update_furthest_jump(target);
}
void StackMapTable::check_new_object(
--- a/hotspot/src/share/vm/classfile/stringTable.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/stringTable.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -37,6 +37,7 @@
#include "runtime/mutexLocker.hpp"
#include "utilities/hashtable.inline.hpp"
#if INCLUDE_ALL_GCS
+#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
#include "gc_implementation/g1/g1StringDedup.hpp"
#endif
@@ -157,11 +158,26 @@
return lookup(chars, length);
}
+// Tell the GC that this string was looked up in the StringTable.
+static void ensure_string_alive(oop string) {
+ // A lookup in the StringTable could return an object that was previously
+ // considered dead. The SATB part of G1 needs to get notified about this
+ // potential resurrection, otherwise the marking might not find the object.
+#if INCLUDE_ALL_GCS
+ if (UseG1GC && string != NULL) {
+ G1SATBCardTableModRefBS::enqueue(string);
+ }
+#endif
+}
oop StringTable::lookup(jchar* name, int len) {
unsigned int hash = hash_string(name, len);
int index = the_table()->hash_to_index(hash);
- return the_table()->lookup(index, name, len, hash);
+ oop string = the_table()->lookup(index, name, len, hash);
+
+ ensure_string_alive(string);
+
+ return string;
}
@@ -172,7 +188,10 @@
oop found_string = the_table()->lookup(index, name, len, hashValue);
// Found
- if (found_string != NULL) return found_string;
+ if (found_string != NULL) {
+ ensure_string_alive(found_string);
+ return found_string;
+ }
debug_only(StableMemoryChecker smc(name, len * sizeof(name[0])));
assert(!Universe::heap()->is_in_reserved(name),
@@ -197,11 +216,17 @@
// Grab the StringTable_lock before getting the_table() because it could
// change at safepoint.
- MutexLocker ml(StringTable_lock, THREAD);
+ oop added_or_found;
+ {
+ MutexLocker ml(StringTable_lock, THREAD);
+ // Otherwise, add to symbol to table
+ added_or_found = the_table()->basic_add(index, string, name, len,
+ hashValue, CHECK_NULL);
+ }
- // Otherwise, add to symbol to table
- return the_table()->basic_add(index, string, name, len,
- hashValue, CHECK_NULL);
+ ensure_string_alive(added_or_found);
+
+ return added_or_found;
}
oop StringTable::intern(Symbol* symbol, TRAPS) {
--- a/hotspot/src/share/vm/classfile/systemDictionary.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1612,13 +1612,7 @@
// system dictionary and follows the remaining classes' contents.
void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
- blk->do_oop(&_java_system_loader);
- blk->do_oop(&_system_loader_lock_obj);
-
- dictionary()->always_strong_oops_do(blk);
-
- // Visit extra methods
- invoke_method_table()->oops_do(blk);
+ roots_oops_do(blk, NULL);
}
void SystemDictionary::always_strong_classes_do(KlassClosure* closure) {
@@ -1685,6 +1679,17 @@
return unloading_occurred;
}
+void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
+ strong->do_oop(&_java_system_loader);
+ strong->do_oop(&_system_loader_lock_obj);
+
+ // Adjust dictionary
+ dictionary()->roots_oops_do(strong, weak);
+
+ // Visit extra methods
+ invoke_method_table()->oops_do(strong);
+}
+
void SystemDictionary::oops_do(OopClosure* f) {
f->do_oop(&_java_system_loader);
f->do_oop(&_system_loader_lock_obj);
--- a/hotspot/src/share/vm/classfile/systemDictionary.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/systemDictionary.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -330,6 +330,7 @@
// Applies "f->do_oop" to all root oops in the system dictionary.
static void oops_do(OopClosure* f);
+ static void roots_oops_do(OopClosure* strong, OopClosure* weak);
// System loader lock
static oop system_loader_lock() { return _system_loader_lock_obj; }
--- a/hotspot/src/share/vm/classfile/verifier.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/verifier.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -633,6 +633,9 @@
bool no_control_flow = false; // Set to true when there is no direct control
// flow from current instruction to the next
// instruction in sequence
+
+ set_furthest_jump(0);
+
Bytecodes::Code opcode;
while (!bcs.is_last_bytecode()) {
// Check for recursive re-verification before each bytecode.
@@ -2248,6 +2251,29 @@
"Bad <init> method call");
return;
}
+
+ // Make sure that this call is not jumped over.
+ if (bci < furthest_jump()) {
+ verify_error(ErrorContext::bad_code(bci),
+ "Bad <init> method call from inside of a branch");
+ return;
+ }
+
+ // Make sure that this call is not done from within a TRY block because
+ // that can result in returning an incomplete object. Simply checking
+ // (bci >= start_pc) also ensures that this call is not done after a TRY
+ // block. That is also illegal because this call must be the first Java
+ // statement in the constructor.
+ ExceptionTable exhandlers(_method());
+ int exlength = exhandlers.length();
+ for(int i = 0; i < exlength; i++) {
+ if (bci >= exhandlers.start_pc(i)) {
+ verify_error(ErrorContext::bad_code(bci),
+ "Bad <init> method call from after the start of a try block");
+ return;
+ }
+ }
+
current_frame->initialize_object(type, current_type());
*this_uninit = true;
} else if (type.is_uninitialized()) {
@@ -2285,16 +2311,19 @@
vmSymbols::object_initializer_name(),
cp->signature_ref_at(bcs->get_index_u2()),
Klass::normal);
- instanceKlassHandle mh(THREAD, m->method_holder());
- if (m->is_protected() && !mh->is_same_class_package(_klass())) {
- bool assignable = current_type().is_assignable_from(
- objectref_type, this, CHECK_VERIFY(this));
- if (!assignable) {
- verify_error(ErrorContext::bad_type(bci,
- TypeOrigin::cp(new_class_index, objectref_type),
- TypeOrigin::implicit(current_type())),
- "Bad access to protected <init> method");
- return;
+ // Do nothing if method is not found. Let resolution detect the error.
+ if (m != NULL) {
+ instanceKlassHandle mh(THREAD, m->method_holder());
+ if (m->is_protected() && !mh->is_same_class_package(_klass())) {
+ bool assignable = current_type().is_assignable_from(
+ objectref_type, this, CHECK_VERIFY(this));
+ if (!assignable) {
+ verify_error(ErrorContext::bad_type(bci,
+ TypeOrigin::cp(new_class_index, objectref_type),
+ TypeOrigin::implicit(current_type())),
+ "Bad access to protected <init> method");
+ return;
+ }
}
}
}
--- a/hotspot/src/share/vm/classfile/verifier.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/verifier.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -258,6 +258,9 @@
ErrorContext _error_context; // contains information about an error
+ // Used to detect illegal jumps over calls to super() nd this() in ctors.
+ int32_t _furthest_jump;
+
void verify_method(methodHandle method, TRAPS);
char* generate_code_data(methodHandle m, u4 code_length, TRAPS);
void verify_exception_handler_table(u4 code_length, char* code_data,
@@ -403,6 +406,20 @@
Symbol* create_temporary_symbol(const char *s, int length, TRAPS);
TypeOrigin ref_ctx(const char* str, TRAPS);
+
+ // Keep track of the furthest branch done in a method to make sure that
+ // there are no branches over calls to super() or this() from inside of
+ // a constructor.
+ int32_t furthest_jump() { return _furthest_jump; }
+
+ void set_furthest_jump(int32_t target) {
+ _furthest_jump = target;
+ }
+
+ void update_furthest_jump(int32_t target) {
+ if (target > _furthest_jump) _furthest_jump = target;
+ }
+
};
inline int ClassVerifier::change_sig_to_verificationType(
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -573,6 +573,7 @@
template(serializeAgentPropertiesToByteArray_name, "serializeAgentPropertiesToByteArray") \
template(classRedefinedCount_name, "classRedefinedCount") \
template(classLoader_name, "classLoader") \
+ template(componentType_name, "componentType") \
\
/* trace signatures */ \
TRACE_TEMPLATES(template) \
--- a/hotspot/src/share/vm/code/codeCache.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/codeCache.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -331,6 +331,11 @@
// Walk the list of methods which might contain non-perm oops.
void CodeCache::scavenge_root_nmethods_do(CodeBlobClosure* f) {
assert_locked_or_safepoint(CodeCache_lock);
+
+ if (UseG1GC) {
+ return;
+ }
+
debug_only(mark_scavenge_root_nmethods());
for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
@@ -356,6 +361,11 @@
void CodeCache::add_scavenge_root_nmethod(nmethod* nm) {
assert_locked_or_safepoint(CodeCache_lock);
+
+ if (UseG1GC) {
+ return;
+ }
+
nm->set_on_scavenge_root_list();
nm->set_scavenge_root_link(_scavenge_root_nmethods);
set_scavenge_root_nmethods(nm);
@@ -364,6 +374,11 @@
void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) {
assert_locked_or_safepoint(CodeCache_lock);
+
+ if (UseG1GC) {
+ return;
+ }
+
print_trace("drop_scavenge_root", nm);
nmethod* last = NULL;
nmethod* cur = scavenge_root_nmethods();
@@ -385,6 +400,11 @@
void CodeCache::prune_scavenge_root_nmethods() {
assert_locked_or_safepoint(CodeCache_lock);
+
+ if (UseG1GC) {
+ return;
+ }
+
debug_only(mark_scavenge_root_nmethods());
nmethod* last = NULL;
@@ -417,6 +437,10 @@
#ifndef PRODUCT
void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) {
+ if (UseG1GC) {
+ return;
+ }
+
// While we are here, verify the integrity of the list.
mark_scavenge_root_nmethods();
for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
@@ -457,9 +481,36 @@
}
#endif //PRODUCT
+void CodeCache::verify_clean_inline_caches() {
+#ifdef ASSERT
+ FOR_ALL_ALIVE_BLOBS(cb) {
+ if (cb->is_nmethod()) {
+ nmethod* nm = (nmethod*)cb;
+ assert(!nm->is_unloaded(), "Tautology");
+ nm->verify_clean_inline_caches();
+ nm->verify();
+ }
+ }
+#endif
+}
+
+void CodeCache::verify_icholder_relocations() {
+#ifdef ASSERT
+ // make sure that we aren't leaking icholders
+ int count = 0;
+ FOR_ALL_BLOBS(cb) {
+ if (cb->is_nmethod()) {
+ nmethod* nm = (nmethod*)cb;
+ count += nm->verify_icholder_relocations();
+ }
+ }
+
+ assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
+ CompiledICHolder::live_count(), "must agree");
+#endif
+}
void CodeCache::gc_prologue() {
- assert(!nmethod::oops_do_marking_is_active(), "oops_do_marking_epilogue must be called");
}
void CodeCache::gc_epilogue() {
@@ -472,41 +523,15 @@
nm->cleanup_inline_caches();
}
DEBUG_ONLY(nm->verify());
- nm->fix_oop_relocations();
+ DEBUG_ONLY(nm->verify_oop_relocations());
}
}
set_needs_cache_clean(false);
prune_scavenge_root_nmethods();
- assert(!nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
-#ifdef ASSERT
- // make sure that we aren't leaking icholders
- int count = 0;
- FOR_ALL_BLOBS(cb) {
- if (cb->is_nmethod()) {
- RelocIterator iter((nmethod*)cb);
- while(iter.next()) {
- if (iter.type() == relocInfo::virtual_call_type) {
- if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
- CompiledIC *ic = CompiledIC_at(iter.reloc());
- if (TraceCompiledIC) {
- tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
- ic->print();
- }
- assert(ic->cached_icholder() != NULL, "must be non-NULL");
- count++;
- }
- }
- }
- }
- }
-
- assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
- CompiledICHolder::live_count(), "must agree");
-#endif
+ verify_icholder_relocations();
}
-
void CodeCache::verify_oops() {
MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
VerifyOopClosure voc;
--- a/hotspot/src/share/vm/code/codeCache.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/codeCache.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -134,10 +134,6 @@
// to) any unmarked codeBlobs in the cache. Sets "marked_for_unloading"
// to "true" iff some code got unloaded.
static void do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred);
- static void oops_do(OopClosure* f) {
- CodeBlobToOopClosure oopc(f, /*do_marking=*/ false);
- blobs_do(&oopc);
- }
static void asserted_non_scavengable_nmethods_do(CodeBlobClosure* f = NULL) PRODUCT_RETURN;
static void scavenge_root_nmethods_do(CodeBlobClosure* f);
@@ -173,6 +169,9 @@
static void set_needs_cache_clean(bool v) { _needs_cache_clean = v; }
static void clear_inline_caches(); // clear all inline caches
+ static void verify_clean_inline_caches();
+ static void verify_icholder_relocations();
+
// Deoptimization
static int mark_for_deoptimization(DepChange& changes);
#ifdef HOTSWAP
--- a/hotspot/src/share/vm/code/compiledIC.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/compiledIC.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -99,13 +99,13 @@
}
{
- MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
+ MutexLockerEx pl(SafepointSynchronize::is_at_safepoint() ? NULL : Patching_lock, Mutex::_no_safepoint_check_flag);
#ifdef ASSERT
- CodeBlob* cb = CodeCache::find_blob_unsafe(_ic_call);
- assert(cb != NULL && cb->is_nmethod(), "must be nmethod");
+ CodeBlob* cb = CodeCache::find_blob_unsafe(_ic_call);
+ assert(cb != NULL && cb->is_nmethod(), "must be nmethod");
#endif
- _ic_call->set_destination_mt_safe(entry_point);
-}
+ _ic_call->set_destination_mt_safe(entry_point);
+ }
if (is_optimized() || is_icstub) {
// Optimized call sites don't have a cache value and ICStub call
@@ -159,10 +159,24 @@
//-----------------------------------------------------------------------------
// High-level access to an inline cache. Guaranteed to be MT-safe.
+void CompiledIC::initialize_from_iter(RelocIterator* iter) {
+ assert(iter->addr() == _ic_call->instruction_address(), "must find ic_call");
+
+ if (iter->type() == relocInfo::virtual_call_type) {
+ virtual_call_Relocation* r = iter->virtual_call_reloc();
+ _is_optimized = false;
+ _value = nativeMovConstReg_at(r->cached_value());
+ } else {
+ assert(iter->type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
+ _is_optimized = true;
+ _value = NULL;
+ }
+}
+
CompiledIC::CompiledIC(nmethod* nm, NativeCall* call)
: _ic_call(call)
{
- address ic_call = call->instruction_address();
+ address ic_call = _ic_call->instruction_address();
assert(ic_call != NULL, "ic_call address must be set");
assert(nm != NULL, "must pass nmethod");
@@ -173,15 +187,21 @@
bool ret = iter.next();
assert(ret == true, "relocInfo must exist at this address");
assert(iter.addr() == ic_call, "must find ic_call");
- if (iter.type() == relocInfo::virtual_call_type) {
- virtual_call_Relocation* r = iter.virtual_call_reloc();
- _is_optimized = false;
- _value = nativeMovConstReg_at(r->cached_value());
- } else {
- assert(iter.type() == relocInfo::opt_virtual_call_type, "must be a virtual call");
- _is_optimized = true;
- _value = NULL;
- }
+
+ initialize_from_iter(&iter);
+}
+
+CompiledIC::CompiledIC(RelocIterator* iter)
+ : _ic_call(nativeCall_at(iter->addr()))
+{
+ address ic_call = _ic_call->instruction_address();
+
+ nmethod* nm = iter->code();
+ assert(ic_call != NULL, "ic_call address must be set");
+ assert(nm != NULL, "must pass nmethod");
+ assert(nm->contains(ic_call), "must be in nmethod");
+
+ initialize_from_iter(iter);
}
bool CompiledIC::set_to_megamorphic(CallInfo* call_info, Bytecodes::Code bytecode, TRAPS) {
@@ -509,7 +529,7 @@
void CompiledStaticCall::set_to_clean() {
assert (CompiledIC_lock->is_locked() || SafepointSynchronize::is_at_safepoint(), "mt unsafe call");
// Reset call site
- MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
+ MutexLockerEx pl(SafepointSynchronize::is_at_safepoint() ? NULL : Patching_lock, Mutex::_no_safepoint_check_flag);
#ifdef ASSERT
CodeBlob* cb = CodeCache::find_blob_unsafe(this);
assert(cb != NULL && cb->is_nmethod(), "must be nmethod");
--- a/hotspot/src/share/vm/code/compiledIC.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/compiledIC.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -150,6 +150,9 @@
bool _is_optimized; // an optimized virtual call (i.e., no compiled IC)
CompiledIC(nmethod* nm, NativeCall* ic_call);
+ CompiledIC(RelocIterator* iter);
+
+ void initialize_from_iter(RelocIterator* iter);
static bool is_icholder_entry(address entry);
@@ -183,6 +186,7 @@
friend CompiledIC* CompiledIC_before(nmethod* nm, address return_addr);
friend CompiledIC* CompiledIC_at(nmethod* nm, address call_site);
friend CompiledIC* CompiledIC_at(Relocation* call_site);
+ friend CompiledIC* CompiledIC_at(RelocIterator* reloc_iter);
// This is used to release CompiledICHolder*s from nmethods that
// are about to be freed. The callsite might contain other stale
@@ -263,6 +267,13 @@
return c_ic;
}
+inline CompiledIC* CompiledIC_at(RelocIterator* reloc_iter) {
+ assert(reloc_iter->type() == relocInfo::virtual_call_type ||
+ reloc_iter->type() == relocInfo::opt_virtual_call_type, "wrong reloc. info");
+ CompiledIC* c_ic = new CompiledIC(reloc_iter);
+ c_ic->verify();
+ return c_ic;
+}
//-----------------------------------------------------------------------------
// The CompiledStaticCall represents a call to a static method in the compiled
--- a/hotspot/src/share/vm/code/nmethod.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/nmethod.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -51,6 +51,8 @@
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
+unsigned char nmethod::_global_unloading_clock = 0;
+
#ifdef DTRACE_ENABLED
// Only bother with this argument setup if dtrace is available
@@ -446,6 +448,7 @@
// Fill in default values for various flag fields
void nmethod::init_defaults() {
_state = in_use;
+ _unloading_clock = 0;
_marked_for_reclamation = 0;
_has_flushed_dependencies = 0;
_has_unsafe_access = 0;
@@ -464,7 +467,11 @@
_oops_do_mark_link = NULL;
_jmethod_id = NULL;
_osr_link = NULL;
- _scavenge_root_link = NULL;
+ if (UseG1GC) {
+ _unloading_next = NULL;
+ } else {
+ _scavenge_root_link = NULL;
+ }
_scavenge_root_state = 0;
_compiler = NULL;
#if INCLUDE_RTM_OPT
@@ -1146,7 +1153,7 @@
switch(iter.type()) {
case relocInfo::virtual_call_type:
case relocInfo::opt_virtual_call_type: {
- CompiledIC *ic = CompiledIC_at(iter.reloc());
+ CompiledIC *ic = CompiledIC_at(&iter);
// Ok, to lookup references to zombies here
CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
if( cb != NULL && cb->is_nmethod() ) {
@@ -1170,6 +1177,77 @@
}
}
+void nmethod::verify_clean_inline_caches() {
+ assert_locked_or_safepoint(CompiledIC_lock);
+
+ // If the method is not entrant or zombie then a JMP is plastered over the
+ // first few bytes. If an oop in the old code was there, that oop
+ // should not get GC'd. Skip the first few bytes of oops on
+ // not-entrant methods.
+ address low_boundary = verified_entry_point();
+ if (!is_in_use()) {
+ low_boundary += NativeJump::instruction_size;
+ // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
+ // This means that the low_boundary is going to be a little too high.
+ // This shouldn't matter, since oops of non-entrant methods are never used.
+ // In fact, why are we bothering to look at oops in a non-entrant method??
+ }
+
+ ResourceMark rm;
+ RelocIterator iter(this, low_boundary);
+ while(iter.next()) {
+ switch(iter.type()) {
+ case relocInfo::virtual_call_type:
+ case relocInfo::opt_virtual_call_type: {
+ CompiledIC *ic = CompiledIC_at(&iter);
+ // Ok, to lookup references to zombies here
+ CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
+ if( cb != NULL && cb->is_nmethod() ) {
+ nmethod* nm = (nmethod*)cb;
+ // Verify that inline caches pointing to both zombie and not_entrant methods are clean
+ if (!nm->is_in_use() || (nm->method()->code() != nm)) {
+ assert(ic->is_clean(), "IC should be clean");
+ }
+ }
+ break;
+ }
+ case relocInfo::static_call_type: {
+ CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
+ CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
+ if( cb != NULL && cb->is_nmethod() ) {
+ nmethod* nm = (nmethod*)cb;
+ // Verify that inline caches pointing to both zombie and not_entrant methods are clean
+ if (!nm->is_in_use() || (nm->method()->code() != nm)) {
+ assert(csc->is_clean(), "IC should be clean");
+ }
+ }
+ break;
+ }
+ }
+ }
+}
+
+int nmethod::verify_icholder_relocations() {
+ int count = 0;
+
+ RelocIterator iter(this);
+ while(iter.next()) {
+ if (iter.type() == relocInfo::virtual_call_type) {
+ if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
+ CompiledIC *ic = CompiledIC_at(&iter);
+ if (TraceCompiledIC) {
+ tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
+ ic->print();
+ }
+ assert(ic->cached_icholder() != NULL, "must be non-NULL");
+ count++;
+ }
+ }
+ }
+
+ return count;
+}
+
// This is a private interface with the sweeper.
void nmethod::mark_as_seen_on_stack() {
assert(is_alive(), "Must be an alive method");
@@ -1202,6 +1280,23 @@
mdo->inc_decompile_count();
}
+void nmethod::increase_unloading_clock() {
+ _global_unloading_clock++;
+ if (_global_unloading_clock == 0) {
+ // _nmethods are allocated with _unloading_clock == 0,
+ // so 0 is never used as a clock value.
+ _global_unloading_clock = 1;
+ }
+}
+
+void nmethod::set_unloading_clock(unsigned char unloading_clock) {
+ OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);
+}
+
+unsigned char nmethod::unloading_clock() {
+ return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock);
+}
+
void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) {
post_compiled_method_unload();
@@ -1247,6 +1342,10 @@
// for later on.
CodeCache::set_needs_cache_clean(true);
}
+
+ // Unregister must be done before the state change
+ Universe::heap()->unregister_nmethod(this);
+
_state = unloaded;
// Log the unloading.
@@ -1590,6 +1689,35 @@
set_unload_reported();
}
+void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) {
+ if (ic->is_icholder_call()) {
+ // The only exception is compiledICHolder oops which may
+ // yet be marked below. (We check this further below).
+ CompiledICHolder* cichk_oop = ic->cached_icholder();
+ if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
+ cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
+ return;
+ }
+ } else {
+ Metadata* ic_oop = ic->cached_metadata();
+ if (ic_oop != NULL) {
+ if (ic_oop->is_klass()) {
+ if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
+ return;
+ }
+ } else if (ic_oop->is_method()) {
+ if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
+ return;
+ }
+ } else {
+ ShouldNotReachHere();
+ }
+ }
+ }
+
+ ic->set_to_clean();
+}
+
// This is called at the end of the strong tracing/marking phase of a
// GC to unload an nmethod if it contains otherwise unreachable
// oops.
@@ -1632,32 +1760,8 @@
RelocIterator iter(this, low_boundary);
while(iter.next()) {
if (iter.type() == relocInfo::virtual_call_type) {
- CompiledIC *ic = CompiledIC_at(iter.reloc());
- if (ic->is_icholder_call()) {
- // The only exception is compiledICHolder oops which may
- // yet be marked below. (We check this further below).
- CompiledICHolder* cichk_oop = ic->cached_icholder();
- if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
- cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
- continue;
- }
- } else {
- Metadata* ic_oop = ic->cached_metadata();
- if (ic_oop != NULL) {
- if (ic_oop->is_klass()) {
- if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
- continue;
- }
- } else if (ic_oop->is_method()) {
- if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
- continue;
- }
- } else {
- ShouldNotReachHere();
- }
- }
- }
- ic->set_to_clean();
+ CompiledIC *ic = CompiledIC_at(&iter);
+ clean_ic_if_metadata_is_dead(ic, is_alive);
}
}
}
@@ -1695,6 +1799,175 @@
verify_metadata_loaders(low_boundary, is_alive);
}
+template <class CompiledICorStaticCall>
+static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
+ // Ok, to lookup references to zombies here
+ CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
+ if (cb != NULL && cb->is_nmethod()) {
+ nmethod* nm = (nmethod*)cb;
+
+ if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
+ // The nmethod has not been processed yet.
+ return true;
+ }
+
+ // Clean inline caches pointing to both zombie and not_entrant methods
+ if (!nm->is_in_use() || (nm->method()->code() != nm)) {
+ ic->set_to_clean();
+ assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));
+ }
+ }
+
+ return false;
+}
+
+static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
+ return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
+}
+
+static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
+ return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
+}
+
+bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
+ ResourceMark rm;
+
+ // Make sure the oop's ready to receive visitors
+ assert(!is_zombie() && !is_unloaded(),
+ "should not call follow on zombie or unloaded nmethod");
+
+ // If the method is not entrant then a JMP is plastered over the
+ // first few bytes. If an oop in the old code was there, that oop
+ // should not get GC'd. Skip the first few bytes of oops on
+ // not-entrant methods.
+ address low_boundary = verified_entry_point();
+ if (is_not_entrant()) {
+ low_boundary += NativeJump::instruction_size;
+ // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
+ // (See comment above.)
+ }
+
+ // The RedefineClasses() API can cause the class unloading invariant
+ // to no longer be true. See jvmtiExport.hpp for details.
+ // Also, leave a debugging breadcrumb in local flag.
+ bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
+ if (a_class_was_redefined) {
+ // This set of the unloading_occurred flag is done before the
+ // call to post_compiled_method_unload() so that the unloading
+ // of this nmethod is reported.
+ unloading_occurred = true;
+ }
+
+ // Exception cache
+ clean_exception_cache(is_alive);
+
+ bool is_unloaded = false;
+ bool postponed = false;
+
+ RelocIterator iter(this, low_boundary);
+ while(iter.next()) {
+
+ switch (iter.type()) {
+
+ case relocInfo::virtual_call_type:
+ if (unloading_occurred) {
+ // If class unloading occurred we first iterate over all inline caches and
+ // clear ICs where the cached oop is referring to an unloaded klass or method.
+ clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
+ }
+
+ postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
+ break;
+
+ case relocInfo::opt_virtual_call_type:
+ postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
+ break;
+
+ case relocInfo::static_call_type:
+ postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
+ break;
+
+ case relocInfo::oop_type:
+ if (!is_unloaded) {
+ // Unload check
+ oop_Relocation* r = iter.oop_reloc();
+ // Traverse those oops directly embedded in the code.
+ // Other oops (oop_index>0) are seen as part of scopes_oops.
+ assert(1 == (r->oop_is_immediate()) +
+ (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
+ "oop must be found in exactly one place");
+ if (r->oop_is_immediate() && r->oop_value() != NULL) {
+ if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
+ is_unloaded = true;
+ }
+ }
+ }
+ break;
+
+ }
+ }
+
+ if (is_unloaded) {
+ return postponed;
+ }
+
+ // Scopes
+ for (oop* p = oops_begin(); p < oops_end(); p++) {
+ if (*p == Universe::non_oop_word()) continue; // skip non-oops
+ if (can_unload(is_alive, p, unloading_occurred)) {
+ is_unloaded = true;
+ break;
+ }
+ }
+
+ if (is_unloaded) {
+ return postponed;
+ }
+
+ // Ensure that all metadata is still alive
+ verify_metadata_loaders(low_boundary, is_alive);
+
+ return postponed;
+}
+
+void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
+ ResourceMark rm;
+
+ // Make sure the oop's ready to receive visitors
+ assert(!is_zombie(),
+ "should not call follow on zombie nmethod");
+
+ // If the method is not entrant then a JMP is plastered over the
+ // first few bytes. If an oop in the old code was there, that oop
+ // should not get GC'd. Skip the first few bytes of oops on
+ // not-entrant methods.
+ address low_boundary = verified_entry_point();
+ if (is_not_entrant()) {
+ low_boundary += NativeJump::instruction_size;
+ // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
+ // (See comment above.)
+ }
+
+ RelocIterator iter(this, low_boundary);
+ while(iter.next()) {
+
+ switch (iter.type()) {
+
+ case relocInfo::virtual_call_type:
+ clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
+ break;
+
+ case relocInfo::opt_virtual_call_type:
+ clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
+ break;
+
+ case relocInfo::static_call_type:
+ clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
+ break;
+ }
+ }
+}
+
#ifdef ASSERT
class CheckClass : AllStatic {
@@ -1741,7 +2014,7 @@
// compiled code is maintaining a link to dead metadata.
address static_call_addr = NULL;
if (iter.type() == relocInfo::opt_virtual_call_type) {
- CompiledIC* cic = CompiledIC_at(iter.reloc());
+ CompiledIC* cic = CompiledIC_at(&iter);
if (!cic->is_call_to_interpreted()) {
static_call_addr = iter.addr();
}
@@ -1793,7 +2066,7 @@
}
} else if (iter.type() == relocInfo::virtual_call_type) {
// Check compiledIC holders associated with this nmethod
- CompiledIC *ic = CompiledIC_at(iter.reloc());
+ CompiledIC *ic = CompiledIC_at(&iter);
if (ic->is_icholder_call()) {
CompiledICHolder* cichk = ic->cached_icholder();
f(cichk->holder_method());
@@ -1911,7 +2184,7 @@
assert(cur != NULL, "not NULL-terminated");
nmethod* next = cur->_oops_do_mark_link;
cur->_oops_do_mark_link = NULL;
- cur->fix_oop_relocations();
+ cur->verify_oop_relocations();
NOT_PRODUCT(if (TraceScavenge) cur->print_on(tty, "oops_do, unmark"));
cur = next;
}
@@ -2479,6 +2752,10 @@
};
void nmethod::verify_scavenge_root_oops() {
+ if (UseG1GC) {
+ return;
+ }
+
if (!on_scavenge_root_list()) {
// Actually look inside, to verify the claim that it's clean.
DebugScavengeRoot debug_scavenge_root(this);
@@ -2922,7 +3199,7 @@
case relocInfo::virtual_call_type:
case relocInfo::opt_virtual_call_type: {
VerifyMutexLocker mc(CompiledIC_lock);
- CompiledIC_at(iter.reloc())->print();
+ CompiledIC_at(&iter)->print();
break;
}
case relocInfo::static_call_type:
--- a/hotspot/src/share/vm/code/nmethod.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/nmethod.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -111,6 +111,11 @@
friend class NMethodSweeper;
friend class CodeCache; // scavengable oops
private:
+
+ // GC support to help figure out if an nmethod has been
+ // cleaned/unloaded by the current GC.
+ static unsigned char _global_unloading_clock;
+
// Shared fields for all nmethod's
Method* _method;
int _entry_bci; // != InvocationEntryBci if this nmethod is an on-stack replacement method
@@ -118,7 +123,13 @@
// To support simple linked-list chaining of nmethods:
nmethod* _osr_link; // from InstanceKlass::osr_nmethods_head
- nmethod* _scavenge_root_link; // from CodeCache::scavenge_root_nmethods
+
+ union {
+ // Used by G1 to chain nmethods.
+ nmethod* _unloading_next;
+ // Used by non-G1 GCs to chain nmethods.
+ nmethod* _scavenge_root_link; // from CodeCache::scavenge_root_nmethods
+ };
static nmethod* volatile _oops_do_mark_nmethods;
nmethod* volatile _oops_do_mark_link;
@@ -180,6 +191,8 @@
// Protected by Patching_lock
volatile unsigned char _state; // {alive, not_entrant, zombie, unloaded}
+ volatile unsigned char _unloading_clock; // Incremented after GC unloaded/cleaned the nmethod
+
#ifdef ASSERT
bool _oops_are_stale; // indicates that it's no longer safe to access oops section
#endif
@@ -437,6 +450,15 @@
bool unload_reported() { return _unload_reported; }
void set_unload_reported() { _unload_reported = true; }
+ void set_unloading_next(nmethod* next) { _unloading_next = next; }
+ nmethod* unloading_next() { return _unloading_next; }
+
+ static unsigned char global_unloading_clock() { return _global_unloading_clock; }
+ static void increase_unloading_clock();
+
+ void set_unloading_clock(unsigned char unloading_clock);
+ unsigned char unloading_clock();
+
bool is_marked_for_deoptimization() const { return _marked_for_deoptimization; }
void mark_for_deoptimization() { _marked_for_deoptimization = true; }
@@ -552,6 +574,10 @@
return (addr >= code_begin() && addr < verified_entry_point());
}
+ // Verify calls to dead methods have been cleaned.
+ void verify_clean_inline_caches();
+ // Verify and count cached icholder relocations.
+ int verify_icholder_relocations();
// Check that all metadata is still alive
void verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive);
@@ -577,6 +603,10 @@
// GC support
void do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred);
+ // The parallel versions are used by G1.
+ bool do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred);
+ void do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred);
+ // Unload a nmethod if the *root object is dead.
bool can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred);
void preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map,
--- a/hotspot/src/share/vm/code/stubs.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/stubs.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -27,21 +27,6 @@
#include "asm/codeBuffer.hpp"
#include "memory/allocation.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
// The classes in this file provide a simple framework for the
// management of little pieces of machine code - or stubs -
--- a/hotspot/src/share/vm/code/vtableStubs.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/code/vtableStubs.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -24,6 +24,7 @@
#include "precompiled.hpp"
#include "code/vtableStubs.hpp"
+#include "compiler/compileBroker.hpp"
#include "compiler/disassembler.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/resourceArea.hpp"
@@ -62,6 +63,7 @@
// If changing the name, update the other file accordingly.
BufferBlob* blob = BufferBlob::create("vtable chunks", bytes);
if (blob == NULL) {
+ CompileBroker::handle_full_code_cache();
return NULL;
}
_chunk = blob->content_begin();
--- a/hotspot/src/share/vm/compiler/compileBroker.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/compiler/compileBroker.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1048,7 +1048,7 @@
}
// Let go of Threads_lock before yielding
- os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
+ os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
return compiler_thread;
}
@@ -2123,6 +2123,7 @@
ResourceMark rm;
char* method_name = method->name()->as_C_string();
strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
+ _last_method_compiled[CompileBroker::name_buffer_length - 1] = '\0'; // ensure null terminated
char current_method[CompilerCounters::cmname_buffer_length];
size_t maxLen = CompilerCounters::cmname_buffer_length;
--- a/hotspot/src/share/vm/compiler/disassembler.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/compiler/disassembler.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -30,6 +30,7 @@
#include "memory/cardTableModRefBS.hpp"
#include "runtime/fprofiler.hpp"
#include "runtime/handles.inline.hpp"
+#include "runtime/os.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "runtime/stubRoutines.hpp"
#ifdef TARGET_ARCH_x86
--- a/hotspot/src/share/vm/compiler/disassembler.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/compiler/disassembler.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -27,21 +27,6 @@
#include "asm/codeBuffer.hpp"
#include "runtime/globals.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
class decode_env;
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/adaptiveFreeList.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/adaptiveFreeList.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,6 +29,7 @@
#include "memory/sharedHeap.hpp"
#include "runtime/globals.hpp"
#include "runtime/mutex.hpp"
+#include "runtime/orderAccess.inline.hpp"
#include "runtime/vmThread.hpp"
template <>
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.cpp Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1354 +0,0 @@
-/*
- * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
-#include "gc_implementation/shared/gcStats.hpp"
-#include "memory/defNewGeneration.hpp"
-#include "memory/genCollectedHeap.hpp"
-#include "runtime/thread.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
-elapsedTimer CMSAdaptiveSizePolicy::_concurrent_timer;
-elapsedTimer CMSAdaptiveSizePolicy::_STW_timer;
-
-// Defined if the granularity of the time measurements is potentially too large.
-#define CLOCK_GRANULARITY_TOO_LARGE
-
-CMSAdaptiveSizePolicy::CMSAdaptiveSizePolicy(size_t init_eden_size,
- size_t init_promo_size,
- size_t init_survivor_size,
- double max_gc_minor_pause_sec,
- double max_gc_pause_sec,
- uint gc_cost_ratio) :
- AdaptiveSizePolicy(init_eden_size,
- init_promo_size,
- init_survivor_size,
- max_gc_pause_sec,
- gc_cost_ratio) {
-
- clear_internal_time_intervals();
-
- _processor_count = os::active_processor_count();
-
- if (CMSConcurrentMTEnabled && (ConcGCThreads > 1)) {
- assert(_processor_count > 0, "Processor count is suspect");
- _concurrent_processor_count = MIN2((uint) ConcGCThreads,
- (uint) _processor_count);
- } else {
- _concurrent_processor_count = 1;
- }
-
- _avg_concurrent_time = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_concurrent_interval = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_concurrent_gc_cost = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
-
- _avg_initial_pause = new AdaptivePaddedAverage(AdaptiveTimeWeight,
- PausePadding);
- _avg_remark_pause = new AdaptivePaddedAverage(AdaptiveTimeWeight,
- PausePadding);
-
- _avg_cms_STW_time = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_cms_STW_gc_cost = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
-
- _avg_cms_free = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_cms_free_at_sweep = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_cms_promo = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
-
- // Mark-sweep-compact
- _avg_msc_pause = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_msc_interval = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_msc_gc_cost = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
-
- // Mark-sweep
- _avg_ms_pause = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_ms_interval = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
- _avg_ms_gc_cost = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
-
- // Variables that estimate pause times as a function of generation
- // size.
- _remark_pause_old_estimator =
- new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
- _initial_pause_old_estimator =
- new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
- _remark_pause_young_estimator =
- new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
- _initial_pause_young_estimator =
- new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
-
- // Alignment comes from that used in ReservedSpace.
- _generation_alignment = os::vm_allocation_granularity();
-
- // Start the concurrent timer here so that the first
- // concurrent_phases_begin() measures a finite mutator
- // time. A finite mutator time is used to determine
- // if a concurrent collection has been started. If this
- // proves to be a problem, use some explicit flag to
- // signal that a concurrent collection has been started.
- _concurrent_timer.start();
- _STW_timer.start();
-}
-
-double CMSAdaptiveSizePolicy::concurrent_processor_fraction() {
- // For now assume no other daemon threads are taking alway
- // cpu's from the application.
- return ((double) _concurrent_processor_count / (double) _processor_count);
-}
-
-double CMSAdaptiveSizePolicy::concurrent_collection_cost(
- double interval_in_seconds) {
- // When the precleaning and sweeping phases use multiple
- // threads, change one_processor_fraction to
- // concurrent_processor_fraction().
- double one_processor_fraction = 1.0 / ((double) processor_count());
- double concurrent_cost =
- collection_cost(_latest_cms_concurrent_marking_time_secs,
- interval_in_seconds) * concurrent_processor_fraction() +
- collection_cost(_latest_cms_concurrent_precleaning_time_secs,
- interval_in_seconds) * one_processor_fraction +
- collection_cost(_latest_cms_concurrent_sweeping_time_secs,
- interval_in_seconds) * one_processor_fraction;
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "\nCMSAdaptiveSizePolicy::scaled_concurrent_collection_cost(%f) "
- "_latest_cms_concurrent_marking_cost %f "
- "_latest_cms_concurrent_precleaning_cost %f "
- "_latest_cms_concurrent_sweeping_cost %f "
- "concurrent_processor_fraction %f "
- "concurrent_cost %f ",
- interval_in_seconds,
- collection_cost(_latest_cms_concurrent_marking_time_secs,
- interval_in_seconds),
- collection_cost(_latest_cms_concurrent_precleaning_time_secs,
- interval_in_seconds),
- collection_cost(_latest_cms_concurrent_sweeping_time_secs,
- interval_in_seconds),
- concurrent_processor_fraction(),
- concurrent_cost);
- }
- return concurrent_cost;
-}
-
-double CMSAdaptiveSizePolicy::concurrent_collection_time() {
- double latest_cms_sum_concurrent_phases_time_secs =
- _latest_cms_concurrent_marking_time_secs +
- _latest_cms_concurrent_precleaning_time_secs +
- _latest_cms_concurrent_sweeping_time_secs;
- return latest_cms_sum_concurrent_phases_time_secs;
-}
-
-double CMSAdaptiveSizePolicy::scaled_concurrent_collection_time() {
- // When the precleaning and sweeping phases use multiple
- // threads, change one_processor_fraction to
- // concurrent_processor_fraction().
- double one_processor_fraction = 1.0 / ((double) processor_count());
- double latest_cms_sum_concurrent_phases_time_secs =
- _latest_cms_concurrent_marking_time_secs * concurrent_processor_fraction() +
- _latest_cms_concurrent_precleaning_time_secs * one_processor_fraction +
- _latest_cms_concurrent_sweeping_time_secs * one_processor_fraction ;
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "\nCMSAdaptiveSizePolicy::scaled_concurrent_collection_time "
- "_latest_cms_concurrent_marking_time_secs %f "
- "_latest_cms_concurrent_precleaning_time_secs %f "
- "_latest_cms_concurrent_sweeping_time_secs %f "
- "concurrent_processor_fraction %f "
- "latest_cms_sum_concurrent_phases_time_secs %f ",
- _latest_cms_concurrent_marking_time_secs,
- _latest_cms_concurrent_precleaning_time_secs,
- _latest_cms_concurrent_sweeping_time_secs,
- concurrent_processor_fraction(),
- latest_cms_sum_concurrent_phases_time_secs);
- }
- return latest_cms_sum_concurrent_phases_time_secs;
-}
-
-void CMSAdaptiveSizePolicy::update_minor_pause_old_estimator(
- double minor_pause_in_ms) {
- // Get the equivalent of the free space
- // that is available for promotions in the CMS generation
- // and use that to update _minor_pause_old_estimator
-
- // Don't implement this until it is needed. A warning is
- // printed if _minor_pause_old_estimator is used.
-}
-
-void CMSAdaptiveSizePolicy::concurrent_marking_begin() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(" ");
- gclog_or_tty->stamp();
- gclog_or_tty->print(": concurrent_marking_begin ");
- }
- // Update the interval time
- _concurrent_timer.stop();
- _latest_cms_collection_end_to_collection_start_secs = _concurrent_timer.seconds();
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::concurrent_marking_begin: "
- "mutator time %f", _latest_cms_collection_end_to_collection_start_secs);
- }
- _concurrent_timer.reset();
- _concurrent_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::concurrent_marking_end() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->stamp();
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::concurrent_marking_end()");
- }
-
- _concurrent_timer.stop();
- _latest_cms_concurrent_marking_time_secs = _concurrent_timer.seconds();
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("\n CMSAdaptiveSizePolicy::concurrent_marking_end"
- ":concurrent marking time (s) %f",
- _latest_cms_concurrent_marking_time_secs);
- }
-}
-
-void CMSAdaptiveSizePolicy::concurrent_precleaning_begin() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->stamp();
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::concurrent_precleaning_begin()");
- }
- _concurrent_timer.reset();
- _concurrent_timer.start();
-}
-
-
-void CMSAdaptiveSizePolicy::concurrent_precleaning_end() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->stamp();
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::concurrent_precleaning_end()");
- }
-
- _concurrent_timer.stop();
- // May be set again by a second call during the same collection.
- _latest_cms_concurrent_precleaning_time_secs = _concurrent_timer.seconds();
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("\n CMSAdaptiveSizePolicy::concurrent_precleaning_end"
- ":concurrent precleaning time (s) %f",
- _latest_cms_concurrent_precleaning_time_secs);
- }
-}
-
-void CMSAdaptiveSizePolicy::concurrent_sweeping_begin() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->stamp();
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::concurrent_sweeping_begin()");
- }
- _concurrent_timer.reset();
- _concurrent_timer.start();
-}
-
-
-void CMSAdaptiveSizePolicy::concurrent_sweeping_end() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->stamp();
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::concurrent_sweeping_end()");
- }
-
- _concurrent_timer.stop();
- _latest_cms_concurrent_sweeping_time_secs = _concurrent_timer.seconds();
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("\n CMSAdaptiveSizePolicy::concurrent_sweeping_end"
- ":concurrent sweeping time (s) %f",
- _latest_cms_concurrent_sweeping_time_secs);
- }
-}
-
-void CMSAdaptiveSizePolicy::concurrent_phases_end(GCCause::Cause gc_cause,
- size_t cur_eden,
- size_t cur_promo) {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(" ");
- gclog_or_tty->stamp();
- gclog_or_tty->print(": concurrent_phases_end ");
- }
-
- // Update the concurrent timer
- _concurrent_timer.stop();
-
- if (gc_cause != GCCause::_java_lang_system_gc ||
- UseAdaptiveSizePolicyWithSystemGC) {
-
- avg_cms_free()->sample(cur_promo);
- double latest_cms_sum_concurrent_phases_time_secs =
- concurrent_collection_time();
-
- _avg_concurrent_time->sample(latest_cms_sum_concurrent_phases_time_secs);
-
- // Cost of collection (unit-less)
-
- // Total interval for collection. May not be valid. Tests
- // below determine whether to use this.
- //
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("\nCMSAdaptiveSizePolicy::concurrent_phases_end \n"
- "_latest_cms_reset_end_to_initial_mark_start_secs %f \n"
- "_latest_cms_initial_mark_start_to_end_time_secs %f \n"
- "_latest_cms_remark_start_to_end_time_secs %f \n"
- "_latest_cms_concurrent_marking_time_secs %f \n"
- "_latest_cms_concurrent_precleaning_time_secs %f \n"
- "_latest_cms_concurrent_sweeping_time_secs %f \n"
- "latest_cms_sum_concurrent_phases_time_secs %f \n"
- "_latest_cms_collection_end_to_collection_start_secs %f \n"
- "concurrent_processor_fraction %f",
- _latest_cms_reset_end_to_initial_mark_start_secs,
- _latest_cms_initial_mark_start_to_end_time_secs,
- _latest_cms_remark_start_to_end_time_secs,
- _latest_cms_concurrent_marking_time_secs,
- _latest_cms_concurrent_precleaning_time_secs,
- _latest_cms_concurrent_sweeping_time_secs,
- latest_cms_sum_concurrent_phases_time_secs,
- _latest_cms_collection_end_to_collection_start_secs,
- concurrent_processor_fraction());
- }
- double interval_in_seconds =
- _latest_cms_initial_mark_start_to_end_time_secs +
- _latest_cms_remark_start_to_end_time_secs +
- latest_cms_sum_concurrent_phases_time_secs +
- _latest_cms_collection_end_to_collection_start_secs;
- assert(interval_in_seconds >= 0.0,
- "Bad interval between cms collections");
-
- // Sample for performance counter
- avg_concurrent_interval()->sample(interval_in_seconds);
-
- // STW costs (initial and remark pauses)
- // Cost of collection (unit-less)
- assert(_latest_cms_initial_mark_start_to_end_time_secs >= 0.0,
- "Bad initial mark pause");
- assert(_latest_cms_remark_start_to_end_time_secs >= 0.0,
- "Bad remark pause");
- double STW_time_in_seconds =
- _latest_cms_initial_mark_start_to_end_time_secs +
- _latest_cms_remark_start_to_end_time_secs;
- double STW_collection_cost = 0.0;
- if (interval_in_seconds > 0.0) {
- // cost for the STW phases of the concurrent collection.
- STW_collection_cost = STW_time_in_seconds / interval_in_seconds;
- avg_cms_STW_gc_cost()->sample(STW_collection_cost);
- }
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print("cmsAdaptiveSizePolicy::STW_collection_end: "
- "STW gc cost: %f average: %f", STW_collection_cost,
- avg_cms_STW_gc_cost()->average());
- gclog_or_tty->print_cr(" STW pause: %f (ms) STW period %f (ms)",
- (double) STW_time_in_seconds * MILLIUNITS,
- (double) interval_in_seconds * MILLIUNITS);
- }
-
- double concurrent_cost = 0.0;
- if (latest_cms_sum_concurrent_phases_time_secs > 0.0) {
- concurrent_cost = concurrent_collection_cost(interval_in_seconds);
-
- avg_concurrent_gc_cost()->sample(concurrent_cost);
- // Average this ms cost into all the other types gc costs
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print("cmsAdaptiveSizePolicy::concurrent_phases_end: "
- "concurrent gc cost: %f average: %f",
- concurrent_cost,
- _avg_concurrent_gc_cost->average());
- gclog_or_tty->print_cr(" concurrent time: %f (ms) cms period %f (ms)"
- " processor fraction: %f",
- latest_cms_sum_concurrent_phases_time_secs * MILLIUNITS,
- interval_in_seconds * MILLIUNITS,
- concurrent_processor_fraction());
- }
- }
- double total_collection_cost = STW_collection_cost + concurrent_cost;
- avg_major_gc_cost()->sample(total_collection_cost);
-
- // Gather information for estimating future behavior
- double initial_pause_in_ms = _latest_cms_initial_mark_start_to_end_time_secs * MILLIUNITS;
- double remark_pause_in_ms = _latest_cms_remark_start_to_end_time_secs * MILLIUNITS;
-
- double cur_promo_size_in_mbytes = ((double)cur_promo)/((double)M);
- initial_pause_old_estimator()->update(cur_promo_size_in_mbytes,
- initial_pause_in_ms);
- remark_pause_old_estimator()->update(cur_promo_size_in_mbytes,
- remark_pause_in_ms);
- major_collection_estimator()->update(cur_promo_size_in_mbytes,
- total_collection_cost);
-
- // This estimate uses the average eden size. It could also
- // have used the latest eden size. Which is better?
- double cur_eden_size_in_mbytes = ((double)cur_eden)/((double) M);
- initial_pause_young_estimator()->update(cur_eden_size_in_mbytes,
- initial_pause_in_ms);
- remark_pause_young_estimator()->update(cur_eden_size_in_mbytes,
- remark_pause_in_ms);
- }
-
- clear_internal_time_intervals();
-
- set_first_after_collection();
-
- // The concurrent phases keeps track of it's own mutator interval
- // with this timer. This allows the stop-the-world phase to
- // be included in the mutator time so that the stop-the-world time
- // is not double counted. Reset and start it.
- _concurrent_timer.reset();
- _concurrent_timer.start();
-
- // The mutator time between STW phases does not include the
- // concurrent collection time.
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::checkpoint_roots_initial_begin() {
- // Update the interval time
- _STW_timer.stop();
- _latest_cms_reset_end_to_initial_mark_start_secs = _STW_timer.seconds();
- // Reset for the initial mark
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::checkpoint_roots_initial_end(
- GCCause::Cause gc_cause) {
- _STW_timer.stop();
-
- if (gc_cause != GCCause::_java_lang_system_gc ||
- UseAdaptiveSizePolicyWithSystemGC) {
- _latest_cms_initial_mark_start_to_end_time_secs = _STW_timer.seconds();
- avg_initial_pause()->sample(_latest_cms_initial_mark_start_to_end_time_secs);
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(
- "cmsAdaptiveSizePolicy::checkpoint_roots_initial_end: "
- "initial pause: %f ", _latest_cms_initial_mark_start_to_end_time_secs);
- }
- }
-
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::checkpoint_roots_final_begin() {
- _STW_timer.stop();
- _latest_cms_initial_mark_end_to_remark_start_secs = _STW_timer.seconds();
- // Start accumulating time for the remark in the STW timer.
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::checkpoint_roots_final_end(
- GCCause::Cause gc_cause) {
- _STW_timer.stop();
- if (gc_cause != GCCause::_java_lang_system_gc ||
- UseAdaptiveSizePolicyWithSystemGC) {
- // Total initial mark pause + remark pause.
- _latest_cms_remark_start_to_end_time_secs = _STW_timer.seconds();
- double STW_time_in_seconds = _latest_cms_initial_mark_start_to_end_time_secs +
- _latest_cms_remark_start_to_end_time_secs;
- double STW_time_in_ms = STW_time_in_seconds * MILLIUNITS;
-
- avg_remark_pause()->sample(_latest_cms_remark_start_to_end_time_secs);
-
- // Sample total for initial mark + remark
- avg_cms_STW_time()->sample(STW_time_in_seconds);
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print("cmsAdaptiveSizePolicy::checkpoint_roots_final_end: "
- "remark pause: %f", _latest_cms_remark_start_to_end_time_secs);
- }
-
- }
- // Don't start the STW times here because the concurrent
- // sweep and reset has not happened.
- // Keep the old comment above in case I don't understand
- // what is going on but now
- // Start the STW timer because it is used by ms_collection_begin()
- // and ms_collection_end() to get the sweep time if a MS is being
- // done in the foreground.
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::msc_collection_begin() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(" ");
- gclog_or_tty->stamp();
- gclog_or_tty->print(": msc_collection_begin ");
- }
- _STW_timer.stop();
- _latest_cms_msc_end_to_msc_start_time_secs = _STW_timer.seconds();
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::msc_collection_begin: "
- "mutator time %f",
- _latest_cms_msc_end_to_msc_start_time_secs);
- }
- avg_msc_interval()->sample(_latest_cms_msc_end_to_msc_start_time_secs);
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::msc_collection_end(GCCause::Cause gc_cause) {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(" ");
- gclog_or_tty->stamp();
- gclog_or_tty->print(": msc_collection_end ");
- }
- _STW_timer.stop();
- if (gc_cause != GCCause::_java_lang_system_gc ||
- UseAdaptiveSizePolicyWithSystemGC) {
- double msc_pause_in_seconds = _STW_timer.seconds();
- if ((_latest_cms_msc_end_to_msc_start_time_secs > 0.0) &&
- (msc_pause_in_seconds > 0.0)) {
- avg_msc_pause()->sample(msc_pause_in_seconds);
- double mutator_time_in_seconds = 0.0;
- if (_latest_cms_collection_end_to_collection_start_secs == 0.0) {
- // This assertion may fail because of time stamp granularity.
- // Comment it out and investigate it at a later time. The large
- // time stamp granularity occurs on some older linux systems.
-#ifndef CLOCK_GRANULARITY_TOO_LARGE
- assert((_latest_cms_concurrent_marking_time_secs == 0.0) &&
- (_latest_cms_concurrent_precleaning_time_secs == 0.0) &&
- (_latest_cms_concurrent_sweeping_time_secs == 0.0),
- "There should not be any concurrent time");
-#endif
- // A concurrent collection did not start. Mutator time
- // between collections comes from the STW MSC timer.
- mutator_time_in_seconds = _latest_cms_msc_end_to_msc_start_time_secs;
- } else {
- // The concurrent collection did start so count the mutator
- // time to the start of the concurrent collection. In this
- // case the _latest_cms_msc_end_to_msc_start_time_secs measures
- // the time between the initial mark or remark and the
- // start of the MSC. That has no real meaning.
- mutator_time_in_seconds = _latest_cms_collection_end_to_collection_start_secs;
- }
-
- double latest_cms_sum_concurrent_phases_time_secs =
- concurrent_collection_time();
- double interval_in_seconds =
- mutator_time_in_seconds +
- _latest_cms_initial_mark_start_to_end_time_secs +
- _latest_cms_remark_start_to_end_time_secs +
- latest_cms_sum_concurrent_phases_time_secs +
- msc_pause_in_seconds;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" interval_in_seconds %f \n"
- " mutator_time_in_seconds %f \n"
- " _latest_cms_initial_mark_start_to_end_time_secs %f\n"
- " _latest_cms_remark_start_to_end_time_secs %f\n"
- " latest_cms_sum_concurrent_phases_time_secs %f\n"
- " msc_pause_in_seconds %f\n",
- interval_in_seconds,
- mutator_time_in_seconds,
- _latest_cms_initial_mark_start_to_end_time_secs,
- _latest_cms_remark_start_to_end_time_secs,
- latest_cms_sum_concurrent_phases_time_secs,
- msc_pause_in_seconds);
- }
-
- // The concurrent cost is wasted cost but it should be
- // included.
- double concurrent_cost = concurrent_collection_cost(interval_in_seconds);
-
- // Initial mark and remark, also wasted.
- double STW_time_in_seconds = _latest_cms_initial_mark_start_to_end_time_secs +
- _latest_cms_remark_start_to_end_time_secs;
- double STW_collection_cost =
- collection_cost(STW_time_in_seconds, interval_in_seconds) +
- concurrent_cost;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" msc_collection_end:\n"
- "_latest_cms_collection_end_to_collection_start_secs %f\n"
- "_latest_cms_msc_end_to_msc_start_time_secs %f\n"
- "_latest_cms_initial_mark_start_to_end_time_secs %f\n"
- "_latest_cms_remark_start_to_end_time_secs %f\n"
- "latest_cms_sum_concurrent_phases_time_secs %f\n",
- _latest_cms_collection_end_to_collection_start_secs,
- _latest_cms_msc_end_to_msc_start_time_secs,
- _latest_cms_initial_mark_start_to_end_time_secs,
- _latest_cms_remark_start_to_end_time_secs,
- latest_cms_sum_concurrent_phases_time_secs);
-
- gclog_or_tty->print_cr(" msc_collection_end: \n"
- "latest_cms_sum_concurrent_phases_time_secs %f\n"
- "STW_time_in_seconds %f\n"
- "msc_pause_in_seconds %f\n",
- latest_cms_sum_concurrent_phases_time_secs,
- STW_time_in_seconds,
- msc_pause_in_seconds);
- }
-
- double cost = concurrent_cost + STW_collection_cost +
- collection_cost(msc_pause_in_seconds, interval_in_seconds);
-
- _avg_msc_gc_cost->sample(cost);
-
- // Average this ms cost into all the other types gc costs
- avg_major_gc_cost()->sample(cost);
-
- // Sample for performance counter
- _avg_msc_interval->sample(interval_in_seconds);
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print("cmsAdaptiveSizePolicy::msc_collection_end: "
- "MSC gc cost: %f average: %f", cost,
- _avg_msc_gc_cost->average());
-
- double msc_pause_in_ms = msc_pause_in_seconds * MILLIUNITS;
- gclog_or_tty->print_cr(" MSC pause: %f (ms) MSC period %f (ms)",
- msc_pause_in_ms, (double) interval_in_seconds * MILLIUNITS);
- }
- }
- }
-
- clear_internal_time_intervals();
-
- // Can this call be put into the epilogue?
- set_first_after_collection();
-
- // The concurrent phases keeps track of it's own mutator interval
- // with this timer. This allows the stop-the-world phase to
- // be included in the mutator time so that the stop-the-world time
- // is not double counted. Reset and start it.
- _concurrent_timer.stop();
- _concurrent_timer.reset();
- _concurrent_timer.start();
-
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::ms_collection_begin() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(" ");
- gclog_or_tty->stamp();
- gclog_or_tty->print(": ms_collection_begin ");
- }
- _STW_timer.stop();
- _latest_cms_ms_end_to_ms_start = _STW_timer.seconds();
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::ms_collection_begin: "
- "mutator time %f",
- _latest_cms_ms_end_to_ms_start);
- }
- avg_ms_interval()->sample(_STW_timer.seconds());
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::ms_collection_end(GCCause::Cause gc_cause) {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print(" ");
- gclog_or_tty->stamp();
- gclog_or_tty->print(": ms_collection_end ");
- }
- _STW_timer.stop();
- if (gc_cause != GCCause::_java_lang_system_gc ||
- UseAdaptiveSizePolicyWithSystemGC) {
- // The MS collection is a foreground collection that does all
- // the parts of a mostly concurrent collection.
- //
- // For this collection include the cost of the
- // initial mark
- // remark
- // all concurrent time (scaled down by the
- // concurrent_processor_fraction). Some
- // may be zero if the baton was passed before
- // it was reached.
- // concurrent marking
- // sweeping
- // resetting
- // STW after baton was passed (STW_in_foreground_in_seconds)
- double STW_in_foreground_in_seconds = _STW_timer.seconds();
-
- double latest_cms_sum_concurrent_phases_time_secs =
- concurrent_collection_time();
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("\nCMSAdaptiveSizePolicy::ms_collection_end "
- "STW_in_foreground_in_seconds %f "
- "_latest_cms_initial_mark_start_to_end_time_secs %f "
- "_latest_cms_remark_start_to_end_time_secs %f "
- "latest_cms_sum_concurrent_phases_time_secs %f "
- "_latest_cms_ms_marking_start_to_end_time_secs %f "
- "_latest_cms_ms_end_to_ms_start %f",
- STW_in_foreground_in_seconds,
- _latest_cms_initial_mark_start_to_end_time_secs,
- _latest_cms_remark_start_to_end_time_secs,
- latest_cms_sum_concurrent_phases_time_secs,
- _latest_cms_ms_marking_start_to_end_time_secs,
- _latest_cms_ms_end_to_ms_start);
- }
-
- double STW_marking_in_seconds = _latest_cms_initial_mark_start_to_end_time_secs +
- _latest_cms_remark_start_to_end_time_secs;
-#ifndef CLOCK_GRANULARITY_TOO_LARGE
- assert(_latest_cms_ms_marking_start_to_end_time_secs == 0.0 ||
- latest_cms_sum_concurrent_phases_time_secs == 0.0,
- "marking done twice?");
-#endif
- double ms_time_in_seconds = STW_marking_in_seconds +
- STW_in_foreground_in_seconds +
- _latest_cms_ms_marking_start_to_end_time_secs +
- scaled_concurrent_collection_time();
- avg_ms_pause()->sample(ms_time_in_seconds);
- // Use the STW costs from the initial mark and remark plus
- // the cost of the concurrent phase to calculate a
- // collection cost.
- double cost = 0.0;
- if ((_latest_cms_ms_end_to_ms_start > 0.0) &&
- (ms_time_in_seconds > 0.0)) {
- double interval_in_seconds =
- _latest_cms_ms_end_to_ms_start + ms_time_in_seconds;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("\n ms_time_in_seconds %f "
- "latest_cms_sum_concurrent_phases_time_secs %f "
- "interval_in_seconds %f",
- ms_time_in_seconds,
- latest_cms_sum_concurrent_phases_time_secs,
- interval_in_seconds);
- }
-
- cost = collection_cost(ms_time_in_seconds, interval_in_seconds);
-
- _avg_ms_gc_cost->sample(cost);
- // Average this ms cost into all the other types gc costs
- avg_major_gc_cost()->sample(cost);
-
- // Sample for performance counter
- _avg_ms_interval->sample(interval_in_seconds);
- }
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print("cmsAdaptiveSizePolicy::ms_collection_end: "
- "MS gc cost: %f average: %f", cost, _avg_ms_gc_cost->average());
-
- double ms_time_in_ms = ms_time_in_seconds * MILLIUNITS;
- gclog_or_tty->print_cr(" MS pause: %f (ms) MS period %f (ms)",
- ms_time_in_ms,
- _latest_cms_ms_end_to_ms_start * MILLIUNITS);
- }
- }
-
- // Consider putting this code (here to end) into a
- // method for convenience.
- clear_internal_time_intervals();
-
- set_first_after_collection();
-
- // The concurrent phases keeps track of it's own mutator interval
- // with this timer. This allows the stop-the-world phase to
- // be included in the mutator time so that the stop-the-world time
- // is not double counted. Reset and start it.
- _concurrent_timer.stop();
- _concurrent_timer.reset();
- _concurrent_timer.start();
-
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::clear_internal_time_intervals() {
- _latest_cms_reset_end_to_initial_mark_start_secs = 0.0;
- _latest_cms_initial_mark_end_to_remark_start_secs = 0.0;
- _latest_cms_collection_end_to_collection_start_secs = 0.0;
- _latest_cms_concurrent_marking_time_secs = 0.0;
- _latest_cms_concurrent_precleaning_time_secs = 0.0;
- _latest_cms_concurrent_sweeping_time_secs = 0.0;
- _latest_cms_msc_end_to_msc_start_time_secs = 0.0;
- _latest_cms_ms_end_to_ms_start = 0.0;
- _latest_cms_remark_start_to_end_time_secs = 0.0;
- _latest_cms_initial_mark_start_to_end_time_secs = 0.0;
- _latest_cms_ms_marking_start_to_end_time_secs = 0.0;
-}
-
-void CMSAdaptiveSizePolicy::clear_generation_free_space_flags() {
- AdaptiveSizePolicy::clear_generation_free_space_flags();
-
- set_change_young_gen_for_maj_pauses(0);
-}
-
-void CMSAdaptiveSizePolicy::concurrent_phases_resume() {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->stamp();
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::concurrent_phases_resume()");
- }
- _concurrent_timer.start();
-}
-
-double CMSAdaptiveSizePolicy::time_since_major_gc() const {
- _concurrent_timer.stop();
- double time_since_cms_gc = _concurrent_timer.seconds();
- _concurrent_timer.start();
- _STW_timer.stop();
- double time_since_STW_gc = _STW_timer.seconds();
- _STW_timer.start();
-
- return MIN2(time_since_cms_gc, time_since_STW_gc);
-}
-
-double CMSAdaptiveSizePolicy::major_gc_interval_average_for_decay() const {
- double cms_interval = _avg_concurrent_interval->average();
- double msc_interval = _avg_msc_interval->average();
- double ms_interval = _avg_ms_interval->average();
-
- return MAX3(cms_interval, msc_interval, ms_interval);
-}
-
-double CMSAdaptiveSizePolicy::cms_gc_cost() const {
- return avg_major_gc_cost()->average();
-}
-
-void CMSAdaptiveSizePolicy::ms_collection_marking_begin() {
- _STW_timer.stop();
- // Start accumulating time for the marking in the STW timer.
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-void CMSAdaptiveSizePolicy::ms_collection_marking_end(
- GCCause::Cause gc_cause) {
- _STW_timer.stop();
- if (gc_cause != GCCause::_java_lang_system_gc ||
- UseAdaptiveSizePolicyWithSystemGC) {
- _latest_cms_ms_marking_start_to_end_time_secs = _STW_timer.seconds();
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("CMSAdaptiveSizePolicy::"
- "msc_collection_marking_end: mutator time %f",
- _latest_cms_ms_marking_start_to_end_time_secs);
- }
- }
- _STW_timer.reset();
- _STW_timer.start();
-}
-
-double CMSAdaptiveSizePolicy::gc_cost() const {
- double cms_gen_cost = cms_gc_cost();
- double result = MIN2(1.0, minor_gc_cost() + cms_gen_cost);
- assert(result >= 0.0, "Both minor and major costs are non-negative");
- return result;
-}
-
-// Cost of collection (unit-less)
-double CMSAdaptiveSizePolicy::collection_cost(double pause_in_seconds,
- double interval_in_seconds) {
- // Cost of collection (unit-less)
- double cost = 0.0;
- if ((interval_in_seconds > 0.0) &&
- (pause_in_seconds > 0.0)) {
- cost =
- pause_in_seconds / interval_in_seconds;
- }
- return cost;
-}
-
-size_t CMSAdaptiveSizePolicy::adjust_eden_for_pause_time(size_t cur_eden) {
- size_t change = 0;
- size_t desired_eden = cur_eden;
-
- // reduce eden size
- change = eden_decrement_aligned_down(cur_eden);
- desired_eden = cur_eden - change;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::adjust_eden_for_pause_time "
- "adjusting eden for pause time. "
- " starting eden size " SIZE_FORMAT
- " reduced eden size " SIZE_FORMAT
- " eden delta " SIZE_FORMAT,
- cur_eden, desired_eden, change);
- }
-
- return desired_eden;
-}
-
-size_t CMSAdaptiveSizePolicy::adjust_eden_for_throughput(size_t cur_eden) {
-
- size_t desired_eden = cur_eden;
-
- set_change_young_gen_for_throughput(increase_young_gen_for_througput_true);
-
- size_t change = eden_increment_aligned_up(cur_eden);
- size_t scaled_change = scale_by_gen_gc_cost(change, minor_gc_cost());
-
- if (cur_eden + scaled_change > cur_eden) {
- desired_eden = cur_eden + scaled_change;
- }
-
- _young_gen_change_for_minor_throughput++;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::adjust_eden_for_throughput "
- "adjusting eden for throughput. "
- " starting eden size " SIZE_FORMAT
- " increased eden size " SIZE_FORMAT
- " eden delta " SIZE_FORMAT,
- cur_eden, desired_eden, scaled_change);
- }
-
- return desired_eden;
-}
-
-size_t CMSAdaptiveSizePolicy::adjust_eden_for_footprint(size_t cur_eden) {
-
- set_decrease_for_footprint(decrease_young_gen_for_footprint_true);
-
- size_t change = eden_decrement(cur_eden);
- size_t desired_eden_size = cur_eden - change;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::adjust_eden_for_footprint "
- "adjusting eden for footprint. "
- " starting eden size " SIZE_FORMAT
- " reduced eden size " SIZE_FORMAT
- " eden delta " SIZE_FORMAT,
- cur_eden, desired_eden_size, change);
- }
- return desired_eden_size;
-}
-
-// The eden and promo versions should be combined if possible.
-// They are the same except that the sizes of the decrement
-// and increment are different for eden and promo.
-size_t CMSAdaptiveSizePolicy::eden_decrement_aligned_down(size_t cur_eden) {
- size_t delta = eden_decrement(cur_eden);
- return align_size_down(delta, generation_alignment());
-}
-
-size_t CMSAdaptiveSizePolicy::eden_increment_aligned_up(size_t cur_eden) {
- size_t delta = eden_increment(cur_eden);
- return align_size_up(delta, generation_alignment());
-}
-
-size_t CMSAdaptiveSizePolicy::promo_decrement_aligned_down(size_t cur_promo) {
- size_t delta = promo_decrement(cur_promo);
- return align_size_down(delta, generation_alignment());
-}
-
-size_t CMSAdaptiveSizePolicy::promo_increment_aligned_up(size_t cur_promo) {
- size_t delta = promo_increment(cur_promo);
- return align_size_up(delta, generation_alignment());
-}
-
-
-void CMSAdaptiveSizePolicy::compute_eden_space_size(size_t cur_eden,
- size_t max_eden_size)
-{
- size_t desired_eden_size = cur_eden;
- size_t eden_limit = max_eden_size;
-
- // Printout input
- if (PrintGC && PrintAdaptiveSizePolicy) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::compute_eden_space_size: "
- "cur_eden " SIZE_FORMAT,
- cur_eden);
- }
-
- // Used for diagnostics
- clear_generation_free_space_flags();
-
- if (_avg_minor_pause->padded_average() > gc_pause_goal_sec()) {
- if (minor_pause_young_estimator()->decrement_will_decrease()) {
- // If the minor pause is too long, shrink the young gen.
- set_change_young_gen_for_min_pauses(
- decrease_young_gen_for_min_pauses_true);
- desired_eden_size = adjust_eden_for_pause_time(desired_eden_size);
- }
- } else if ((avg_remark_pause()->padded_average() > gc_pause_goal_sec()) ||
- (avg_initial_pause()->padded_average() > gc_pause_goal_sec())) {
- // The remark or initial pauses are not meeting the goal. Should
- // the generation be shrunk?
- if (get_and_clear_first_after_collection() &&
- ((avg_remark_pause()->padded_average() > gc_pause_goal_sec() &&
- remark_pause_young_estimator()->decrement_will_decrease()) ||
- (avg_initial_pause()->padded_average() > gc_pause_goal_sec() &&
- initial_pause_young_estimator()->decrement_will_decrease()))) {
-
- set_change_young_gen_for_maj_pauses(
- decrease_young_gen_for_maj_pauses_true);
-
- // If the remark or initial pause is too long and this is the
- // first young gen collection after a cms collection, shrink
- // the young gen.
- desired_eden_size = adjust_eden_for_pause_time(desired_eden_size);
- }
- // If not the first young gen collection after a cms collection,
- // don't do anything. In this case an adjustment has already
- // been made and the results of the adjustment has not yet been
- // measured.
- } else if ((minor_gc_cost() >= 0.0) &&
- (adjusted_mutator_cost() < _throughput_goal)) {
- desired_eden_size = adjust_eden_for_throughput(desired_eden_size);
- } else {
- desired_eden_size = adjust_eden_for_footprint(desired_eden_size);
- }
-
- if (PrintGC && PrintAdaptiveSizePolicy) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::compute_eden_space_size limits:"
- " desired_eden_size: " SIZE_FORMAT
- " old_eden_size: " SIZE_FORMAT,
- desired_eden_size, cur_eden);
- }
-
- set_eden_size(desired_eden_size);
-}
-
-size_t CMSAdaptiveSizePolicy::adjust_promo_for_pause_time(size_t cur_promo) {
- size_t change = 0;
- size_t desired_promo = cur_promo;
- // Move this test up to caller like the adjust_eden_for_pause_time()
- // call.
- if ((AdaptiveSizePausePolicy == 0) &&
- ((avg_remark_pause()->padded_average() > gc_pause_goal_sec()) ||
- (avg_initial_pause()->padded_average() > gc_pause_goal_sec()))) {
- set_change_old_gen_for_maj_pauses(decrease_old_gen_for_maj_pauses_true);
- change = promo_decrement_aligned_down(cur_promo);
- desired_promo = cur_promo - change;
- } else if ((AdaptiveSizePausePolicy > 0) &&
- (((avg_remark_pause()->padded_average() > gc_pause_goal_sec()) &&
- remark_pause_old_estimator()->decrement_will_decrease()) ||
- ((avg_initial_pause()->padded_average() > gc_pause_goal_sec()) &&
- initial_pause_old_estimator()->decrement_will_decrease()))) {
- set_change_old_gen_for_maj_pauses(decrease_old_gen_for_maj_pauses_true);
- change = promo_decrement_aligned_down(cur_promo);
- desired_promo = cur_promo - change;
- }
-
- if ((change != 0) &&PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::adjust_promo_for_pause_time "
- "adjusting promo for pause time. "
- " starting promo size " SIZE_FORMAT
- " reduced promo size " SIZE_FORMAT
- " promo delta " SIZE_FORMAT,
- cur_promo, desired_promo, change);
- }
-
- return desired_promo;
-}
-
-// Try to share this with PS.
-size_t CMSAdaptiveSizePolicy::scale_by_gen_gc_cost(size_t base_change,
- double gen_gc_cost) {
-
- // Calculate the change to use for the tenured gen.
- size_t scaled_change = 0;
- // Can the increment to the generation be scaled?
- if (gc_cost() >= 0.0 && gen_gc_cost >= 0.0) {
- double scale_by_ratio = gen_gc_cost / gc_cost();
- scaled_change =
- (size_t) (scale_by_ratio * (double) base_change);
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "Scaled tenured increment: " SIZE_FORMAT " by %f down to "
- SIZE_FORMAT,
- base_change, scale_by_ratio, scaled_change);
- }
- } else if (gen_gc_cost >= 0.0) {
- // Scaling is not going to work. If the major gc time is the
- // larger than the other GC costs, give it a full increment.
- if (gen_gc_cost >= (gc_cost() - gen_gc_cost)) {
- scaled_change = base_change;
- }
- } else {
- // Don't expect to get here but it's ok if it does
- // in the product build since the delta will be 0
- // and nothing will change.
- assert(false, "Unexpected value for gc costs");
- }
-
- return scaled_change;
-}
-
-size_t CMSAdaptiveSizePolicy::adjust_promo_for_throughput(size_t cur_promo) {
-
- size_t desired_promo = cur_promo;
-
- set_change_old_gen_for_throughput(increase_old_gen_for_throughput_true);
-
- size_t change = promo_increment_aligned_up(cur_promo);
- size_t scaled_change = scale_by_gen_gc_cost(change, major_gc_cost());
-
- if (cur_promo + scaled_change > cur_promo) {
- desired_promo = cur_promo + scaled_change;
- }
-
- _old_gen_change_for_major_throughput++;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::adjust_promo_for_throughput "
- "adjusting promo for throughput. "
- " starting promo size " SIZE_FORMAT
- " increased promo size " SIZE_FORMAT
- " promo delta " SIZE_FORMAT,
- cur_promo, desired_promo, scaled_change);
- }
-
- return desired_promo;
-}
-
-size_t CMSAdaptiveSizePolicy::adjust_promo_for_footprint(size_t cur_promo,
- size_t cur_eden) {
-
- set_decrease_for_footprint(decrease_young_gen_for_footprint_true);
-
- size_t change = promo_decrement(cur_promo);
- size_t desired_promo_size = cur_promo - change;
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::adjust_promo_for_footprint "
- "adjusting promo for footprint. "
- " starting promo size " SIZE_FORMAT
- " reduced promo size " SIZE_FORMAT
- " promo delta " SIZE_FORMAT,
- cur_promo, desired_promo_size, change);
- }
- return desired_promo_size;
-}
-
-void CMSAdaptiveSizePolicy::compute_tenured_generation_free_space(
- size_t cur_tenured_free,
- size_t max_tenured_available,
- size_t cur_eden) {
- // This can be bad if the desired value grows/shrinks without
- // any connection to the read free space
- size_t desired_promo_size = promo_size();
- size_t tenured_limit = max_tenured_available;
-
- // Printout input
- if (PrintGC && PrintAdaptiveSizePolicy) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::compute_tenured_generation_free_space: "
- "cur_tenured_free " SIZE_FORMAT
- " max_tenured_available " SIZE_FORMAT,
- cur_tenured_free, max_tenured_available);
- }
-
- // Used for diagnostics
- clear_generation_free_space_flags();
-
- set_decide_at_full_gc(decide_at_full_gc_true);
- if (avg_remark_pause()->padded_average() > gc_pause_goal_sec() ||
- avg_initial_pause()->padded_average() > gc_pause_goal_sec()) {
- desired_promo_size = adjust_promo_for_pause_time(cur_tenured_free);
- } else if (avg_minor_pause()->padded_average() > gc_pause_goal_sec()) {
- // Nothing to do since the minor collections are too large and
- // this method only deals with the cms generation.
- } else if ((cms_gc_cost() >= 0.0) &&
- (adjusted_mutator_cost() < _throughput_goal)) {
- desired_promo_size = adjust_promo_for_throughput(cur_tenured_free);
- } else {
- desired_promo_size = adjust_promo_for_footprint(cur_tenured_free,
- cur_eden);
- }
-
- if (PrintGC && PrintAdaptiveSizePolicy) {
- gclog_or_tty->print_cr(
- "CMSAdaptiveSizePolicy::compute_tenured_generation_free_space limits:"
- " desired_promo_size: " SIZE_FORMAT
- " old_promo_size: " SIZE_FORMAT,
- desired_promo_size, cur_tenured_free);
- }
-
- set_promo_size(desired_promo_size);
-}
-
-uint CMSAdaptiveSizePolicy::compute_survivor_space_size_and_threshold(
- bool is_survivor_overflow,
- uint tenuring_threshold,
- size_t survivor_limit) {
- assert(survivor_limit >= generation_alignment(),
- "survivor_limit too small");
- assert((size_t)align_size_down(survivor_limit, generation_alignment())
- == survivor_limit, "survivor_limit not aligned");
-
- // Change UsePSAdaptiveSurvivorSizePolicy -> UseAdaptiveSurvivorSizePolicy?
- if (!UsePSAdaptiveSurvivorSizePolicy ||
- !young_gen_policy_is_ready()) {
- return tenuring_threshold;
- }
-
- // We'll decide whether to increase or decrease the tenuring
- // threshold based partly on the newly computed survivor size
- // (if we hit the maximum limit allowed, we'll always choose to
- // decrement the threshold).
- bool incr_tenuring_threshold = false;
- bool decr_tenuring_threshold = false;
-
- set_decrement_tenuring_threshold_for_gc_cost(false);
- set_increment_tenuring_threshold_for_gc_cost(false);
- set_decrement_tenuring_threshold_for_survivor_limit(false);
-
- if (!is_survivor_overflow) {
- // Keep running averages on how much survived
-
- // We use the tenuring threshold to equalize the cost of major
- // and minor collections.
- // ThresholdTolerance is used to indicate how sensitive the
- // tenuring threshold is to differences in cost between the
- // collection types.
-
- // Get the times of interest. This involves a little work, so
- // we cache the values here.
- const double major_cost = major_gc_cost();
- const double minor_cost = minor_gc_cost();
-
- if (minor_cost > major_cost * _threshold_tolerance_percent) {
- // Minor times are getting too long; lower the threshold so
- // less survives and more is promoted.
- decr_tenuring_threshold = true;
- set_decrement_tenuring_threshold_for_gc_cost(true);
- } else if (major_cost > minor_cost * _threshold_tolerance_percent) {
- // Major times are too long, so we want less promotion.
- incr_tenuring_threshold = true;
- set_increment_tenuring_threshold_for_gc_cost(true);
- }
-
- } else {
- // Survivor space overflow occurred, so promoted and survived are
- // not accurate. We'll make our best guess by combining survived
- // and promoted and count them as survivors.
- //
- // We'll lower the tenuring threshold to see if we can correct
- // things. Also, set the survivor size conservatively. We're
- // trying to avoid many overflows from occurring if defnew size
- // is just too small.
-
- decr_tenuring_threshold = true;
- }
-
- // The padded average also maintains a deviation from the average;
- // we use this to see how good of an estimate we have of what survived.
- // We're trying to pad the survivor size as little as possible without
- // overflowing the survivor spaces.
- size_t target_size = align_size_up((size_t)_avg_survived->padded_average(),
- generation_alignment());
- target_size = MAX2(target_size, generation_alignment());
-
- if (target_size > survivor_limit) {
- // Target size is bigger than we can handle. Let's also reduce
- // the tenuring threshold.
- target_size = survivor_limit;
- decr_tenuring_threshold = true;
- set_decrement_tenuring_threshold_for_survivor_limit(true);
- }
-
- // Finally, increment or decrement the tenuring threshold, as decided above.
- // We test for decrementing first, as we might have hit the target size
- // limit.
- if (decr_tenuring_threshold && !(AlwaysTenure || NeverTenure)) {
- if (tenuring_threshold > 1) {
- tenuring_threshold--;
- }
- } else if (incr_tenuring_threshold && !(AlwaysTenure || NeverTenure)) {
- if (tenuring_threshold < MaxTenuringThreshold) {
- tenuring_threshold++;
- }
- }
-
- // We keep a running average of the amount promoted which is used
- // to decide when we should collect the old generation (when
- // the amount of old gen free space is less than what we expect to
- // promote).
-
- if (PrintAdaptiveSizePolicy) {
- // A little more detail if Verbose is on
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- if (Verbose) {
- gclog_or_tty->print( " avg_survived: %f"
- " avg_deviation: %f",
- _avg_survived->average(),
- _avg_survived->deviation());
- }
-
- gclog_or_tty->print( " avg_survived_padded_avg: %f",
- _avg_survived->padded_average());
-
- if (Verbose) {
- gclog_or_tty->print( " avg_promoted_avg: %f"
- " avg_promoted_dev: %f",
- gch->gc_stats(1)->avg_promoted()->average(),
- gch->gc_stats(1)->avg_promoted()->deviation());
- }
-
- gclog_or_tty->print( " avg_promoted_padded_avg: %f"
- " avg_pretenured_padded_avg: %f"
- " tenuring_thresh: %u"
- " target_size: " SIZE_FORMAT
- " survivor_limit: " SIZE_FORMAT,
- gch->gc_stats(1)->avg_promoted()->padded_average(),
- _avg_pretenured->padded_average(),
- tenuring_threshold, target_size, survivor_limit);
- gclog_or_tty->cr();
- }
-
- set_survivor_size(target_size);
-
- return tenuring_threshold;
-}
-
-bool CMSAdaptiveSizePolicy::get_and_clear_first_after_collection() {
- bool result = _first_after_collection;
- _first_after_collection = false;
- return result;
-}
-
-bool CMSAdaptiveSizePolicy::print_adaptive_size_policy_on(
- outputStream* st) const {
-
- if (!UseAdaptiveSizePolicy) {
- return false;
- }
-
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- Generation* young = gch->get_gen(0);
- DefNewGeneration* def_new = young->as_DefNewGeneration();
- return AdaptiveSizePolicy::print_adaptive_size_policy_on(
- st,
- def_new->tenuring_threshold());
-}
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,477 +0,0 @@
-/*
- * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSADAPTIVESIZEPOLICY_HPP
-#define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSADAPTIVESIZEPOLICY_HPP
-
-#include "gc_implementation/shared/adaptiveSizePolicy.hpp"
-#include "runtime/timer.hpp"
-
-// This class keeps statistical information and computes the
-// size of the heap for the concurrent mark sweep collector.
-//
-// Cost for garbage collector include cost for
-// minor collection
-// concurrent collection
-// stop-the-world component
-// concurrent component
-// major compacting collection
-// uses decaying cost
-
-// Forward decls
-class elapsedTimer;
-
-class CMSAdaptiveSizePolicy : public AdaptiveSizePolicy {
- friend class CMSGCAdaptivePolicyCounters;
- friend class CMSCollector;
- private:
-
- // Total number of processors available
- int _processor_count;
- // Number of processors used by the concurrent phases of GC
- // This number is assumed to be the same for all concurrent
- // phases.
- int _concurrent_processor_count;
-
- // Time that the mutators run exclusive of a particular
- // phase. For example, the time the mutators run excluding
- // the time during which the cms collector runs concurrently
- // with the mutators.
- // Between end of most recent cms reset and start of initial mark
- // This may be redundant
- double _latest_cms_reset_end_to_initial_mark_start_secs;
- // Between end of the most recent initial mark and start of remark
- double _latest_cms_initial_mark_end_to_remark_start_secs;
- // Between end of most recent collection and start of
- // a concurrent collection
- double _latest_cms_collection_end_to_collection_start_secs;
- // Times of the concurrent phases of the most recent
- // concurrent collection
- double _latest_cms_concurrent_marking_time_secs;
- double _latest_cms_concurrent_precleaning_time_secs;
- double _latest_cms_concurrent_sweeping_time_secs;
- // Between end of most recent STW MSC and start of next STW MSC
- double _latest_cms_msc_end_to_msc_start_time_secs;
- // Between end of most recent MS and start of next MS
- // This does not include any time spent during a concurrent
- // collection.
- double _latest_cms_ms_end_to_ms_start;
- // Between start and end of the initial mark of the most recent
- // concurrent collection.
- double _latest_cms_initial_mark_start_to_end_time_secs;
- // Between start and end of the remark phase of the most recent
- // concurrent collection
- double _latest_cms_remark_start_to_end_time_secs;
- // Between start and end of the most recent MS STW marking phase
- double _latest_cms_ms_marking_start_to_end_time_secs;
-
- // Pause time timers
- static elapsedTimer _STW_timer;
- // Concurrent collection timer. Used for total of all concurrent phases
- // during 1 collection cycle.
- static elapsedTimer _concurrent_timer;
-
- // When the size of the generation is changed, the size
- // of the change will rounded up or down (depending on the
- // type of change) by this value.
- size_t _generation_alignment;
-
- // If this variable is true, the size of the young generation
- // may be changed in order to reduce the pause(s) of the
- // collection of the tenured generation in order to meet the
- // pause time goal. It is common to change the size of the
- // tenured generation in order to meet the pause time goal
- // for the tenured generation. With the CMS collector for
- // the tenured generation, the size of the young generation
- // can have an significant affect on the pause times for collecting the
- // tenured generation.
- // This is a duplicate of a variable in PSAdaptiveSizePolicy. It
- // is duplicated because it is not clear that it is general enough
- // to go into AdaptiveSizePolicy.
- int _change_young_gen_for_maj_pauses;
-
- // Variable that is set to true after a collection.
- bool _first_after_collection;
-
- // Fraction of collections that are of each type
- double concurrent_fraction() const;
- double STW_msc_fraction() const;
- double STW_ms_fraction() const;
-
- // This call cannot be put into the epilogue as long as some
- // of the counters can be set during concurrent phases.
- virtual void clear_generation_free_space_flags();
-
- void set_first_after_collection() { _first_after_collection = true; }
-
- protected:
- // Average of the sum of the concurrent times for
- // one collection in seconds.
- AdaptiveWeightedAverage* _avg_concurrent_time;
- // Average time between concurrent collections in seconds.
- AdaptiveWeightedAverage* _avg_concurrent_interval;
- // Average cost of the concurrent part of a collection
- // in seconds.
- AdaptiveWeightedAverage* _avg_concurrent_gc_cost;
-
- // Average of the initial pause of a concurrent collection in seconds.
- AdaptivePaddedAverage* _avg_initial_pause;
- // Average of the remark pause of a concurrent collection in seconds.
- AdaptivePaddedAverage* _avg_remark_pause;
-
- // Average of the stop-the-world (STW) (initial mark + remark)
- // times in seconds for concurrent collections.
- AdaptiveWeightedAverage* _avg_cms_STW_time;
- // Average of the STW collection cost for concurrent collections.
- AdaptiveWeightedAverage* _avg_cms_STW_gc_cost;
-
- // Average of the bytes free at the start of the sweep.
- AdaptiveWeightedAverage* _avg_cms_free_at_sweep;
- // Average of the bytes free at the end of the collection.
- AdaptiveWeightedAverage* _avg_cms_free;
- // Average of the bytes promoted between cms collections.
- AdaptiveWeightedAverage* _avg_cms_promo;
-
- // stop-the-world (STW) mark-sweep-compact
- // Average of the pause time in seconds for STW mark-sweep-compact
- // collections.
- AdaptiveWeightedAverage* _avg_msc_pause;
- // Average of the interval in seconds between STW mark-sweep-compact
- // collections.
- AdaptiveWeightedAverage* _avg_msc_interval;
- // Average of the collection costs for STW mark-sweep-compact
- // collections.
- AdaptiveWeightedAverage* _avg_msc_gc_cost;
-
- // Averages for mark-sweep collections.
- // The collection may have started as a background collection
- // that completes in a stop-the-world (STW) collection.
- // Average of the pause time in seconds for mark-sweep
- // collections.
- AdaptiveWeightedAverage* _avg_ms_pause;
- // Average of the interval in seconds between mark-sweep
- // collections.
- AdaptiveWeightedAverage* _avg_ms_interval;
- // Average of the collection costs for mark-sweep
- // collections.
- AdaptiveWeightedAverage* _avg_ms_gc_cost;
-
- // These variables contain a linear fit of
- // a generation size as the independent variable
- // and a pause time as the dependent variable.
- // For example _remark_pause_old_estimator
- // is a fit of the old generation size as the
- // independent variable and the remark pause
- // as the dependent variable.
- // remark pause time vs. cms gen size
- LinearLeastSquareFit* _remark_pause_old_estimator;
- // initial pause time vs. cms gen size
- LinearLeastSquareFit* _initial_pause_old_estimator;
- // remark pause time vs. young gen size
- LinearLeastSquareFit* _remark_pause_young_estimator;
- // initial pause time vs. young gen size
- LinearLeastSquareFit* _initial_pause_young_estimator;
-
- // Accessors
- int processor_count() const { return _processor_count; }
- int concurrent_processor_count() const { return _concurrent_processor_count; }
-
- AdaptiveWeightedAverage* avg_concurrent_time() const {
- return _avg_concurrent_time;
- }
-
- AdaptiveWeightedAverage* avg_concurrent_interval() const {
- return _avg_concurrent_interval;
- }
-
- AdaptiveWeightedAverage* avg_concurrent_gc_cost() const {
- return _avg_concurrent_gc_cost;
- }
-
- AdaptiveWeightedAverage* avg_cms_STW_time() const {
- return _avg_cms_STW_time;
- }
-
- AdaptiveWeightedAverage* avg_cms_STW_gc_cost() const {
- return _avg_cms_STW_gc_cost;
- }
-
- AdaptivePaddedAverage* avg_initial_pause() const {
- return _avg_initial_pause;
- }
-
- AdaptivePaddedAverage* avg_remark_pause() const {
- return _avg_remark_pause;
- }
-
- AdaptiveWeightedAverage* avg_cms_free() const {
- return _avg_cms_free;
- }
-
- AdaptiveWeightedAverage* avg_cms_free_at_sweep() const {
- return _avg_cms_free_at_sweep;
- }
-
- AdaptiveWeightedAverage* avg_msc_pause() const {
- return _avg_msc_pause;
- }
-
- AdaptiveWeightedAverage* avg_msc_interval() const {
- return _avg_msc_interval;
- }
-
- AdaptiveWeightedAverage* avg_msc_gc_cost() const {
- return _avg_msc_gc_cost;
- }
-
- AdaptiveWeightedAverage* avg_ms_pause() const {
- return _avg_ms_pause;
- }
-
- AdaptiveWeightedAverage* avg_ms_interval() const {
- return _avg_ms_interval;
- }
-
- AdaptiveWeightedAverage* avg_ms_gc_cost() const {
- return _avg_ms_gc_cost;
- }
-
- LinearLeastSquareFit* remark_pause_old_estimator() {
- return _remark_pause_old_estimator;
- }
- LinearLeastSquareFit* initial_pause_old_estimator() {
- return _initial_pause_old_estimator;
- }
- LinearLeastSquareFit* remark_pause_young_estimator() {
- return _remark_pause_young_estimator;
- }
- LinearLeastSquareFit* initial_pause_young_estimator() {
- return _initial_pause_young_estimator;
- }
-
- // These *slope() methods return the slope
- // m for the linear fit of an independent
- // variable vs. a dependent variable. For
- // example
- // remark_pause = m * old_generation_size + c
- // These may be used to determine if an
- // adjustment should be made to achieve a goal.
- // For example, if remark_pause_old_slope() is
- // positive, a reduction of the old generation
- // size has on average resulted in the reduction
- // of the remark pause.
- float remark_pause_old_slope() {
- return _remark_pause_old_estimator->slope();
- }
-
- float initial_pause_old_slope() {
- return _initial_pause_old_estimator->slope();
- }
-
- float remark_pause_young_slope() {
- return _remark_pause_young_estimator->slope();
- }
-
- float initial_pause_young_slope() {
- return _initial_pause_young_estimator->slope();
- }
-
- // Update estimators
- void update_minor_pause_old_estimator(double minor_pause_in_ms);
-
- // Fraction of processors used by the concurrent phases.
- double concurrent_processor_fraction();
-
- // Returns the total times for the concurrent part of the
- // latest collection in seconds.
- double concurrent_collection_time();
-
- // Return the total times for the concurrent part of the
- // latest collection in seconds where the times of the various
- // concurrent phases are scaled by the processor fraction used
- // during the phase.
- double scaled_concurrent_collection_time();
-
- // Dimensionless concurrent GC cost for all the concurrent phases.
- double concurrent_collection_cost(double interval_in_seconds);
-
- // Dimensionless GC cost
- double collection_cost(double pause_in_seconds, double interval_in_seconds);
-
- virtual GCPolicyKind kind() const { return _gc_cms_adaptive_size_policy; }
-
- virtual double time_since_major_gc() const;
-
- // This returns the maximum average for the concurrent, ms, and
- // msc collections. This is meant to be used for the calculation
- // of the decayed major gc cost and is not in general the
- // average of all the different types of major collections.
- virtual double major_gc_interval_average_for_decay() const;
-
- public:
- CMSAdaptiveSizePolicy(size_t init_eden_size,
- size_t init_promo_size,
- size_t init_survivor_size,
- double max_gc_minor_pause_sec,
- double max_gc_pause_sec,
- uint gc_cost_ratio);
-
- // The timers for the stop-the-world phases measure a total
- // stop-the-world time. The timer is started and stopped
- // for each phase but is only reset after the final checkpoint.
- void checkpoint_roots_initial_begin();
- void checkpoint_roots_initial_end(GCCause::Cause gc_cause);
- void checkpoint_roots_final_begin();
- void checkpoint_roots_final_end(GCCause::Cause gc_cause);
-
- // Methods for gathering information about the
- // concurrent marking phase of the collection.
- // Records the mutator times and
- // resets the concurrent timer.
- void concurrent_marking_begin();
- // Resets concurrent phase timer in the begin methods and
- // saves the time for a phase in the end methods.
- void concurrent_marking_end();
- void concurrent_sweeping_begin();
- void concurrent_sweeping_end();
- // Similar to the above (e.g., concurrent_marking_end()) and
- // is used for both the precleaning an abortable precleaning
- // phases.
- void concurrent_precleaning_begin();
- void concurrent_precleaning_end();
- // Stops the concurrent phases time. Gathers
- // information and resets the timer.
- void concurrent_phases_end(GCCause::Cause gc_cause,
- size_t cur_eden,
- size_t cur_promo);
-
- // Methods for gather information about STW Mark-Sweep-Compact
- void msc_collection_begin();
- void msc_collection_end(GCCause::Cause gc_cause);
-
- // Methods for gather information about Mark-Sweep done
- // in the foreground.
- void ms_collection_begin();
- void ms_collection_end(GCCause::Cause gc_cause);
-
- // Cost for a mark-sweep tenured gen collection done in the foreground
- double ms_gc_cost() const {
- return MAX2(0.0F, _avg_ms_gc_cost->average());
- }
-
- // Cost of collecting the tenured generation. Includes
- // concurrent collection and STW collection costs
- double cms_gc_cost() const;
-
- // Cost of STW mark-sweep-compact tenured gen collection.
- double msc_gc_cost() const {
- return MAX2(0.0F, _avg_msc_gc_cost->average());
- }
-
- //
- double compacting_gc_cost() const {
- double result = MIN2(1.0, minor_gc_cost() + msc_gc_cost());
- assert(result >= 0.0, "Both minor and major costs are non-negative");
- return result;
- }
-
- // Restarts the concurrent phases timer.
- void concurrent_phases_resume();
-
- // Time beginning and end of the marking phase for
- // a synchronous MS collection. A MS collection
- // that finishes in the foreground can have started
- // in the background. These methods capture the
- // completion of the marking (after the initial
- // marking) that is done in the foreground.
- void ms_collection_marking_begin();
- void ms_collection_marking_end(GCCause::Cause gc_cause);
-
- static elapsedTimer* concurrent_timer_ptr() {
- return &_concurrent_timer;
- }
-
- AdaptiveWeightedAverage* avg_cms_promo() const {
- return _avg_cms_promo;
- }
-
- int change_young_gen_for_maj_pauses() {
- return _change_young_gen_for_maj_pauses;
- }
- void set_change_young_gen_for_maj_pauses(int v) {
- _change_young_gen_for_maj_pauses = v;
- }
-
- void clear_internal_time_intervals();
-
-
- // Either calculated_promo_size_in_bytes() or promo_size()
- // should be deleted.
- size_t promo_size() { return _promo_size; }
- void set_promo_size(size_t v) { _promo_size = v; }
-
- // Cost of GC for all types of collections.
- virtual double gc_cost() const;
-
- size_t generation_alignment() { return _generation_alignment; }
-
- virtual void compute_eden_space_size(size_t cur_eden,
- size_t max_eden_size);
- // Calculates new survivor space size; returns a new tenuring threshold
- // value. Stores new survivor size in _survivor_size.
- virtual uint compute_survivor_space_size_and_threshold(
- bool is_survivor_overflow,
- uint tenuring_threshold,
- size_t survivor_limit);
-
- virtual void compute_tenured_generation_free_space(size_t cur_tenured_free,
- size_t max_tenured_available,
- size_t cur_eden);
-
- size_t eden_decrement_aligned_down(size_t cur_eden);
- size_t eden_increment_aligned_up(size_t cur_eden);
-
- size_t adjust_eden_for_pause_time(size_t cur_eden);
- size_t adjust_eden_for_throughput(size_t cur_eden);
- size_t adjust_eden_for_footprint(size_t cur_eden);
-
- size_t promo_decrement_aligned_down(size_t cur_promo);
- size_t promo_increment_aligned_up(size_t cur_promo);
-
- size_t adjust_promo_for_pause_time(size_t cur_promo);
- size_t adjust_promo_for_throughput(size_t cur_promo);
- size_t adjust_promo_for_footprint(size_t cur_promo, size_t cur_eden);
-
- // Scale down the input size by the ratio of the cost to collect the
- // generation to the total GC cost.
- size_t scale_by_gen_gc_cost(size_t base_change, double gen_gc_cost);
-
- // Return the value and clear it.
- bool get_and_clear_first_after_collection();
-
- // Printing support
- virtual bool print_adaptive_size_policy_on(outputStream* st) const;
-};
-
-#endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSADAPTIVESIZEPOLICY_HPP
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -23,9 +23,8 @@
*/
#include "precompiled.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
+#include "gc_implementation/shared/adaptiveSizePolicy.hpp"
#include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
#include "gc_implementation/parNew/parNewGeneration.hpp"
#include "gc_implementation/shared/gcPolicyCounters.hpp"
#include "gc_implementation/shared/vmGCOperations.hpp"
@@ -57,25 +56,12 @@
if (_generations == NULL)
vm_exit_during_initialization("Unable to allocate gen spec");
- if (UseParNewGC) {
- if (UseAdaptiveSizePolicy) {
- _generations[0] = new GenerationSpec(Generation::ASParNew,
- _initial_young_size, _max_young_size);
- } else {
- _generations[0] = new GenerationSpec(Generation::ParNew,
- _initial_young_size, _max_young_size);
- }
- } else {
- _generations[0] = new GenerationSpec(Generation::DefNew,
- _initial_young_size, _max_young_size);
- }
- if (UseAdaptiveSizePolicy) {
- _generations[1] = new GenerationSpec(Generation::ASConcurrentMarkSweep,
- _initial_old_size, _max_old_size);
- } else {
- _generations[1] = new GenerationSpec(Generation::ConcurrentMarkSweep,
- _initial_old_size, _max_old_size);
- }
+ Generation::Name yg_name =
+ UseParNewGC ? Generation::ParNew : Generation::DefNew;
+ _generations[0] = new GenerationSpec(yg_name, _initial_young_size,
+ _max_young_size);
+ _generations[1] = new GenerationSpec(Generation::ConcurrentMarkSweep,
+ _initial_old_size, _max_old_size);
if (_generations[0] == NULL || _generations[1] == NULL) {
vm_exit_during_initialization("Unable to allocate gen spec");
@@ -85,14 +71,12 @@
void ConcurrentMarkSweepPolicy::initialize_size_policy(size_t init_eden_size,
size_t init_promo_size,
size_t init_survivor_size) {
- double max_gc_minor_pause_sec = ((double) MaxGCMinorPauseMillis)/1000.0;
double max_gc_pause_sec = ((double) MaxGCPauseMillis)/1000.0;
- _size_policy = new CMSAdaptiveSizePolicy(init_eden_size,
- init_promo_size,
- init_survivor_size,
- max_gc_minor_pause_sec,
- max_gc_pause_sec,
- GCTimeRatio);
+ _size_policy = new AdaptiveSizePolicy(init_eden_size,
+ init_promo_size,
+ init_survivor_size,
+ max_gc_pause_sec,
+ GCTimeRatio);
}
void ConcurrentMarkSweepPolicy::initialize_gc_policy_counters() {
@@ -110,22 +94,3 @@
{
return CMSIncrementalMode;
}
-
-
-//
-// ASConcurrentMarkSweepPolicy methods
-//
-
-void ASConcurrentMarkSweepPolicy::initialize_gc_policy_counters() {
-
- assert(size_policy() != NULL, "A size policy is required");
- // initialize the policy counters - 2 collectors, 3 generations
- if (UseParNewGC) {
- _gc_policy_counters = new CMSGCAdaptivePolicyCounters("ParNew:CMS", 2, 3,
- size_policy());
- }
- else {
- _gc_policy_counters = new CMSGCAdaptivePolicyCounters("Copy:CMS", 2, 3,
- size_policy());
- }
-}
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -47,19 +47,4 @@
virtual bool has_soft_ended_eden();
};
-class ASConcurrentMarkSweepPolicy : public ConcurrentMarkSweepPolicy {
- public:
-
- // Initialize the jstat counters. This method requires a
- // size policy. The size policy is expected to be created
- // after the generations are fully initialized so the
- // initialization of the counters need to be done post
- // the initialization of the generations.
- void initialize_gc_policy_counters();
-
- virtual CollectorPolicy::Name kind() {
- return CollectorPolicy::ASConcurrentMarkSweepPolicyKind;
- }
-};
-
#endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSCOLLECTORPOLICY_HPP
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.cpp Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,303 +0,0 @@
-/*
- * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
-#include "memory/resourceArea.hpp"
-
-CMSGCAdaptivePolicyCounters::CMSGCAdaptivePolicyCounters(const char* name_arg,
- int collectors,
- int generations,
- AdaptiveSizePolicy* size_policy_arg)
- : GCAdaptivePolicyCounters(name_arg,
- collectors,
- generations,
- size_policy_arg) {
- if (UsePerfData) {
- EXCEPTION_MARK;
- ResourceMark rm;
-
- const char* cname =
- PerfDataManager::counter_name(name_space(), "cmsCapacity");
- _cms_capacity_counter = PerfDataManager::create_variable(SUN_GC, cname,
- PerfData::U_Bytes, (jlong) OldSize, CHECK);
-#ifdef NOT_PRODUCT
- cname =
- PerfDataManager::counter_name(name_space(), "initialPause");
- _initial_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_initial_pause()->last_sample(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "remarkPause");
- _remark_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_remark_pause()->last_sample(),
- CHECK);
-#endif
- cname =
- PerfDataManager::counter_name(name_space(), "avgInitialPause");
- _avg_initial_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_initial_pause()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgRemarkPause");
- _avg_remark_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_remark_pause()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgSTWGcCost");
- _avg_cms_STW_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_cms_STW_gc_cost()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgSTWTime");
- _avg_cms_STW_time_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_cms_STW_time()->average(),
- CHECK);
-
-
- cname = PerfDataManager::counter_name(name_space(), "avgConcurrentTime");
- _avg_concurrent_time_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_concurrent_time()->average(),
- CHECK);
-
- cname =
- PerfDataManager::counter_name(name_space(), "avgConcurrentInterval");
- _avg_concurrent_interval_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_concurrent_interval()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgConcurrentGcCost");
- _avg_concurrent_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_concurrent_gc_cost()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgCMSFreeAtSweep");
- _avg_cms_free_at_sweep_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_cms_free_at_sweep()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgCMSFree");
- _avg_cms_free_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_cms_free()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgCMSPromo");
- _avg_cms_promo_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_cms_promo()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgMscPause");
- _avg_msc_pause_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_msc_pause()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgMscInterval");
- _avg_msc_interval_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_msc_interval()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "mscGcCost");
- _msc_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_msc_gc_cost()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgMsPause");
- _avg_ms_pause_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_ms_pause()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgMsInterval");
- _avg_ms_interval_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_ms_interval()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "msGcCost");
- _ms_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
- cname,
- PerfData::U_Ticks,
- (jlong) cms_size_policy()->avg_ms_gc_cost()->average(),
- CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "majorGcCost");
- _major_gc_cost_counter = PerfDataManager::create_variable(SUN_GC, cname,
- PerfData::U_Ticks, (jlong) cms_size_policy()->cms_gc_cost(), CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgPromotedAvg");
- _promoted_avg_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- cms_size_policy()->calculated_promo_size_in_bytes(), CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgPromotedDev");
- _promoted_avg_dev_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- (jlong) 0 , CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "avgPromotedPaddedAvg");
- _promoted_padded_avg_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- cms_size_policy()->calculated_promo_size_in_bytes(), CHECK);
-
- cname = PerfDataManager::counter_name(name_space(),
- "changeYoungGenForMajPauses");
- _change_young_gen_for_maj_pauses_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Events,
- (jlong)0, CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "remarkPauseOldSlope");
- _remark_pause_old_slope_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- (jlong) cms_size_policy()->remark_pause_old_slope(), CHECK);
-
- cname = PerfDataManager::counter_name(name_space(), "initialPauseOldSlope");
- _initial_pause_old_slope_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- (jlong) cms_size_policy()->initial_pause_old_slope(), CHECK);
-
- cname =
- PerfDataManager::counter_name(name_space(), "remarkPauseYoungSlope") ;
- _remark_pause_young_slope_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- (jlong) cms_size_policy()->remark_pause_young_slope(), CHECK);
-
- cname =
- PerfDataManager::counter_name(name_space(), "initialPauseYoungSlope");
- _initial_pause_young_slope_counter =
- PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
- (jlong) cms_size_policy()->initial_pause_young_slope(), CHECK);
-
-
- }
- assert(size_policy()->is_gc_cms_adaptive_size_policy(),
- "Wrong type of size policy");
-}
-
-void CMSGCAdaptivePolicyCounters::update_counters() {
- if (UsePerfData) {
- GCAdaptivePolicyCounters::update_counters_from_policy();
- update_counters_from_policy();
- }
-}
-
-void CMSGCAdaptivePolicyCounters::update_counters(CMSGCStats* gc_stats) {
- if (UsePerfData) {
- update_counters();
- update_promoted((size_t) gc_stats->avg_promoted()->last_sample());
- update_avg_promoted_avg(gc_stats);
- update_avg_promoted_dev(gc_stats);
- update_avg_promoted_padded_avg(gc_stats);
- }
-}
-
-void CMSGCAdaptivePolicyCounters::update_counters_from_policy() {
- if (UsePerfData && (cms_size_policy() != NULL)) {
-
- GCAdaptivePolicyCounters::update_counters_from_policy();
-
- update_major_gc_cost_counter();
- update_mutator_cost_counter();
-
- update_eden_size();
- update_promo_size();
-
- // If these updates from the last_sample() work,
- // revise the update methods for these counters
- // (both here and in PS).
- update_survived((size_t) cms_size_policy()->avg_survived()->last_sample());
-
- update_avg_concurrent_time_counter();
- update_avg_concurrent_interval_counter();
- update_avg_concurrent_gc_cost_counter();
-#ifdef NOT_PRODUCT
- update_initial_pause_counter();
- update_remark_pause_counter();
-#endif
- update_avg_initial_pause_counter();
- update_avg_remark_pause_counter();
-
- update_avg_cms_STW_time_counter();
- update_avg_cms_STW_gc_cost_counter();
-
- update_avg_cms_free_counter();
- update_avg_cms_free_at_sweep_counter();
- update_avg_cms_promo_counter();
-
- update_avg_msc_pause_counter();
- update_avg_msc_interval_counter();
- update_msc_gc_cost_counter();
-
- update_avg_ms_pause_counter();
- update_avg_ms_interval_counter();
- update_ms_gc_cost_counter();
-
- update_avg_old_live_counter();
-
- update_survivor_size_counters();
- update_avg_survived_avg_counters();
- update_avg_survived_dev_counters();
-
- update_decrement_tenuring_threshold_for_gc_cost();
- update_increment_tenuring_threshold_for_gc_cost();
- update_decrement_tenuring_threshold_for_survivor_limit();
-
- update_change_young_gen_for_maj_pauses();
-
- update_major_collection_slope_counter();
- update_remark_pause_old_slope_counter();
- update_initial_pause_old_slope_counter();
- update_remark_pause_young_slope_counter();
- update_initial_pause_young_slope_counter();
-
- update_decide_at_full_gc_counter();
- }
-}
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,308 +0,0 @@
-/*
- * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSGCADAPTIVEPOLICYCOUNTERS_HPP
-#define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSGCADAPTIVEPOLICYCOUNTERS_HPP
-
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
-#include "gc_implementation/shared/gcAdaptivePolicyCounters.hpp"
-#include "gc_implementation/shared/gcStats.hpp"
-#include "runtime/perfData.hpp"
-
-// CMSGCAdaptivePolicyCounters is a holder class for performance counters
-// that track the data and decisions for the ergonomics policy for the
-// concurrent mark sweep collector
-
-class CMSGCAdaptivePolicyCounters : public GCAdaptivePolicyCounters {
- friend class VMStructs;
-
- private:
-
- // Capacity of tenured generation recorded at the end of
- // any collection.
- PerfVariable* _cms_capacity_counter; // Make this common with PS _old_capacity
-
- // Average stop-the-world pause time for both initial and
- // remark pauses sampled at the end of the checkpointRootsFinalWork.
- PerfVariable* _avg_cms_STW_time_counter;
- // Average stop-the-world (STW) GC cost for the STW pause time
- // _avg_cms_STW_time_counter.
- PerfVariable* _avg_cms_STW_gc_cost_counter;
-
-#ifdef NOT_PRODUCT
- // These are useful to see how the most recent values of these
- // counters compare to their respective averages but
- // do not control behavior.
- PerfVariable* _initial_pause_counter;
- PerfVariable* _remark_pause_counter;
-#endif
-
- // Average of the initial marking pause for a concurrent collection.
- PerfVariable* _avg_initial_pause_counter;
- // Average of the remark pause for a concurrent collection.
- PerfVariable* _avg_remark_pause_counter;
-
- // Average for the sum of all the concurrent times per collection.
- PerfVariable* _avg_concurrent_time_counter;
- // Average for the time between the most recent end of a
- // concurrent collection and the beginning of the next
- // concurrent collection.
- PerfVariable* _avg_concurrent_interval_counter;
- // Average of the concurrent GC costs based on _avg_concurrent_time_counter
- // and _avg_concurrent_interval_counter.
- PerfVariable* _avg_concurrent_gc_cost_counter;
-
- // Average of the free space in the tenured generation at the
- // end of the sweep of the tenured generation.
- PerfVariable* _avg_cms_free_counter;
- // Average of the free space in the tenured generation at the
- // start of the sweep of the tenured generation.
- PerfVariable* _avg_cms_free_at_sweep_counter;
- // Average of the free space in the tenured generation at the
- // after any resizing of the tenured generation at the end
- // of a collection of the tenured generation.
- PerfVariable* _avg_cms_promo_counter;
-
- // Average of the mark-sweep-compact (MSC) pause time for a collection
- // of the tenured generation.
- PerfVariable* _avg_msc_pause_counter;
- // Average for the time between the most recent end of a
- // MSC collection and the beginning of the next MSC collection.
- PerfVariable* _avg_msc_interval_counter;
- // Average for the GC cost of a MSC collection based on
- // _avg_msc_pause_counter and _avg_msc_interval_counter.
- PerfVariable* _msc_gc_cost_counter;
-
- // Average of the mark-sweep (MS) pause time for a collection
- // of the tenured generation.
- PerfVariable* _avg_ms_pause_counter;
- // Average for the time between the most recent end of a
- // MS collection and the beginning of the next MS collection.
- PerfVariable* _avg_ms_interval_counter;
- // Average for the GC cost of a MS collection based on
- // _avg_ms_pause_counter and _avg_ms_interval_counter.
- PerfVariable* _ms_gc_cost_counter;
-
- // Average of the bytes promoted per minor collection.
- PerfVariable* _promoted_avg_counter;
- // Average of the deviation of the promoted average.
- PerfVariable* _promoted_avg_dev_counter;
- // Padded average of the bytes promoted per minor collection.
- PerfVariable* _promoted_padded_avg_counter;
-
- // See description of the _change_young_gen_for_maj_pauses
- // variable recently in cmsAdaptiveSizePolicy.hpp.
- PerfVariable* _change_young_gen_for_maj_pauses_counter;
-
- // See descriptions of _remark_pause_old_slope, _initial_pause_old_slope,
- // etc. variables recently in cmsAdaptiveSizePolicy.hpp.
- PerfVariable* _remark_pause_old_slope_counter;
- PerfVariable* _initial_pause_old_slope_counter;
- PerfVariable* _remark_pause_young_slope_counter;
- PerfVariable* _initial_pause_young_slope_counter;
-
- CMSAdaptiveSizePolicy* cms_size_policy() {
- assert(_size_policy->kind() ==
- AdaptiveSizePolicy::_gc_cms_adaptive_size_policy,
- "Wrong size policy");
- return (CMSAdaptiveSizePolicy*)_size_policy;
- }
-
- inline void update_avg_cms_STW_time_counter() {
- _avg_cms_STW_time_counter->set_value(
- (jlong) (cms_size_policy()->avg_cms_STW_time()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_avg_cms_STW_gc_cost_counter() {
- _avg_cms_STW_gc_cost_counter->set_value(
- (jlong) (cms_size_policy()->avg_cms_STW_gc_cost()->average() * 100.0));
- }
-
- inline void update_avg_initial_pause_counter() {
- _avg_initial_pause_counter->set_value(
- (jlong) (cms_size_policy()->avg_initial_pause()->average() *
- (double) MILLIUNITS));
- }
-#ifdef NOT_PRODUCT
- inline void update_avg_remark_pause_counter() {
- _avg_remark_pause_counter->set_value(
- (jlong) (cms_size_policy()-> avg_remark_pause()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_initial_pause_counter() {
- _initial_pause_counter->set_value(
- (jlong) (cms_size_policy()->avg_initial_pause()->average() *
- (double) MILLIUNITS));
- }
-#endif
- inline void update_remark_pause_counter() {
- _remark_pause_counter->set_value(
- (jlong) (cms_size_policy()-> avg_remark_pause()->last_sample() *
- (double) MILLIUNITS));
- }
-
- inline void update_avg_concurrent_time_counter() {
- _avg_concurrent_time_counter->set_value(
- (jlong) (cms_size_policy()->avg_concurrent_time()->last_sample() *
- (double) MILLIUNITS));
- }
-
- inline void update_avg_concurrent_interval_counter() {
- _avg_concurrent_interval_counter->set_value(
- (jlong) (cms_size_policy()->avg_concurrent_interval()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_avg_concurrent_gc_cost_counter() {
- _avg_concurrent_gc_cost_counter->set_value(
- (jlong) (cms_size_policy()->avg_concurrent_gc_cost()->average() * 100.0));
- }
-
- inline void update_avg_cms_free_counter() {
- _avg_cms_free_counter->set_value(
- (jlong) cms_size_policy()->avg_cms_free()->average());
- }
-
- inline void update_avg_cms_free_at_sweep_counter() {
- _avg_cms_free_at_sweep_counter->set_value(
- (jlong) cms_size_policy()->avg_cms_free_at_sweep()->average());
- }
-
- inline void update_avg_cms_promo_counter() {
- _avg_cms_promo_counter->set_value(
- (jlong) cms_size_policy()->avg_cms_promo()->average());
- }
-
- inline void update_avg_old_live_counter() {
- _avg_old_live_counter->set_value(
- (jlong)(cms_size_policy()->avg_old_live()->average())
- );
- }
-
- inline void update_avg_msc_pause_counter() {
- _avg_msc_pause_counter->set_value(
- (jlong) (cms_size_policy()->avg_msc_pause()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_avg_msc_interval_counter() {
- _avg_msc_interval_counter->set_value(
- (jlong) (cms_size_policy()->avg_msc_interval()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_msc_gc_cost_counter() {
- _msc_gc_cost_counter->set_value(
- (jlong) (cms_size_policy()->avg_msc_gc_cost()->average() * 100.0));
- }
-
- inline void update_avg_ms_pause_counter() {
- _avg_ms_pause_counter->set_value(
- (jlong) (cms_size_policy()->avg_ms_pause()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_avg_ms_interval_counter() {
- _avg_ms_interval_counter->set_value(
- (jlong) (cms_size_policy()->avg_ms_interval()->average() *
- (double) MILLIUNITS));
- }
-
- inline void update_ms_gc_cost_counter() {
- _ms_gc_cost_counter->set_value(
- (jlong) (cms_size_policy()->avg_ms_gc_cost()->average() * 100.0));
- }
-
- inline void update_major_gc_cost_counter() {
- _major_gc_cost_counter->set_value(
- (jlong)(cms_size_policy()->cms_gc_cost() * 100.0)
- );
- }
- inline void update_mutator_cost_counter() {
- _mutator_cost_counter->set_value(
- (jlong)(cms_size_policy()->mutator_cost() * 100.0)
- );
- }
-
- inline void update_avg_promoted_avg(CMSGCStats* gc_stats) {
- _promoted_avg_counter->set_value(
- (jlong)(gc_stats->avg_promoted()->average())
- );
- }
- inline void update_avg_promoted_dev(CMSGCStats* gc_stats) {
- _promoted_avg_dev_counter->set_value(
- (jlong)(gc_stats->avg_promoted()->deviation())
- );
- }
- inline void update_avg_promoted_padded_avg(CMSGCStats* gc_stats) {
- _promoted_padded_avg_counter->set_value(
- (jlong)(gc_stats->avg_promoted()->padded_average())
- );
- }
- inline void update_remark_pause_old_slope_counter() {
- _remark_pause_old_slope_counter->set_value(
- (jlong)(cms_size_policy()->remark_pause_old_slope() * 1000)
- );
- }
- inline void update_initial_pause_old_slope_counter() {
- _initial_pause_old_slope_counter->set_value(
- (jlong)(cms_size_policy()->initial_pause_old_slope() * 1000)
- );
- }
- inline void update_remark_pause_young_slope_counter() {
- _remark_pause_young_slope_counter->set_value(
- (jlong)(cms_size_policy()->remark_pause_young_slope() * 1000)
- );
- }
- inline void update_initial_pause_young_slope_counter() {
- _initial_pause_young_slope_counter->set_value(
- (jlong)(cms_size_policy()->initial_pause_young_slope() * 1000)
- );
- }
- inline void update_change_young_gen_for_maj_pauses() {
- _change_young_gen_for_maj_pauses_counter->set_value(
- cms_size_policy()->change_young_gen_for_maj_pauses());
- }
-
- public:
- CMSGCAdaptivePolicyCounters(const char* name, int collectors, int generations,
- AdaptiveSizePolicy* size_policy);
-
- // update counters
- void update_counters();
- void update_counters(CMSGCStats* gc_stats);
- void update_counters_from_policy();
-
- inline void update_cms_capacity_counter(size_t size_in_bytes) {
- _cms_capacity_counter->set_value(size_in_bytes);
- }
-
- virtual GCPolicyCounters::Name kind() const {
- return GCPolicyCounters::CMSGCAdaptivePolicyCountersKind;
- }
-};
-
-#endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSGCADAPTIVEPOLICYCOUNTERS_HPP
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -70,7 +70,6 @@
class CompactibleFreeListSpace: public CompactibleSpace {
friend class VMStructs;
friend class ConcurrentMarkSweepGeneration;
- friend class ASConcurrentMarkSweepGeneration;
friend class CMSCollector;
// Local alloc buffer for promotion into this space.
friend class CFLS_LAB;
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -27,9 +27,8 @@
#include "classfile/stringTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/codeCache.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
+#include "gc_implementation/shared/adaptiveSizePolicy.hpp"
#include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
#include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
#include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp"
@@ -319,26 +318,12 @@
}
}
-CMSAdaptiveSizePolicy* CMSCollector::size_policy() {
+AdaptiveSizePolicy* CMSCollector::size_policy() {
GenCollectedHeap* gch = GenCollectedHeap::heap();
assert(gch->kind() == CollectedHeap::GenCollectedHeap,
"Wrong type of heap");
- CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
- gch->gen_policy()->size_policy();
- assert(sp->is_gc_cms_adaptive_size_policy(),
- "Wrong type of size policy");
- return sp;
-}
-
-CMSGCAdaptivePolicyCounters* CMSCollector::gc_adaptive_policy_counters() {
- CMSGCAdaptivePolicyCounters* results =
- (CMSGCAdaptivePolicyCounters*) collector_policy()->counters();
- assert(
- results->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
- "Wrong gc policy counter kind");
- return results;
-}
-
+ return gch->gen_policy()->size_policy();
+}
void ConcurrentMarkSweepGeneration::initialize_performance_counters() {
@@ -1573,11 +1558,11 @@
}
if (MetaspaceGC::should_concurrent_collect()) {
- if (Verbose && PrintGCDetails) {
+ if (Verbose && PrintGCDetails) {
gclog_or_tty->print("CMSCollector: collect for metadata allocation ");
- }
- return true;
- }
+ }
+ return true;
+ }
// CMSTriggerInterval starts a CMS cycle if enough time has passed.
if (CMSTriggerInterval >= 0) {
@@ -2031,11 +2016,6 @@
"collections passed to foreground collector", _full_gcs_since_conc_gc);
}
- // Sample collection interval time and reset for collection pause.
- if (UseAdaptiveSizePolicy) {
- size_policy()->msc_collection_begin();
- }
-
// Temporarily widen the span of the weak reference processing to
// the entire heap.
MemRegion new_span(GenCollectedHeap::heap()->reserved_region());
@@ -2111,11 +2091,6 @@
_inter_sweep_timer.reset();
_inter_sweep_timer.start();
- // Sample collection pause time and reset for collection interval.
- if (UseAdaptiveSizePolicy) {
- size_policy()->msc_collection_end(gch->gc_cause());
- }
-
gc_timer->register_gc_end();
gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
@@ -2373,26 +2348,14 @@
}
break;
case Precleaning:
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_precleaning_begin();
- }
// marking from roots in markFromRoots has been completed
preclean();
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_precleaning_end();
- }
assert(_collectorState == AbortablePreclean ||
_collectorState == FinalMarking,
"Collector state should have changed");
break;
case AbortablePreclean:
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_phases_resume();
- }
abortable_preclean();
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_precleaning_end();
- }
assert(_collectorState == FinalMarking, "Collector state should "
"have changed");
break;
@@ -2406,23 +2369,12 @@
assert(_foregroundGCShouldWait, "block post-condition");
break;
case Sweeping:
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_sweeping_begin();
- }
// final marking in checkpointRootsFinal has been completed
sweep(true);
assert(_collectorState == Resizing, "Collector state change "
"to Resizing must be done under the free_list_lock");
_full_gcs_since_conc_gc = 0;
- // Stop the timers for adaptive size policy for the concurrent phases
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_sweeping_end();
- size_policy()->concurrent_phases_end(gch->gc_cause(),
- gch->prev_gen(_cmsGen)->capacity(),
- _cmsGen->free());
- }
-
case Resizing: {
// Sweeping has been completed...
// At this point the background collection has completed.
@@ -2539,9 +2491,6 @@
const GCId gc_id = _collectorState == InitialMarking ? GCId::peek() : _gc_tracer_cm->gc_id();
NOT_PRODUCT(GCTraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose,
true, NULL, gc_id);)
- if (UseAdaptiveSizePolicy) {
- size_policy()->ms_collection_begin();
- }
COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact);
HandleMark hm; // Discard invalid handles created during verification
@@ -2633,11 +2582,6 @@
}
}
- if (UseAdaptiveSizePolicy) {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- size_policy()->ms_collection_end(gch->gc_cause());
- }
-
if (VerifyAfterGC &&
GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
Universe::verify();
@@ -3053,20 +2997,21 @@
HandleMark hm;
GenCollectedHeap* gch = GenCollectedHeap::heap();
- // Get a clear set of claim bits for the strong roots processing to work with.
+ // Get a clear set of claim bits for the roots processing to work with.
ClassLoaderDataGraph::clear_claimed_marks();
// Mark from roots one level into CMS
MarkRefsIntoClosure notOlder(_span, verification_mark_bm());
gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
- gch->gen_process_strong_roots(_cmsGen->level(),
- true, // younger gens are roots
- true, // activate StrongRootsScope
- SharedHeap::ScanningOption(roots_scanning_options()),
- ¬Older,
- NULL,
- NULL); // SSS: Provide correct closure
+ gch->gen_process_roots(_cmsGen->level(),
+ true, // younger gens are roots
+ true, // activate StrongRootsScope
+ SharedHeap::ScanningOption(roots_scanning_options()),
+ should_unload_classes(),
+ ¬Older,
+ NULL,
+ NULL); // SSS: Provide correct closure
// Now mark from the roots
MarkFromRootsClosure markFromRootsClosure(this, _span,
@@ -3117,22 +3062,24 @@
HandleMark hm;
GenCollectedHeap* gch = GenCollectedHeap::heap();
- // Get a clear set of claim bits for the strong roots processing to work with.
+ // Get a clear set of claim bits for the roots processing to work with.
ClassLoaderDataGraph::clear_claimed_marks();
// Mark from roots one level into CMS
MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(),
markBitMap());
- KlassToOopClosure klass_closure(¬Older);
+ CLDToOopClosure cld_closure(¬Older, true);
gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
- gch->gen_process_strong_roots(_cmsGen->level(),
- true, // younger gens are roots
- true, // activate StrongRootsScope
- SharedHeap::ScanningOption(roots_scanning_options()),
- ¬Older,
- NULL,
- &klass_closure);
+
+ gch->gen_process_roots(_cmsGen->level(),
+ true, // younger gens are roots
+ true, // activate StrongRootsScope
+ SharedHeap::ScanningOption(roots_scanning_options()),
+ should_unload_classes(),
+ ¬Older,
+ NULL,
+ &cld_closure);
// Now mark from the roots
MarkFromRootsVerifyClosure markFromRootsClosure(this, _span,
@@ -3319,12 +3266,10 @@
void CMSCollector::setup_cms_unloading_and_verification_state() {
const bool should_verify = VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC
|| VerifyBeforeExit;
- const int rso = SharedHeap::SO_Strings | SharedHeap::SO_AllCodeCache;
+ const int rso = SharedHeap::SO_AllCodeCache;
// We set the proper root for this CMS cycle here.
if (should_unload_classes()) { // Should unload classes this cycle
- remove_root_scanning_option(SharedHeap::SO_AllClasses);
- add_root_scanning_option(SharedHeap::SO_SystemClasses);
remove_root_scanning_option(rso); // Shrink the root set appropriately
set_verifying(should_verify); // Set verification state for this cycle
return; // Nothing else needs to be done at this time
@@ -3332,8 +3277,6 @@
// Not unloading classes this cycle
assert(!should_unload_classes(), "Inconsistency!");
- remove_root_scanning_option(SharedHeap::SO_SystemClasses);
- add_root_scanning_option(SharedHeap::SO_AllClasses);
if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) {
// Include symbols, strings and code cache elements to prevent their resurrection.
@@ -3687,9 +3630,6 @@
NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork",
PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());)
- if (UseAdaptiveSizePolicy) {
- size_policy()->checkpoint_roots_initial_begin();
- }
// Reset all the PLAB chunk arrays if necessary.
if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) {
@@ -3744,15 +3684,16 @@
gch->set_par_threads(0);
} else {
// The serial version.
- KlassToOopClosure klass_closure(¬Older);
+ CLDToOopClosure cld_closure(¬Older, true);
gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
- gch->gen_process_strong_roots(_cmsGen->level(),
- true, // younger gens are roots
- true, // activate StrongRootsScope
- SharedHeap::ScanningOption(roots_scanning_options()),
- ¬Older,
- NULL,
- &klass_closure);
+ gch->gen_process_roots(_cmsGen->level(),
+ true, // younger gens are roots
+ true, // activate StrongRootsScope
+ SharedHeap::ScanningOption(roots_scanning_options()),
+ should_unload_classes(),
+ ¬Older,
+ NULL,
+ &cld_closure);
}
}
@@ -3769,9 +3710,6 @@
// Save the end of the used_region of the constituent generations
// to be used to limit the extent of sweep in each generation.
save_sweep_limits();
- if (UseAdaptiveSizePolicy) {
- size_policy()->checkpoint_roots_initial_end(gch->gc_cause());
- }
verify_overflow_empty();
}
@@ -3788,15 +3726,6 @@
bool res;
if (asynch) {
-
- // Start the timers for adaptive size policy for the concurrent phases
- // Do it here so that the foreground MS can use the concurrent
- // timer since a foreground MS might has the sweep done concurrently
- // or STW.
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_marking_begin();
- }
-
// Weak ref discovery note: We may be discovering weak
// refs in this generation concurrent (but interleaved) with
// weak ref discovery by a younger generation collector.
@@ -3814,22 +3743,12 @@
gclog_or_tty->print_cr("bailing out to foreground collection");
}
}
- if (UseAdaptiveSizePolicy) {
- size_policy()->concurrent_marking_end();
- }
} else {
assert(SafepointSynchronize::is_at_safepoint(),
"inconsistent with asynch == false");
- if (UseAdaptiveSizePolicy) {
- size_policy()->ms_collection_marking_begin();
- }
// already have locks
res = markFromRootsWork(asynch);
_collectorState = FinalMarking;
- if (UseAdaptiveSizePolicy) {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- size_policy()->ms_collection_marking_end(gch->gc_cause());
- }
}
verify_overflow_empty();
return res;
@@ -4705,8 +4624,7 @@
if (clean_survivor) { // preclean the active survivor space(s)
assert(_young_gen->kind() == Generation::DefNew ||
- _young_gen->kind() == Generation::ParNew ||
- _young_gen->kind() == Generation::ASParNew,
+ _young_gen->kind() == Generation::ParNew,
"incorrect type for cast");
DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
PushAndMarkClosure pam_cl(this, _span, ref_processor(),
@@ -5077,10 +4995,6 @@
assert(haveFreelistLocks(), "must have free list locks");
assert_lock_strong(bitMapLock());
- if (UseAdaptiveSizePolicy) {
- size_policy()->checkpoint_roots_final_begin();
- }
-
ResourceMark rm;
HandleMark hm;
@@ -5214,9 +5128,6 @@
"Should be clear by end of the final marking");
assert(_ct->klass_rem_set()->mod_union_is_clear(),
"Should be clear by end of the final marking");
- if (UseAdaptiveSizePolicy) {
- size_policy()->checkpoint_roots_final_end(gch->gc_cause());
- }
}
void CMSParInitialMarkTask::work(uint worker_id) {
@@ -5228,7 +5139,6 @@
_timer.start();
GenCollectedHeap* gch = GenCollectedHeap::heap();
Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
- KlassToOopClosure klass_closure(&par_mri_cl);
// ---------- young gen roots --------------
{
@@ -5244,13 +5154,17 @@
// ---------- remaining roots --------------
_timer.reset();
_timer.start();
- gch->gen_process_strong_roots(_collector->_cmsGen->level(),
- false, // yg was scanned above
- false, // this is parallel code
- SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
- &par_mri_cl,
- NULL,
- &klass_closure);
+
+ CLDToOopClosure cld_closure(&par_mri_cl, true);
+
+ gch->gen_process_roots(_collector->_cmsGen->level(),
+ false, // yg was scanned above
+ false, // this is parallel code
+ SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
+ _collector->should_unload_classes(),
+ &par_mri_cl,
+ NULL,
+ &cld_closure);
assert(_collector->should_unload_classes()
|| (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache),
"if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
@@ -5379,13 +5293,15 @@
// ---------- remaining roots --------------
_timer.reset();
_timer.start();
- gch->gen_process_strong_roots(_collector->_cmsGen->level(),
- false, // yg was scanned above
- false, // this is parallel code
- SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
- &par_mrias_cl,
- NULL,
- NULL); // The dirty klasses will be handled below
+ gch->gen_process_roots(_collector->_cmsGen->level(),
+ false, // yg was scanned above
+ false, // this is parallel code
+ SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
+ _collector->should_unload_classes(),
+ &par_mrias_cl,
+ NULL,
+ NULL); // The dirty klasses will be handled below
+
assert(_collector->should_unload_classes()
|| (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache),
"if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
@@ -5440,7 +5356,7 @@
// We might have added oops to ClassLoaderData::_handles during the
// concurrent marking phase. These oops point to newly allocated objects
// that are guaranteed to be kept alive. Either by the direct allocation
- // code, or when the young collector processes the strong roots. Hence,
+ // code, or when the young collector processes the roots. Hence,
// we don't have to revisit the _handles block during the remark phase.
// ---------- rescan dirty cards ------------
@@ -5862,7 +5778,7 @@
cms_space,
n_workers, workers, task_queues());
- // Set up for parallel process_strong_roots work.
+ // Set up for parallel process_roots work.
gch->set_par_threads(n_workers);
// We won't be iterating over the cards in the card table updating
// the younger_gen cards, so we shouldn't call the following else
@@ -5871,7 +5787,7 @@
// gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel
// The young gen rescan work will not be done as part of
- // process_strong_roots (which currently doesn't knw how to
+ // process_roots (which currently doesn't know how to
// parallelize such a scan), but rather will be broken up into
// a set of parallel tasks (via the sampling that the [abortable]
// preclean phase did of EdenSpace, plus the [two] tasks of
@@ -5968,13 +5884,15 @@
gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
GenCollectedHeap::StrongRootsScope srs(gch);
- gch->gen_process_strong_roots(_cmsGen->level(),
- true, // younger gens as roots
- false, // use the local StrongRootsScope
- SharedHeap::ScanningOption(roots_scanning_options()),
- &mrias_cl,
- NULL,
- NULL); // The dirty klasses will be handled below
+
+ gch->gen_process_roots(_cmsGen->level(),
+ true, // younger gens as roots
+ false, // use the local StrongRootsScope
+ SharedHeap::ScanningOption(roots_scanning_options()),
+ should_unload_classes(),
+ &mrias_cl,
+ NULL,
+ NULL); // The dirty klasses will be handled below
assert(should_unload_classes()
|| (roots_scanning_options() & SharedHeap::SO_AllCodeCache),
@@ -6014,7 +5932,7 @@
// We might have added oops to ClassLoaderData::_handles during the
// concurrent marking phase. These oops point to newly allocated objects
// that are guaranteed to be kept alive. Either by the direct allocation
- // code, or when the young collector processes the strong roots. Hence,
+ // code, or when the young collector processes the roots. Hence,
// we don't have to revisit the _handles block during the remark phase.
verify_work_stacks_empty();
@@ -6264,15 +6182,14 @@
// Clean up unreferenced symbols in symbol table.
SymbolTable::unlink();
}
- }
-
- // CMS doesn't use the StringTable as hard roots when class unloading is turned off.
- // Need to check if we really scanned the StringTable.
- if ((roots_scanning_options() & SharedHeap::SO_Strings) == 0) {
- GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
- // Delete entries for dead interned strings.
- StringTable::unlink(&_is_alive_closure);
- }
+
+ {
+ GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
+ // Delete entries for dead interned strings.
+ StringTable::unlink(&_is_alive_closure);
+ }
+ }
+
// Restore any preserved marks as a result of mark stack or
// work queue overflow
@@ -6329,7 +6246,6 @@
_inter_sweep_timer.stop();
_inter_sweep_estimate.sample(_inter_sweep_timer.seconds());
- size_policy()->avg_cms_free_at_sweep()->sample(_cmsGen->free());
assert(!_intra_sweep_timer.is_active(), "Should not be active");
_intra_sweep_timer.reset();
@@ -6454,17 +6370,6 @@
}
}
-CMSAdaptiveSizePolicy* ConcurrentMarkSweepGeneration::size_policy() {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- assert(gch->kind() == CollectedHeap::GenCollectedHeap,
- "Wrong type of heap");
- CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
- gch->gen_policy()->size_policy();
- assert(sp->is_gc_cms_adaptive_size_policy(),
- "Wrong type of size policy");
- return sp;
-}
-
void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() {
if (PrintGCDetails && Verbose) {
gclog_or_tty->print("Rotate from %d ", _debug_collection_type);
@@ -6540,9 +6445,6 @@
// Reset CMS data structures (for now just the marking bit map)
// preparatory for the next cycle.
void CMSCollector::reset(bool asynch) {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- CMSAdaptiveSizePolicy* sp = size_policy();
- AdaptiveSizePolicyOutput(sp, gch->total_collections());
if (asynch) {
CMSTokenSyncWithLocks ts(true, bitMapLock());
@@ -6597,7 +6499,7 @@
// Because only the full (i.e., concurrent mode failure) collections
// are being measured for gc overhead limits, clean the "near" flag
// and count.
- sp->reset_gc_overhead_limit_count();
+ size_policy()->reset_gc_overhead_limit_count();
_collectorState = Idling;
} else {
// already have the lock
@@ -7064,7 +6966,6 @@
ConcurrentMarkSweepThread::desynchronize(true);
ConcurrentMarkSweepThread::acknowledge_yield_request();
_collector->stopTimer();
- GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
if (PrintCMSStatistics != 0) {
_collector->incrementYields();
}
@@ -7225,7 +7126,6 @@
ConcurrentMarkSweepThread::desynchronize(true);
ConcurrentMarkSweepThread::acknowledge_yield_request();
_collector->stopTimer();
- GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
if (PrintCMSStatistics != 0) {
_collector->incrementYields();
}
@@ -7298,7 +7198,6 @@
ConcurrentMarkSweepThread::desynchronize(true);
ConcurrentMarkSweepThread::acknowledge_yield_request();
_collector->stopTimer();
- GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
if (PrintCMSStatistics != 0) {
_collector->incrementYields();
}
@@ -7457,7 +7356,6 @@
ConcurrentMarkSweepThread::desynchronize(true);
ConcurrentMarkSweepThread::acknowledge_yield_request();
_collector->stopTimer();
- GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
if (PrintCMSStatistics != 0) {
_collector->incrementYields();
}
@@ -8099,7 +7997,6 @@
ConcurrentMarkSweepThread::acknowledge_yield_request();
_collector->stopTimer();
- GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
if (PrintCMSStatistics != 0) {
_collector->incrementYields();
}
@@ -8780,7 +8677,6 @@
ConcurrentMarkSweepThread::desynchronize(true);
ConcurrentMarkSweepThread::acknowledge_yield_request();
_collector->stopTimer();
- GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
if (PrintCMSStatistics != 0) {
_collector->incrementYields();
}
@@ -9327,172 +9223,6 @@
}
#endif
-CMSAdaptiveSizePolicy* ASConcurrentMarkSweepGeneration::cms_size_policy() const
-{
- GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
- CMSAdaptiveSizePolicy* size_policy =
- (CMSAdaptiveSizePolicy*) gch->gen_policy()->size_policy();
- assert(size_policy->is_gc_cms_adaptive_size_policy(),
- "Wrong type for size policy");
- return size_policy;
-}
-
-void ASConcurrentMarkSweepGeneration::resize(size_t cur_promo_size,
- size_t desired_promo_size) {
- if (cur_promo_size < desired_promo_size) {
- size_t expand_bytes = desired_promo_size - cur_promo_size;
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
- "Expanding tenured generation by " SIZE_FORMAT " (bytes)",
- expand_bytes);
- }
- expand(expand_bytes,
- MinHeapDeltaBytes,
- CMSExpansionCause::_adaptive_size_policy);
- } else if (desired_promo_size < cur_promo_size) {
- size_t shrink_bytes = cur_promo_size - desired_promo_size;
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
- "Shrinking tenured generation by " SIZE_FORMAT " (bytes)",
- shrink_bytes);
- }
- shrink(shrink_bytes);
- }
-}
-
-CMSGCAdaptivePolicyCounters* ASConcurrentMarkSweepGeneration::gc_adaptive_policy_counters() {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- CMSGCAdaptivePolicyCounters* counters =
- (CMSGCAdaptivePolicyCounters*) gch->collector_policy()->counters();
- assert(counters->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
- "Wrong kind of counters");
- return counters;
-}
-
-
-void ASConcurrentMarkSweepGeneration::update_counters() {
- if (UsePerfData) {
- _space_counters->update_all();
- _gen_counters->update_all();
- CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
- assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
- "Wrong gc statistics type");
- counters->update_counters(gc_stats_l);
- }
-}
-
-void ASConcurrentMarkSweepGeneration::update_counters(size_t used) {
- if (UsePerfData) {
- _space_counters->update_used(used);
- _space_counters->update_capacity();
- _gen_counters->update_all();
-
- CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
- assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
- "Wrong gc statistics type");
- counters->update_counters(gc_stats_l);
- }
-}
-
-void ASConcurrentMarkSweepGeneration::shrink_by(size_t desired_bytes) {
- assert_locked_or_safepoint(Heap_lock);
- assert_lock_strong(freelistLock());
- HeapWord* old_end = _cmsSpace->end();
- HeapWord* unallocated_start = _cmsSpace->unallocated_block();
- assert(old_end >= unallocated_start, "Miscalculation of unallocated_start");
- FreeChunk* chunk_at_end = find_chunk_at_end();
- if (chunk_at_end == NULL) {
- // No room to shrink
- if (PrintGCDetails && Verbose) {
- gclog_or_tty->print_cr("No room to shrink: old_end "
- PTR_FORMAT " unallocated_start " PTR_FORMAT
- " chunk_at_end " PTR_FORMAT,
- old_end, unallocated_start, chunk_at_end);
- }
- return;
- } else {
-
- // Find the chunk at the end of the space and determine
- // how much it can be shrunk.
- size_t shrinkable_size_in_bytes = chunk_at_end->size();
- size_t aligned_shrinkable_size_in_bytes =
- align_size_down(shrinkable_size_in_bytes, os::vm_page_size());
- assert(unallocated_start <= (HeapWord*) chunk_at_end->end(),
- "Inconsistent chunk at end of space");
- size_t bytes = MIN2(desired_bytes, aligned_shrinkable_size_in_bytes);
- size_t word_size_before = heap_word_size(_virtual_space.committed_size());
-
- // Shrink the underlying space
- _virtual_space.shrink_by(bytes);
- if (PrintGCDetails && Verbose) {
- gclog_or_tty->print_cr("ConcurrentMarkSweepGeneration::shrink_by:"
- " desired_bytes " SIZE_FORMAT
- " shrinkable_size_in_bytes " SIZE_FORMAT
- " aligned_shrinkable_size_in_bytes " SIZE_FORMAT
- " bytes " SIZE_FORMAT,
- desired_bytes, shrinkable_size_in_bytes,
- aligned_shrinkable_size_in_bytes, bytes);
- gclog_or_tty->print_cr(" old_end " SIZE_FORMAT
- " unallocated_start " SIZE_FORMAT,
- old_end, unallocated_start);
- }
-
- // If the space did shrink (shrinking is not guaranteed),
- // shrink the chunk at the end by the appropriate amount.
- if (((HeapWord*)_virtual_space.high()) < old_end) {
- size_t new_word_size =
- heap_word_size(_virtual_space.committed_size());
-
- // Have to remove the chunk from the dictionary because it is changing
- // size and might be someplace elsewhere in the dictionary.
-
- // Get the chunk at end, shrink it, and put it
- // back.
- _cmsSpace->removeChunkFromDictionary(chunk_at_end);
- size_t word_size_change = word_size_before - new_word_size;
- size_t chunk_at_end_old_size = chunk_at_end->size();
- assert(chunk_at_end_old_size >= word_size_change,
- "Shrink is too large");
- chunk_at_end->set_size(chunk_at_end_old_size -
- word_size_change);
- _cmsSpace->freed((HeapWord*) chunk_at_end->end(),
- word_size_change);
-
- _cmsSpace->returnChunkToDictionary(chunk_at_end);
-
- MemRegion mr(_cmsSpace->bottom(), new_word_size);
- _bts->resize(new_word_size); // resize the block offset shared array
- Universe::heap()->barrier_set()->resize_covered_region(mr);
- _cmsSpace->assert_locked();
- _cmsSpace->set_end((HeapWord*)_virtual_space.high());
-
- NOT_PRODUCT(_cmsSpace->dictionary()->verify());
-
- // update the space and generation capacity counters
- if (UsePerfData) {
- _space_counters->update_capacity();
- _gen_counters->update_all();
- }
-
- if (Verbose && PrintGCDetails) {
- size_t new_mem_size = _virtual_space.committed_size();
- size_t old_mem_size = new_mem_size + bytes;
- gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
- name(), old_mem_size/K, bytes/K, new_mem_size/K);
- }
- }
-
- assert(_cmsSpace->unallocated_block() <= _cmsSpace->end(),
- "Inconsistency at end of space");
- assert(chunk_at_end->end() == (uintptr_t*) _cmsSpace->end(),
- "Shrinking is inconsistent");
- return;
- }
-}
// Transfer some number of overflown objects to usual marking
// stack. Return true if some objects were transferred.
bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -32,6 +32,7 @@
#include "gc_implementation/shared/generationCounters.hpp"
#include "memory/freeBlockDictionary.hpp"
#include "memory/generation.hpp"
+#include "memory/iterator.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/virtualspace.hpp"
#include "services/memoryService.hpp"
@@ -52,7 +53,7 @@
// Concurrent mode failures are currently handled by
// means of a sliding mark-compact.
-class CMSAdaptiveSizePolicy;
+class AdaptiveSizePolicy;
class CMSConcMarkingTask;
class CMSGCAdaptivePolicyCounters;
class CMSTracer;
@@ -1009,8 +1010,7 @@
void icms_wait(); // Called at yield points.
// Adaptive size policy
- CMSAdaptiveSizePolicy* size_policy();
- CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();
+ AdaptiveSizePolicy* size_policy();
static void print_on_error(outputStream* st);
@@ -1150,9 +1150,6 @@
virtual Generation::Name kind() { return Generation::ConcurrentMarkSweep; }
- // Adaptive size policy
- CMSAdaptiveSizePolicy* size_policy();
-
void set_did_compact(bool v) { _did_compact = v; }
bool refs_discovery_is_atomic() const { return false; }
@@ -1346,37 +1343,6 @@
void rotate_debug_collection_type();
};
-class ASConcurrentMarkSweepGeneration : public ConcurrentMarkSweepGeneration {
-
- // Return the size policy from the heap's collector
- // policy casted to CMSAdaptiveSizePolicy*.
- CMSAdaptiveSizePolicy* cms_size_policy() const;
-
- // Resize the generation based on the adaptive size
- // policy.
- void resize(size_t cur_promo, size_t desired_promo);
-
- // Return the GC counters from the collector policy
- CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();
-
- virtual void shrink_by(size_t bytes);
-
- public:
- ASConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,
- int level, CardTableRS* ct,
- bool use_adaptive_freelists,
- FreeBlockDictionary<FreeChunk>::DictionaryChoice
- dictionaryChoice) :
- ConcurrentMarkSweepGeneration(rs, initial_byte_size, level, ct,
- use_adaptive_freelists, dictionaryChoice) {}
-
- virtual const char* short_name() const { return "ASCMS"; }
- virtual Generation::Name kind() { return Generation::ASConcurrentMarkSweep; }
-
- virtual void update_counters();
- virtual void update_counters(size_t used);
-};
-
//
// Closures of various sorts used by CMS to accomplish its work
//
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeChunk.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeChunk.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
#include "memory/memRegion.hpp"
#include "oops/markOop.hpp"
#include "runtime/mutex.hpp"
+#include "runtime/orderAccess.hpp"
#include "utilities/debug.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/ostream.hpp"
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -24,6 +24,7 @@
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
+#include "code/codeCache.hpp"
#include "gc_implementation/g1/concurrentMark.inline.hpp"
#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
@@ -39,6 +40,7 @@
#include "gc_implementation/shared/gcTimer.hpp"
#include "gc_implementation/shared/gcTrace.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
+#include "memory/allocation.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/resourceArea.hpp"
@@ -58,8 +60,8 @@
_bmWordSize = 0;
}
-HeapWord* CMBitMapRO::getNextMarkedWordAddress(HeapWord* addr,
- HeapWord* limit) const {
+HeapWord* CMBitMapRO::getNextMarkedWordAddress(const HeapWord* addr,
+ const HeapWord* limit) const {
// First we must round addr *up* to a possible object boundary.
addr = (HeapWord*)align_size_up((intptr_t)addr,
HeapWordSize << _shifter);
@@ -76,8 +78,8 @@
return nextAddr;
}
-HeapWord* CMBitMapRO::getNextUnmarkedWordAddress(HeapWord* addr,
- HeapWord* limit) const {
+HeapWord* CMBitMapRO::getNextUnmarkedWordAddress(const HeapWord* addr,
+ const HeapWord* limit) const {
size_t addrOffset = heapWordToOffset(addr);
if (limit == NULL) {
limit = _bmStartWord + _bmWordSize;
@@ -1223,6 +1225,9 @@
};
void ConcurrentMark::scanRootRegions() {
+ // Start of concurrent marking.
+ ClassLoaderDataGraph::clear_claimed_marks();
+
// scan_in_progress() will have been set to true only if there was
// at least one root region to scan. So, if it's false, we
// should not attempt to do any further work.
@@ -1271,7 +1276,7 @@
CMConcurrentMarkingTask markingTask(this, cmThread());
if (use_parallel_marking_threads()) {
_parallel_workers->set_active_workers((int)active_workers);
- // Don't set _n_par_threads because it affects MT in process_strong_roots()
+ // Don't set _n_par_threads because it affects MT in process_roots()
// and the decisions on that MT processing is made elsewhere.
assert(_parallel_workers->active_workers() > 0, "Should have been set");
_parallel_workers->run_task(&markingTask);
@@ -2142,23 +2147,29 @@
// Update the soft reference policy with the new heap occupancy.
Universe::update_heap_info_at_gc();
- // We need to make this be a "collection" so any collection pause that
- // races with it goes around and waits for completeCleanup to finish.
- g1h->increment_total_collections();
-
- // We reclaimed old regions so we should calculate the sizes to make
- // sure we update the old gen/space data.
- g1h->g1mm()->update_sizes();
-
if (VerifyDuringGC) {
HandleMark hm; // handle scope
Universe::heap()->prepare_for_verify();
Universe::verify(VerifyOption_G1UsePrevMarking,
" VerifyDuringGC:(after)");
}
+
g1h->check_bitmaps("Cleanup End");
g1h->verify_region_sets_optional();
+
+ // We need to make this be a "collection" so any collection pause that
+ // races with it goes around and waits for completeCleanup to finish.
+ g1h->increment_total_collections();
+
+ // Clean out dead classes and update Metaspace sizes.
+ ClassLoaderDataGraph::purge();
+ MetaspaceGC::compute_new_size();
+
+ // We reclaimed old regions so we should calculate the sizes to make
+ // sure we update the old gen/space data.
+ g1h->g1mm()->update_sizes();
+
g1h->trace_heap_after_concurrent_cycle();
}
@@ -2445,6 +2456,26 @@
_g1h->set_par_threads(0);
}
+void ConcurrentMark::weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes) {
+ G1CollectedHeap::heap()->parallel_cleaning(is_alive, true, true, purged_classes);
+}
+
+// Helper class to get rid of some boilerplate code.
+class G1RemarkGCTraceTime : public GCTraceTime {
+ static bool doit_and_prepend(bool doit) {
+ if (doit) {
+ gclog_or_tty->put(' ');
+ }
+ return doit;
+ }
+
+ public:
+ G1RemarkGCTraceTime(const char* title, bool doit)
+ : GCTraceTime(title, doit_and_prepend(doit), false, G1CollectedHeap::heap()->gc_timer_cm(),
+ G1CollectedHeap::heap()->concurrent_mark()->concurrent_gc_id()) {
+ }
+};
+
void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
if (has_overflown()) {
// Skip processing the discovered references if we have
@@ -2557,9 +2588,28 @@
return;
}
- g1h->unlink_string_and_symbol_table(&g1_is_alive,
- /* process_strings */ false, // currently strings are always roots
- /* process_symbols */ true);
+ assert(_markStack.isEmpty(), "Marking should have completed");
+
+ // Unload Klasses, String, Symbols, Code Cache, etc.
+
+ G1RemarkGCTraceTime trace("Unloading", G1Log::finer());
+
+ bool purged_classes;
+
+ {
+ G1RemarkGCTraceTime trace("System Dictionary Unloading", G1Log::finest());
+ purged_classes = SystemDictionary::do_unloading(&g1_is_alive);
+ }
+
+ {
+ G1RemarkGCTraceTime trace("Parallel Unloading", G1Log::finest());
+ weakRefsWorkParallelPart(&g1_is_alive, purged_classes);
+ }
+
+ if (G1StringDedup::is_enabled()) {
+ G1RemarkGCTraceTime trace("String Deduplication Unlink", G1Log::finest());
+ G1StringDedup::unlink(&g1_is_alive);
+ }
}
void ConcurrentMark::swapMarkBitMaps() {
@@ -2568,6 +2618,57 @@
_nextMarkBitMap = (CMBitMap*) temp;
}
+class CMObjectClosure;
+
+// Closure for iterating over objects, currently only used for
+// processing SATB buffers.
+class CMObjectClosure : public ObjectClosure {
+private:
+ CMTask* _task;
+
+public:
+ void do_object(oop obj) {
+ _task->deal_with_reference(obj);
+ }
+
+ CMObjectClosure(CMTask* task) : _task(task) { }
+};
+
+class G1RemarkThreadsClosure : public ThreadClosure {
+ CMObjectClosure _cm_obj;
+ G1CMOopClosure _cm_cl;
+ MarkingCodeBlobClosure _code_cl;
+ int _thread_parity;
+ bool _is_par;
+
+ public:
+ G1RemarkThreadsClosure(G1CollectedHeap* g1h, CMTask* task, bool is_par) :
+ _cm_obj(task), _cm_cl(g1h, g1h->concurrent_mark(), task), _code_cl(&_cm_cl, !CodeBlobToOopClosure::FixRelocations),
+ _thread_parity(SharedHeap::heap()->strong_roots_parity()), _is_par(is_par) {}
+
+ void do_thread(Thread* thread) {
+ if (thread->is_Java_thread()) {
+ if (thread->claim_oops_do(_is_par, _thread_parity)) {
+ JavaThread* jt = (JavaThread*)thread;
+
+ // In theory it should not be neccessary to explicitly walk the nmethods to find roots for concurrent marking
+ // however the liveness of oops reachable from nmethods have very complex lifecycles:
+ // * Alive if on the stack of an executing method
+ // * Weakly reachable otherwise
+ // Some objects reachable from nmethods, such as the class loader (or klass_holder) of the receiver should be
+ // live by the SATB invariant but other oops recorded in nmethods may behave differently.
+ jt->nmethods_do(&_code_cl);
+
+ jt->satb_mark_queue().apply_closure_and_empty(&_cm_obj);
+ }
+ } else if (thread->is_VM_thread()) {
+ if (thread->claim_oops_do(_is_par, _thread_parity)) {
+ JavaThread::satb_mark_queue_set().shared_satb_queue()->apply_closure_and_empty(&_cm_obj);
+ }
+ }
+ }
+};
+
class CMRemarkTask: public AbstractGangTask {
private:
ConcurrentMark* _cm;
@@ -2579,6 +2680,14 @@
if (worker_id < _cm->active_tasks()) {
CMTask* task = _cm->task(worker_id);
task->record_start_time();
+ {
+ ResourceMark rm;
+ HandleMark hm;
+
+ G1RemarkThreadsClosure threads_f(G1CollectedHeap::heap(), task, !_is_serial);
+ Threads::threads_do(&threads_f);
+ }
+
do {
task->do_marking_step(1000000000.0 /* something very large */,
true /* do_termination */,
@@ -2601,6 +2710,8 @@
HandleMark hm;
G1CollectedHeap* g1h = G1CollectedHeap::heap();
+ G1RemarkGCTraceTime trace("Finalize Marking", G1Log::finer());
+
g1h->ensure_parsability(false);
if (G1CollectedHeap::use_parallel_gc_threads()) {
@@ -3430,20 +3541,6 @@
}
};
-// Closure for iterating over objects, currently only used for
-// processing SATB buffers.
-class CMObjectClosure : public ObjectClosure {
-private:
- CMTask* _task;
-
-public:
- void do_object(oop obj) {
- _task->deal_with_reference(obj);
- }
-
- CMObjectClosure(CMTask* task) : _task(task) { }
-};
-
G1CMOopClosure::G1CMOopClosure(G1CollectedHeap* g1h,
ConcurrentMark* cm,
CMTask* task)
@@ -3908,15 +4005,6 @@
}
}
- if (!concurrent() && !has_aborted()) {
- // We should only do this during remark.
- if (G1CollectedHeap::use_parallel_gc_threads()) {
- satb_mq_set.par_iterate_closure_all_threads(_worker_id);
- } else {
- satb_mq_set.iterate_closure_all_threads();
- }
- }
-
_draining_satb_buffers = false;
assert(has_aborted() ||
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,6 +25,7 @@
#ifndef SHARE_VM_GC_IMPLEMENTATION_G1_CONCURRENTMARK_HPP
#define SHARE_VM_GC_IMPLEMENTATION_G1_CONCURRENTMARK_HPP
+#include "classfile/javaClasses.hpp"
#include "gc_implementation/g1/heapRegionSet.hpp"
#include "gc_implementation/shared/gcId.hpp"
#include "utilities/taskqueue.hpp"
@@ -86,19 +87,19 @@
// Return the address corresponding to the next marked bit at or after
// "addr", and before "limit", if "limit" is non-NULL. If there is no
// such bit, returns "limit" if that is non-NULL, or else "endWord()".
- HeapWord* getNextMarkedWordAddress(HeapWord* addr,
- HeapWord* limit = NULL) const;
+ HeapWord* getNextMarkedWordAddress(const HeapWord* addr,
+ const HeapWord* limit = NULL) const;
// Return the address corresponding to the next unmarked bit at or after
// "addr", and before "limit", if "limit" is non-NULL. If there is no
// such bit, returns "limit" if that is non-NULL, or else "endWord()".
- HeapWord* getNextUnmarkedWordAddress(HeapWord* addr,
- HeapWord* limit = NULL) const;
+ HeapWord* getNextUnmarkedWordAddress(const HeapWord* addr,
+ const HeapWord* limit = NULL) const;
// conversion utilities
HeapWord* offsetToHeapWord(size_t offset) const {
return _bmStartWord + (offset << _shifter);
}
- size_t heapWordToOffset(HeapWord* addr) const {
+ size_t heapWordToOffset(const HeapWord* addr) const {
return pointer_delta(addr, _bmStartWord) >> _shifter;
}
int heapWordDiffToOffsetDiff(size_t diff) const;
@@ -476,6 +477,7 @@
ForceOverflowSettings _force_overflow_conc;
ForceOverflowSettings _force_overflow_stw;
+ void weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes);
void weakRefsWork(bool clear_all_soft_refs);
void swapMarkBitMaps();
--- a/hotspot/src/share/vm/gc_implementation/g1/g1AllocRegion.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1AllocRegion.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,6 +26,7 @@
#define SHARE_VM_GC_IMPLEMENTATION_G1_G1ALLOCREGION_INLINE_HPP
#include "gc_implementation/g1/g1AllocRegion.hpp"
+#include "gc_implementation/g1/heapRegion.inline.hpp"
inline HeapWord* G1AllocRegion::allocate(HeapRegion* alloc_region,
size_t word_size,
--- a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -426,7 +426,7 @@
q = n;
oop obj = oop(q);
if (obj->klass_or_null() == NULL) return q;
- n += obj->size();
+ n += block_size(q);
}
assert(q <= next_boundary && n > next_boundary, "Consequence of loop");
// [q, n) is the block that crosses the boundary.
--- a/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1BlockOffsetTable.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,7 +26,8 @@
#define SHARE_VM_GC_IMPLEMENTATION_G1_G1BLOCKOFFSETTABLE_INLINE_HPP
#include "gc_implementation/g1/g1BlockOffsetTable.hpp"
-#include "gc_implementation/g1/heapRegion.hpp"
+#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
+#include "gc_implementation/g1/heapRegion.inline.hpp"
#include "memory/space.hpp"
inline HeapWord* G1BlockOffsetTable::block_start(const void* addr) {
@@ -112,7 +113,7 @@
q = n;
oop obj = oop(q);
if (obj->klass_or_null() == NULL) return q;
- n += obj->size();
+ n += block_size(q);
}
assert(q <= n, "wrong order for q and addr");
assert(addr < n, "wrong order for addr and n");
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -30,23 +30,52 @@
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
-G1CodeRootChunk::G1CodeRootChunk() : _top(NULL), _next(NULL), _prev(NULL) {
+G1CodeRootChunk::G1CodeRootChunk() : _top(NULL), _next(NULL), _prev(NULL), _free(NULL) {
_top = bottom();
}
void G1CodeRootChunk::reset() {
_next = _prev = NULL;
+ _free = NULL;
_top = bottom();
}
void G1CodeRootChunk::nmethods_do(CodeBlobClosure* cl) {
- nmethod** cur = bottom();
+ NmethodOrLink* cur = bottom();
while (cur != _top) {
- cl->do_code_blob(*cur);
+ if (is_nmethod(cur)) {
+ cl->do_code_blob(cur->_nmethod);
+ }
cur++;
}
}
+bool G1CodeRootChunk::remove_lock_free(nmethod* method) {
+ NmethodOrLink* cur = bottom();
+
+ for (NmethodOrLink* cur = bottom(); cur != _top; cur++) {
+ if (cur->_nmethod == method) {
+ bool result = Atomic::cmpxchg_ptr(NULL, &cur->_nmethod, method) == method;
+
+ if (!result) {
+ // Someone else cleared out this entry.
+ return false;
+ }
+
+ // The method was cleared. Time to link it into the free list.
+ NmethodOrLink* prev_free;
+ do {
+ prev_free = (NmethodOrLink*)_free;
+ cur->_link = prev_free;
+ } while (Atomic::cmpxchg_ptr(cur, &_free, prev_free) != prev_free);
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
G1CodeRootChunkManager::G1CodeRootChunkManager() : _free_list(), _num_chunks_handed_out(0) {
_free_list.initialize();
_free_list.set_size(G1CodeRootChunk::word_size());
@@ -140,34 +169,43 @@
void G1CodeRootSet::add(nmethod* method) {
if (!contains(method)) {
- // Try to add the nmethod. If there is not enough space, get a new chunk.
- if (_list.head() == NULL || _list.head()->is_full()) {
- G1CodeRootChunk* cur = new_chunk();
+ // Find the first chunk that isn't full.
+ G1CodeRootChunk* cur = _list.head();
+ while (cur != NULL) {
+ if (!cur->is_full()) {
+ break;
+ }
+ cur = cur->next();
+ }
+
+ // All chunks are full, get a new chunk.
+ if (cur == NULL) {
+ cur = new_chunk();
_list.return_chunk_at_head(cur);
}
- bool result = _list.head()->add(method);
+
+ // Add the nmethod.
+ bool result = cur->add(method);
+
guarantee(result, err_msg("Not able to add nmethod "PTR_FORMAT" to newly allocated chunk.", method));
+
_length++;
}
}
-void G1CodeRootSet::remove(nmethod* method) {
+void G1CodeRootSet::remove_lock_free(nmethod* method) {
G1CodeRootChunk* found = find(method);
if (found != NULL) {
- bool result = found->remove(method);
- guarantee(result, err_msg("could not find nmethod "PTR_FORMAT" during removal although we previously found it", method));
- // eventually free completely emptied chunk
- if (found->is_empty()) {
- _list.remove_chunk(found);
- free(found);
+ bool result = found->remove_lock_free(method);
+ if (result) {
+ Atomic::dec_ptr((volatile intptr_t*)&_length);
}
- _length--;
}
assert(!contains(method), err_msg(PTR_FORMAT" still contains nmethod "PTR_FORMAT, this, method));
}
nmethod* G1CodeRootSet::pop() {
- do {
+ while (true) {
G1CodeRootChunk* cur = _list.head();
if (cur == NULL) {
assert(_length == 0, "when there are no chunks, there should be no elements");
@@ -180,7 +218,7 @@
} else {
free(_list.get_chunk_at_head());
}
- } while (true);
+ }
}
G1CodeRootChunk* G1CodeRootSet::find(nmethod* method) {
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -31,6 +31,14 @@
class CodeBlobClosure;
+// The elements of the G1CodeRootChunk is either:
+// 1) nmethod pointers
+// 2) nodes in an internally chained free list
+typedef union {
+ nmethod* _nmethod;
+ void* _link;
+} NmethodOrLink;
+
class G1CodeRootChunk : public CHeapObj<mtGC> {
private:
static const int NUM_ENTRIES = 32;
@@ -38,16 +46,28 @@
G1CodeRootChunk* _next;
G1CodeRootChunk* _prev;
- nmethod** _top;
+ NmethodOrLink* _top;
+ // First free position within the chunk.
+ volatile NmethodOrLink* _free;
- nmethod* _data[NUM_ENTRIES];
+ NmethodOrLink _data[NUM_ENTRIES];
- nmethod** bottom() const {
- return (nmethod**) &(_data[0]);
+ NmethodOrLink* bottom() const {
+ return (NmethodOrLink*) &(_data[0]);
}
- nmethod** end() const {
- return (nmethod**) &(_data[NUM_ENTRIES]);
+ NmethodOrLink* end() const {
+ return (NmethodOrLink*) &(_data[NUM_ENTRIES]);
+ }
+
+ bool is_link(NmethodOrLink* nmethod_or_link) {
+ return nmethod_or_link->_link == NULL ||
+ (bottom() <= nmethod_or_link->_link
+ && nmethod_or_link->_link < end());
+ }
+
+ bool is_nmethod(NmethodOrLink* nmethod_or_link) {
+ return !is_link(nmethod_or_link);
}
public:
@@ -85,46 +105,55 @@
}
bool is_full() const {
- return _top == (nmethod**)end();
+ return _top == end() && _free == NULL;
}
bool contains(nmethod* method) {
- nmethod** cur = bottom();
+ NmethodOrLink* cur = bottom();
while (cur != _top) {
- if (*cur == method) return true;
+ if (cur->_nmethod == method) return true;
cur++;
}
return false;
}
bool add(nmethod* method) {
- if (is_full()) return false;
- *_top = method;
- _top++;
+ if (is_full()) {
+ return false;
+ }
+
+ if (_free != NULL) {
+ // Take from internally chained free list
+ NmethodOrLink* first_free = (NmethodOrLink*)_free;
+ _free = (NmethodOrLink*)_free->_link;
+ first_free->_nmethod = method;
+ } else {
+ // Take from top.
+ _top->_nmethod = method;
+ _top++;
+ }
+
return true;
}
- bool remove(nmethod* method) {
- nmethod** cur = bottom();
- while (cur != _top) {
- if (*cur == method) {
- memmove(cur, cur + 1, (_top - (cur + 1)) * sizeof(nmethod**));
- _top--;
- return true;
- }
- cur++;
- }
- return false;
- }
+ bool remove_lock_free(nmethod* method);
void nmethods_do(CodeBlobClosure* blk);
nmethod* pop() {
- if (is_empty()) {
- return NULL;
+ if (_free != NULL) {
+ // Kill the free list.
+ _free = NULL;
}
- _top--;
- return *_top;
+
+ while (!is_empty()) {
+ _top--;
+ if (is_nmethod(_top)) {
+ return _top->_nmethod;
+ }
+ }
+
+ return NULL;
}
};
@@ -193,7 +222,7 @@
// method is likely to be repeatedly called with the same nmethod.
void add(nmethod* method);
- void remove(nmethod* method);
+ void remove_lock_free(nmethod* method);
nmethod* pop();
bool contains(nmethod* method);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -44,6 +44,7 @@
#include "gc_implementation/g1/g1Log.hpp"
#include "gc_implementation/g1/g1MarkSweep.hpp"
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
+#include "gc_implementation/g1/g1ParScanThreadState.inline.hpp"
#include "gc_implementation/g1/g1RemSet.inline.hpp"
#include "gc_implementation/g1/g1StringDedup.hpp"
#include "gc_implementation/g1/g1YCTypes.hpp"
@@ -56,6 +57,7 @@
#include "gc_implementation/shared/gcTrace.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
#include "gc_implementation/shared/isGCActiveMark.hpp"
+#include "memory/allocation.hpp"
#include "memory/gcLocker.inline.hpp"
#include "memory/generationSpec.hpp"
#include "memory/iterator.hpp"
@@ -63,11 +65,9 @@
#include "oops/oop.inline.hpp"
#include "oops/oop.pcgc.inline.hpp"
#include "runtime/atomic.inline.hpp"
-#include "runtime/prefetch.inline.hpp"
#include "runtime/orderAccess.inline.hpp"
#include "runtime/vmThread.hpp"
#include "utilities/globalDefinitions.hpp"
-#include "utilities/ticks.hpp"
size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
@@ -92,10 +92,10 @@
// G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
// The number of GC workers is passed to heap_region_par_iterate_chunked().
// It does use run_task() which sets _n_workers in the task.
-// G1ParTask executes g1_process_strong_roots() ->
-// SharedHeap::process_strong_roots() which calls eventually to
+// G1ParTask executes g1_process_roots() ->
+// SharedHeap::process_roots() which calls eventually to
// CardTableModRefBS::par_non_clean_card_iterate_work() which uses
-// SequentialSubTasksDone. SharedHeap::process_strong_roots() also
+// SequentialSubTasksDone. SharedHeap::process_roots() also
// directly uses SubTasksDone (_process_strong_tasks field in SharedHeap).
//
@@ -3380,25 +3380,19 @@
if (!silent) { gclog_or_tty->print("Roots "); }
VerifyRootsClosure rootsCl(vo);
VerifyKlassClosure klassCl(this, &rootsCl);
+ CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false);
// We apply the relevant closures to all the oops in the
- // system dictionary, class loader data graph and the string table.
- // Don't verify the code cache here, since it's verified below.
- const int so = SO_AllClasses | SO_Strings;
-
- // Need cleared claim bits for the strong roots processing
- ClassLoaderDataGraph::clear_claimed_marks();
-
- process_strong_roots(true, // activate StrongRootsScope
- ScanningOption(so), // roots scanning options
- &rootsCl,
- &klassCl
- );
-
- // Verify the nmethods in the code cache.
+ // system dictionary, class loader data graph, the string table
+ // and the nmethods in the code cache.
G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
- CodeCache::blobs_do(&blobsCl);
+
+ process_all_roots(true, // activate StrongRootsScope
+ SO_AllCodeCache, // roots scanning options
+ &rootsCl,
+ &cldCl,
+ &blobsCl);
bool failures = rootsCl.failures() || codeRootsCl.failures();
@@ -3980,6 +3974,7 @@
increment_gc_time_stamp();
verify_before_gc();
+
check_bitmaps("GC Start");
COMPILER2_PRESENT(DerivedPointerTable::clear());
@@ -4330,11 +4325,7 @@
assert(_mutator_alloc_region.get() == NULL, "post-condition");
}
-void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
- assert_at_safepoint(true /* should_be_vm_thread */);
-
- _survivor_gc_alloc_region.init();
- _old_gc_alloc_region.init();
+void G1CollectedHeap::use_retained_old_gc_alloc_region(EvacuationInfo& evacuation_info) {
HeapRegion* retained_region = _retained_old_gc_alloc_region;
_retained_old_gc_alloc_region = NULL;
@@ -4352,7 +4343,7 @@
!(retained_region->top() == retained_region->end()) &&
!retained_region->is_empty() &&
!retained_region->isHumongous()) {
- retained_region->set_saved_mark();
+ retained_region->record_top_and_timestamp();
// The retained region was added to the old region set when it was
// retired. We have to remove it now, since we don't allow regions
// we allocate to in the region sets. We'll re-add it later, when
@@ -4366,6 +4357,15 @@
}
}
+void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
+ assert_at_safepoint(true /* should_be_vm_thread */);
+
+ _survivor_gc_alloc_region.init();
+ _old_gc_alloc_region.init();
+
+ use_retained_old_gc_alloc_region(evacuation_info);
+}
+
void G1CollectedHeap::release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info) {
evacuation_info.set_allocation_regions(_survivor_gc_alloc_region.count() +
_old_gc_alloc_region.count());
@@ -4559,126 +4559,6 @@
G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
ParGCAllocBuffer(gclab_word_size), _retired(true) { }
-G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp)
- : _g1h(g1h),
- _refs(g1h->task_queue(queue_num)),
- _dcq(&g1h->dirty_card_queue_set()),
- _ct_bs(g1h->g1_barrier_set()),
- _g1_rem(g1h->g1_rem_set()),
- _hash_seed(17), _queue_num(queue_num),
- _term_attempts(0),
- _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
- _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
- _age_table(false), _scanner(g1h, this, rp),
- _strong_roots_time(0), _term_time(0),
- _alloc_buffer_waste(0), _undo_waste(0) {
- // we allocate G1YoungSurvRateNumRegions plus one entries, since
- // we "sacrifice" entry 0 to keep track of surviving bytes for
- // non-young regions (where the age is -1)
- // We also add a few elements at the beginning and at the end in
- // an attempt to eliminate cache contention
- uint real_length = 1 + _g1h->g1_policy()->young_cset_region_length();
- uint array_length = PADDING_ELEM_NUM +
- real_length +
- PADDING_ELEM_NUM;
- _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
- if (_surviving_young_words_base == NULL)
- vm_exit_out_of_memory(array_length * sizeof(size_t), OOM_MALLOC_ERROR,
- "Not enough space for young surv histo.");
- _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
- memset(_surviving_young_words, 0, (size_t) real_length * sizeof(size_t));
-
- _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
- _alloc_buffers[GCAllocForTenured] = &_tenured_alloc_buffer;
-
- _start = os::elapsedTime();
-}
-
-void
-G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
-{
- st->print_raw_cr("GC Termination Stats");
- st->print_raw_cr(" elapsed --strong roots-- -------termination-------"
- " ------waste (KiB)------");
- st->print_raw_cr("thr ms ms % ms % attempts"
- " total alloc undo");
- st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
- " ------- ------- -------");
-}
-
-void
-G1ParScanThreadState::print_termination_stats(int i,
- outputStream* const st) const
-{
- const double elapsed_ms = elapsed_time() * 1000.0;
- const double s_roots_ms = strong_roots_time() * 1000.0;
- const double term_ms = term_time() * 1000.0;
- st->print_cr("%3d %9.2f %9.2f %6.2f "
- "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
- SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
- i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
- term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
- (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
- alloc_buffer_waste() * HeapWordSize / K,
- undo_waste() * HeapWordSize / K);
-}
-
-#ifdef ASSERT
-bool G1ParScanThreadState::verify_ref(narrowOop* ref) const {
- assert(ref != NULL, "invariant");
- assert(UseCompressedOops, "sanity");
- assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, ref));
- oop p = oopDesc::load_decode_heap_oop(ref);
- assert(_g1h->is_in_g1_reserved(p),
- err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
- return true;
-}
-
-bool G1ParScanThreadState::verify_ref(oop* ref) const {
- assert(ref != NULL, "invariant");
- if (has_partial_array_mask(ref)) {
- // Must be in the collection set--it's already been copied.
- oop p = clear_partial_array_mask(ref);
- assert(_g1h->obj_in_cs(p),
- err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
- } else {
- oop p = oopDesc::load_decode_heap_oop(ref);
- assert(_g1h->is_in_g1_reserved(p),
- err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
- }
- return true;
-}
-
-bool G1ParScanThreadState::verify_task(StarTask ref) const {
- if (ref.is_narrow()) {
- return verify_ref((narrowOop*) ref);
- } else {
- return verify_ref((oop*) ref);
- }
-}
-#endif // ASSERT
-
-void G1ParScanThreadState::trim_queue() {
- assert(_evac_failure_cl != NULL, "not set");
-
- StarTask ref;
- do {
- // Drain the overflow stack first, so other threads can steal.
- while (refs()->pop_overflow(ref)) {
- deal_with_reference(ref);
- }
-
- while (refs()->pop_local(ref)) {
- deal_with_reference(ref);
- }
- } while (!refs()->is_empty());
-}
-
-G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1,
- G1ParScanThreadState* par_scan_state) :
- _g1(g1), _par_scan_state(par_scan_state),
- _worker_id(par_scan_state->queue_num()) { }
-
void G1ParCopyHelper::mark_object(oop obj) {
assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet");
@@ -4701,107 +4581,6 @@
_cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
}
-oop G1ParScanThreadState::copy_to_survivor_space(oop const old) {
- size_t word_sz = old->size();
- HeapRegion* from_region = _g1h->heap_region_containing_raw(old);
- // +1 to make the -1 indexes valid...
- int young_index = from_region->young_index_in_cset()+1;
- assert( (from_region->is_young() && young_index > 0) ||
- (!from_region->is_young() && young_index == 0), "invariant" );
- G1CollectorPolicy* g1p = _g1h->g1_policy();
- markOop m = old->mark();
- int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
- : m->age();
- GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
- word_sz);
- HeapWord* obj_ptr = allocate(alloc_purpose, word_sz);
-#ifndef PRODUCT
- // Should this evacuation fail?
- if (_g1h->evacuation_should_fail()) {
- if (obj_ptr != NULL) {
- undo_allocation(alloc_purpose, obj_ptr, word_sz);
- obj_ptr = NULL;
- }
- }
-#endif // !PRODUCT
-
- if (obj_ptr == NULL) {
- // This will either forward-to-self, or detect that someone else has
- // installed a forwarding pointer.
- return _g1h->handle_evacuation_failure_par(this, old);
- }
-
- oop obj = oop(obj_ptr);
-
- // We're going to allocate linearly, so might as well prefetch ahead.
- Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
-
- oop forward_ptr = old->forward_to_atomic(obj);
- if (forward_ptr == NULL) {
- Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
-
- // alloc_purpose is just a hint to allocate() above, recheck the type of region
- // we actually allocated from and update alloc_purpose accordingly
- HeapRegion* to_region = _g1h->heap_region_containing_raw(obj_ptr);
- alloc_purpose = to_region->is_young() ? GCAllocForSurvived : GCAllocForTenured;
-
- if (g1p->track_object_age(alloc_purpose)) {
- // We could simply do obj->incr_age(). However, this causes a
- // performance issue. obj->incr_age() will first check whether
- // the object has a displaced mark by checking its mark word;
- // getting the mark word from the new location of the object
- // stalls. So, given that we already have the mark word and we
- // are about to install it anyway, it's better to increase the
- // age on the mark word, when the object does not have a
- // displaced mark word. We're not expecting many objects to have
- // a displaced marked word, so that case is not optimized
- // further (it could be...) and we simply call obj->incr_age().
-
- if (m->has_displaced_mark_helper()) {
- // in this case, we have to install the mark word first,
- // otherwise obj looks to be forwarded (the old mark word,
- // which contains the forward pointer, was copied)
- obj->set_mark(m);
- obj->incr_age();
- } else {
- m = m->incr_age();
- obj->set_mark(m);
- }
- age_table()->add(obj, word_sz);
- } else {
- obj->set_mark(m);
- }
-
- if (G1StringDedup::is_enabled()) {
- G1StringDedup::enqueue_from_evacuation(from_region->is_young(),
- to_region->is_young(),
- queue_num(),
- obj);
- }
-
- size_t* surv_young_words = surviving_young_words();
- surv_young_words[young_index] += word_sz;
-
- if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
- // We keep track of the next start index in the length field of
- // the to-space object. The actual length can be found in the
- // length field of the from-space object.
- arrayOop(obj)->set_length(0);
- oop* old_p = set_partial_array_mask(old);
- push_on_queue(old_p);
- } else {
- // No point in using the slower heap_region_containing() method,
- // given that we know obj is in the heap.
- _scanner.set_region(_g1h->heap_region_containing_raw(obj));
- obj->oop_iterate_backwards(&_scanner);
- }
- } else {
- undo_allocation(alloc_purpose, obj_ptr, word_sz);
- obj = forward_ptr;
- }
- return obj;
-}
-
template <class T>
void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {
if (_g1->heap_region_containing_raw(new_obj)->is_young()) {
@@ -4809,7 +4588,7 @@
}
}
-template <G1Barrier barrier, bool do_mark_object>
+template <G1Barrier barrier, G1Mark do_mark_object>
template <class T>
void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {
T heap_oop = oopDesc::load_heap_oop(p);
@@ -4831,7 +4610,7 @@
}
assert(forwardee != NULL, "forwardee should not be NULL");
oopDesc::encode_store_heap_oop(p, forwardee);
- if (do_mark_object && forwardee != obj) {
+ if (do_mark_object != G1MarkNone && forwardee != obj) {
// If the object is self-forwarded we don't need to explicitly
// mark it, the evacuation failure protocol will do so.
mark_forwarded_object(obj, forwardee);
@@ -4842,9 +4621,8 @@
}
} else {
// The object is not in collection set. If we're a root scanning
- // closure during an initial mark pause (i.e. do_mark_object will
- // be true) then attempt to mark the object.
- if (do_mark_object) {
+ // closure during an initial mark pause then attempt to mark the object.
+ if (do_mark_object == G1MarkFromRoot) {
mark_object(obj);
}
}
@@ -4854,8 +4632,8 @@
}
}
-template void G1ParCopyClosure<G1BarrierEvac, false>::do_oop_work(oop* p);
-template void G1ParCopyClosure<G1BarrierEvac, false>::do_oop_work(narrowOop* p);
+template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(oop* p);
+template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(narrowOop* p);
class G1ParEvacuateFollowersClosure : public VoidClosure {
protected:
@@ -4891,24 +4669,10 @@
}
void G1ParEvacuateFollowersClosure::do_void() {
- StarTask stolen_task;
G1ParScanThreadState* const pss = par_scan_state();
pss->trim_queue();
-
do {
- while (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) {
- assert(pss->verify_task(stolen_task), "sanity");
- if (stolen_task.is_narrow()) {
- pss->deal_with_reference((narrowOop*) stolen_task);
- } else {
- pss->deal_with_reference((oop*) stolen_task);
- }
-
- // We've just processed a reference and we might have made
- // available new entries on the queues. So we have to make sure
- // we drain the queues as necessary.
- pss->trim_queue();
- }
+ pss->steal_and_trim_queue(queues());
} while (!offer_termination());
}
@@ -4954,8 +4718,7 @@
}
public:
- G1ParTask(G1CollectedHeap* g1h,
- RefToScanQueueSet *task_queues)
+ G1ParTask(G1CollectedHeap* g1h, RefToScanQueueSet *task_queues)
: AbstractGangTask("G1 collection"),
_g1h(g1h),
_queues(task_queues),
@@ -4983,6 +4746,51 @@
_n_workers = active_workers;
}
+ // Helps out with CLD processing.
+ //
+ // During InitialMark we need to:
+ // 1) Scavenge all CLDs for the young GC.
+ // 2) Mark all objects directly reachable from strong CLDs.
+ template <G1Mark do_mark_object>
+ class G1CLDClosure : public CLDClosure {
+ G1ParCopyClosure<G1BarrierNone, do_mark_object>* _oop_closure;
+ G1ParCopyClosure<G1BarrierKlass, do_mark_object> _oop_in_klass_closure;
+ G1KlassScanClosure _klass_in_cld_closure;
+ bool _claim;
+
+ public:
+ G1CLDClosure(G1ParCopyClosure<G1BarrierNone, do_mark_object>* oop_closure,
+ bool only_young, bool claim)
+ : _oop_closure(oop_closure),
+ _oop_in_klass_closure(oop_closure->g1(),
+ oop_closure->pss(),
+ oop_closure->rp()),
+ _klass_in_cld_closure(&_oop_in_klass_closure, only_young),
+ _claim(claim) {
+
+ }
+
+ void do_cld(ClassLoaderData* cld) {
+ cld->oops_do(_oop_closure, &_klass_in_cld_closure, _claim);
+ }
+ };
+
+ class G1CodeBlobClosure: public CodeBlobClosure {
+ OopClosure* _f;
+
+ public:
+ G1CodeBlobClosure(OopClosure* f) : _f(f) {}
+ void do_code_blob(CodeBlob* blob) {
+ nmethod* that = blob->as_nmethod_or_null();
+ if (that != NULL) {
+ if (!that->test_set_oops_do_mark()) {
+ that->oops_do(_f);
+ that->fix_oop_relocations();
+ }
+ }
+ }
+ };
+
void work(uint worker_id) {
if (worker_id >= _n_workers) return; // no work needed this round
@@ -5000,40 +4808,62 @@
pss.set_evac_failure_closure(&evac_failure_cl);
- G1ParScanExtRootClosure only_scan_root_cl(_g1h, &pss, rp);
- G1ParScanMetadataClosure only_scan_metadata_cl(_g1h, &pss, rp);
-
- G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss, rp);
- G1ParScanAndMarkMetadataClosure scan_mark_metadata_cl(_g1h, &pss, rp);
-
- bool only_young = _g1h->g1_policy()->gcs_are_young();
- G1KlassScanClosure scan_mark_klasses_cl_s(&scan_mark_metadata_cl, false);
- G1KlassScanClosure only_scan_klasses_cl_s(&only_scan_metadata_cl, only_young);
-
- OopClosure* scan_root_cl = &only_scan_root_cl;
- G1KlassScanClosure* scan_klasses_cl = &only_scan_klasses_cl_s;
+ bool only_young = _g1h->g1_policy()->gcs_are_young();
+
+ // Non-IM young GC.
+ G1ParCopyClosure<G1BarrierNone, G1MarkNone> scan_only_root_cl(_g1h, &pss, rp);
+ G1CLDClosure<G1MarkNone> scan_only_cld_cl(&scan_only_root_cl,
+ only_young, // Only process dirty klasses.
+ false); // No need to claim CLDs.
+ // IM young GC.
+ // Strong roots closures.
+ G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot> scan_mark_root_cl(_g1h, &pss, rp);
+ G1CLDClosure<G1MarkFromRoot> scan_mark_cld_cl(&scan_mark_root_cl,
+ false, // Process all klasses.
+ true); // Need to claim CLDs.
+ // Weak roots closures.
+ G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> scan_mark_weak_root_cl(_g1h, &pss, rp);
+ G1CLDClosure<G1MarkPromotedFromRoot> scan_mark_weak_cld_cl(&scan_mark_weak_root_cl,
+ false, // Process all klasses.
+ true); // Need to claim CLDs.
+
+ G1CodeBlobClosure scan_only_code_cl(&scan_only_root_cl);
+ G1CodeBlobClosure scan_mark_code_cl(&scan_mark_root_cl);
+ // IM Weak code roots are handled later.
+
+ OopClosure* strong_root_cl;
+ OopClosure* weak_root_cl;
+ CLDClosure* strong_cld_cl;
+ CLDClosure* weak_cld_cl;
+ CodeBlobClosure* strong_code_cl;
if (_g1h->g1_policy()->during_initial_mark_pause()) {
// We also need to mark copied objects.
- scan_root_cl = &scan_mark_root_cl;
- scan_klasses_cl = &scan_mark_klasses_cl_s;
+ strong_root_cl = &scan_mark_root_cl;
+ weak_root_cl = &scan_mark_weak_root_cl;
+ strong_cld_cl = &scan_mark_cld_cl;
+ weak_cld_cl = &scan_mark_weak_cld_cl;
+ strong_code_cl = &scan_mark_code_cl;
+ } else {
+ strong_root_cl = &scan_only_root_cl;
+ weak_root_cl = &scan_only_root_cl;
+ strong_cld_cl = &scan_only_cld_cl;
+ weak_cld_cl = &scan_only_cld_cl;
+ strong_code_cl = &scan_only_code_cl;
}
- G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
-
- // Don't scan the scavengable methods in the code cache as part
- // of strong root scanning. The code roots that point into a
- // region in the collection set are scanned when we scan the
- // region's RSet.
- int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings;
+
+ G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
pss.start_strong_roots();
- _g1h->g1_process_strong_roots(/* is scavenging */ true,
- SharedHeap::ScanningOption(so),
- scan_root_cl,
- &push_heap_rs_cl,
- scan_klasses_cl,
- worker_id);
+ _g1h->g1_process_roots(strong_root_cl,
+ weak_root_cl,
+ &push_heap_rs_cl,
+ strong_cld_cl,
+ weak_cld_cl,
+ strong_code_cl,
+ worker_id);
+
pss.end_strong_roots();
{
@@ -5053,7 +4883,7 @@
pss.print_termination_stats(worker_id);
}
- assert(pss.refs()->is_empty(), "should be empty");
+ assert(pss.queue_is_empty(), "should be empty");
// Close the inner scope so that the ResourceMark and HandleMark
// destructors are executed here and are included as part of the
@@ -5071,24 +4901,31 @@
void
G1CollectedHeap::
-g1_process_strong_roots(bool is_scavenging,
- ScanningOption so,
- OopClosure* scan_non_heap_roots,
- OopsInHeapRegionClosure* scan_rs,
- G1KlassScanClosure* scan_klasses,
- uint worker_i) {
-
- // First scan the strong roots
+g1_process_roots(OopClosure* scan_non_heap_roots,
+ OopClosure* scan_non_heap_weak_roots,
+ OopsInHeapRegionClosure* scan_rs,
+ CLDClosure* scan_strong_clds,
+ CLDClosure* scan_weak_clds,
+ CodeBlobClosure* scan_strong_code,
+ uint worker_i) {
+
+ // First scan the shared roots.
double ext_roots_start = os::elapsedTime();
double closure_app_time_sec = 0.0;
+ bool during_im = _g1h->g1_policy()->during_initial_mark_pause();
+
BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
-
- process_strong_roots(false, // no scoping; this is parallel code
- so,
- &buf_scan_non_heap_roots,
- scan_klasses
- );
+ BufferingOopClosure buf_scan_non_heap_weak_roots(scan_non_heap_weak_roots);
+
+ process_roots(false, // no scoping; this is parallel code
+ SharedHeap::SO_None,
+ &buf_scan_non_heap_roots,
+ &buf_scan_non_heap_weak_roots,
+ scan_strong_clds,
+ // Initial Mark handles the weak CLDs separately.
+ (during_im ? NULL : scan_weak_clds),
+ scan_strong_code);
// Now the CM ref_processor roots.
if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
@@ -5099,10 +4936,21 @@
ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots);
}
+ if (during_im) {
+ // Barrier to make sure all workers passed
+ // the strong CLD and strong nmethods phases.
+ active_strong_roots_scope()->wait_until_all_workers_done_with_threads(n_par_threads());
+
+ // Now take the complement of the strong CLDs.
+ ClassLoaderDataGraph::roots_cld_do(NULL, scan_weak_clds);
+ }
+
// Finish up any enqueued closure apps (attributed as object copy time).
buf_scan_non_heap_roots.done();
-
- double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds();
+ buf_scan_non_heap_weak_roots.done();
+
+ double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds()
+ + buf_scan_non_heap_weak_roots.closure_app_seconds();
g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
@@ -5126,22 +4974,10 @@
}
g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms);
- // If this is an initial mark pause, and we're not scanning
- // the entire code cache, we need to mark the oops in the
- // strong code root lists for the regions that are not in
- // the collection set.
- // Note all threads participate in this set of root tasks.
- double mark_strong_code_roots_ms = 0.0;
- if (g1_policy()->during_initial_mark_pause() && !(so & SO_AllCodeCache)) {
- double mark_strong_roots_start = os::elapsedTime();
- mark_strong_code_roots(worker_i);
- mark_strong_code_roots_ms = (os::elapsedTime() - mark_strong_roots_start) * 1000.0;
- }
- g1_policy()->phase_times()->record_strong_code_root_mark_time(worker_i, mark_strong_code_roots_ms);
-
// Now scan the complement of the collection set.
- CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, true /* do_marking */);
- g1_rem_set()->oops_into_collection_set_do(scan_rs, &eager_scan_code_roots, worker_i);
+ MarkingCodeBlobClosure scavenge_cs_nmethods(scan_non_heap_weak_roots, CodeBlobToOopClosure::FixRelocations);
+
+ g1_rem_set()->oops_into_collection_set_do(scan_rs, &scavenge_cs_nmethods, worker_i);
_process_strong_tasks->all_tasks_completed();
}
@@ -5163,7 +4999,8 @@
bool _do_in_parallel;
public:
G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
- AbstractGangTask("Par String/Symbol table unlink"), _is_alive(is_alive),
+ AbstractGangTask("String/Symbol Unlinking"),
+ _is_alive(is_alive),
_do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),
_process_strings(process_strings), _strings_processed(0), _strings_removed(0),
_process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
@@ -5185,6 +5022,14 @@
guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
err_msg("claim value %d after unlink less than initial symbol table size %d",
SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
+
+ if (G1TraceStringSymbolTableScrubbing) {
+ gclog_or_tty->print_cr("Cleaned string and symbol table, "
+ "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
+ "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
+ strings_processed(), strings_removed(),
+ symbols_processed(), symbols_removed());
+ }
}
void work(uint worker_id) {
@@ -5220,12 +5065,279 @@
size_t symbols_removed() const { return (size_t)_symbols_removed; }
};
-void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
- bool process_strings, bool process_symbols) {
+class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC {
+private:
+ static Monitor* _lock;
+
+ BoolObjectClosure* const _is_alive;
+ const bool _unloading_occurred;
+ const uint _num_workers;
+
+ // Variables used to claim nmethods.
+ nmethod* _first_nmethod;
+ volatile nmethod* _claimed_nmethod;
+
+ // The list of nmethods that need to be processed by the second pass.
+ volatile nmethod* _postponed_list;
+ volatile uint _num_entered_barrier;
+
+ public:
+ G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) :
+ _is_alive(is_alive),
+ _unloading_occurred(unloading_occurred),
+ _num_workers(num_workers),
+ _first_nmethod(NULL),
+ _claimed_nmethod(NULL),
+ _postponed_list(NULL),
+ _num_entered_barrier(0)
+ {
+ nmethod::increase_unloading_clock();
+ _first_nmethod = CodeCache::alive_nmethod(CodeCache::first());
+ _claimed_nmethod = (volatile nmethod*)_first_nmethod;
+ }
+
+ ~G1CodeCacheUnloadingTask() {
+ CodeCache::verify_clean_inline_caches();
+
+ CodeCache::set_needs_cache_clean(false);
+ guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be");
+
+ CodeCache::verify_icholder_relocations();
+ }
+
+ private:
+ void add_to_postponed_list(nmethod* nm) {
+ nmethod* old;
+ do {
+ old = (nmethod*)_postponed_list;
+ nm->set_unloading_next(old);
+ } while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old);
+ }
+
+ void clean_nmethod(nmethod* nm) {
+ bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred);
+
+ if (postponed) {
+ // This nmethod referred to an nmethod that has not been cleaned/unloaded yet.
+ add_to_postponed_list(nm);
+ }
+
+ // Mark that this thread has been cleaned/unloaded.
+ // After this call, it will be safe to ask if this nmethod was unloaded or not.
+ nm->set_unloading_clock(nmethod::global_unloading_clock());
+ }
+
+ void clean_nmethod_postponed(nmethod* nm) {
+ nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred);
+ }
+
+ static const int MaxClaimNmethods = 16;
+
+ void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) {
+ nmethod* first;
+ nmethod* last;
+
+ do {
+ *num_claimed_nmethods = 0;
+
+ first = last = (nmethod*)_claimed_nmethod;
+
+ if (first != NULL) {
+ for (int i = 0; i < MaxClaimNmethods; i++) {
+ last = CodeCache::alive_nmethod(CodeCache::next(last));
+
+ if (last == NULL) {
+ break;
+ }
+
+ claimed_nmethods[i] = last;
+ (*num_claimed_nmethods)++;
+ }
+ }
+
+ } while ((nmethod*)Atomic::cmpxchg_ptr(last, &_claimed_nmethod, first) != first);
+ }
+
+ nmethod* claim_postponed_nmethod() {
+ nmethod* claim;
+ nmethod* next;
+
+ do {
+ claim = (nmethod*)_postponed_list;
+ if (claim == NULL) {
+ return NULL;
+ }
+
+ next = claim->unloading_next();
+
+ } while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim);
+
+ return claim;
+ }
+
+ public:
+ // Mark that we're done with the first pass of nmethod cleaning.
+ void barrier_mark(uint worker_id) {
+ MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
+ _num_entered_barrier++;
+ if (_num_entered_barrier == _num_workers) {
+ ml.notify_all();
+ }
+ }
+
+ // See if we have to wait for the other workers to
+ // finish their first-pass nmethod cleaning work.
+ void barrier_wait(uint worker_id) {
+ if (_num_entered_barrier < _num_workers) {
+ MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
+ while (_num_entered_barrier < _num_workers) {
+ ml.wait(Mutex::_no_safepoint_check_flag, 0, false);
+ }
+ }
+ }
+
+ // Cleaning and unloading of nmethods. Some work has to be postponed
+ // to the second pass, when we know which nmethods survive.
+ void work_first_pass(uint worker_id) {
+ // The first nmethods is claimed by the first worker.
+ if (worker_id == 0 && _first_nmethod != NULL) {
+ clean_nmethod(_first_nmethod);
+ _first_nmethod = NULL;
+ }
+
+ int num_claimed_nmethods;
+ nmethod* claimed_nmethods[MaxClaimNmethods];
+
+ while (true) {
+ claim_nmethods(claimed_nmethods, &num_claimed_nmethods);
+
+ if (num_claimed_nmethods == 0) {
+ break;
+ }
+
+ for (int i = 0; i < num_claimed_nmethods; i++) {
+ clean_nmethod(claimed_nmethods[i]);
+ }
+ }
+ }
+
+ void work_second_pass(uint worker_id) {
+ nmethod* nm;
+ // Take care of postponed nmethods.
+ while ((nm = claim_postponed_nmethod()) != NULL) {
+ clean_nmethod_postponed(nm);
+ }
+ }
+};
+
+Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock");
+
+class G1KlassCleaningTask : public StackObj {
+ BoolObjectClosure* _is_alive;
+ volatile jint _clean_klass_tree_claimed;
+ ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator;
+
+ public:
+ G1KlassCleaningTask(BoolObjectClosure* is_alive) :
+ _is_alive(is_alive),
+ _clean_klass_tree_claimed(0),
+ _klass_iterator() {
+ }
+
+ private:
+ bool claim_clean_klass_tree_task() {
+ if (_clean_klass_tree_claimed) {
+ return false;
+ }
+
+ return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0;
+ }
+
+ InstanceKlass* claim_next_klass() {
+ Klass* klass;
+ do {
+ klass =_klass_iterator.next_klass();
+ } while (klass != NULL && !klass->oop_is_instance());
+
+ return (InstanceKlass*)klass;
+ }
+
+public:
+
+ void clean_klass(InstanceKlass* ik) {
+ ik->clean_implementors_list(_is_alive);
+ ik->clean_method_data(_is_alive);
+
+ // G1 specific cleanup work that has
+ // been moved here to be done in parallel.
+ ik->clean_dependent_nmethods();
+ }
+
+ void work() {
+ ResourceMark rm;
+
+ // One worker will clean the subklass/sibling klass tree.
+ if (claim_clean_klass_tree_task()) {
+ Klass::clean_subklass_tree(_is_alive);
+ }
+
+ // All workers will help cleaning the classes,
+ InstanceKlass* klass;
+ while ((klass = claim_next_klass()) != NULL) {
+ clean_klass(klass);
+ }
+ }
+};
+
+// To minimize the remark pause times, the tasks below are done in parallel.
+class G1ParallelCleaningTask : public AbstractGangTask {
+private:
+ G1StringSymbolTableUnlinkTask _string_symbol_task;
+ G1CodeCacheUnloadingTask _code_cache_task;
+ G1KlassCleaningTask _klass_cleaning_task;
+
+public:
+ // The constructor is run in the VMThread.
+ G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) :
+ AbstractGangTask("Parallel Cleaning"),
+ _string_symbol_task(is_alive, process_strings, process_symbols),
+ _code_cache_task(num_workers, is_alive, unloading_occurred),
+ _klass_cleaning_task(is_alive) {
+ }
+
+ // The parallel work done by all worker threads.
+ void work(uint worker_id) {
+ // Do first pass of code cache cleaning.
+ _code_cache_task.work_first_pass(worker_id);
+
+ // Let the threads mark that the first pass is done.
+ _code_cache_task.barrier_mark(worker_id);
+
+ // Clean the Strings and Symbols.
+ _string_symbol_task.work(worker_id);
+
+ // Wait for all workers to finish the first code cache cleaning pass.
+ _code_cache_task.barrier_wait(worker_id);
+
+ // Do the second code cache cleaning work, which realize on
+ // the liveness information gathered during the first pass.
+ _code_cache_task.work_second_pass(worker_id);
+
+ // Clean all klasses that were not unloaded.
+ _klass_cleaning_task.work();
+ }
+};
+
+
+void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive,
+ bool process_strings,
+ bool process_symbols,
+ bool class_unloading_occurred) {
uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
- _g1h->workers()->active_workers() : 1);
-
- G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
+ workers()->active_workers() : 1);
+
+ G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols,
+ n_workers, class_unloading_occurred);
if (G1CollectedHeap::use_parallel_gc_threads()) {
set_par_threads(n_workers);
workers()->run_task(&g1_unlink_task);
@@ -5233,12 +5345,21 @@
} else {
g1_unlink_task.work(0);
}
- if (G1TraceStringSymbolTableScrubbing) {
- gclog_or_tty->print_cr("Cleaned string and symbol table, "
- "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
- "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
- g1_unlink_task.strings_processed(), g1_unlink_task.strings_removed(),
- g1_unlink_task.symbols_processed(), g1_unlink_task.symbols_removed());
+}
+
+void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
+ bool process_strings, bool process_symbols) {
+ {
+ uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
+ _g1h->workers()->active_workers() : 1);
+ G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
+ if (G1CollectedHeap::use_parallel_gc_threads()) {
+ set_par_threads(n_workers);
+ workers()->run_task(&g1_unlink_task);
+ set_par_threads(0);
+ } else {
+ g1_unlink_task.work(0);
+ }
}
if (G1StringDedup::is_enabled()) {
@@ -5577,8 +5698,7 @@
pss.set_evac_failure_closure(&evac_failure_cl);
- assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
-
+ assert(pss.queue_is_empty(), "both queue and overflow should be empty");
G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);
@@ -5632,7 +5752,7 @@
G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
drain_queue.do_void();
// Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
- assert(pss.refs()->is_empty(), "should be");
+ assert(pss.queue_is_empty(), "should be");
}
};
@@ -5699,7 +5819,7 @@
pss.set_evac_failure_closure(&evac_failure_cl);
- assert(pss.refs()->is_empty(), "pre-condition");
+ assert(pss.queue_is_empty(), "pre-condition");
G1ParScanExtRootClosure only_copy_non_heap_cl(this, &pss, NULL);
@@ -5747,7 +5867,7 @@
_gc_tracer_stw->report_gc_reference_stats(stats);
// We have completed copying any necessary live referent objects.
- assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
+ assert(pss.queue_is_empty(), "both queue and overflow should be empty");
double ref_proc_time = os::elapsedTime() - ref_proc_start;
g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
@@ -5832,6 +5952,10 @@
{
StrongRootsScope srs(this);
+ // InitialMark needs claim bits to keep track of the marked-through CLDs.
+ if (g1_policy()->during_initial_mark_pause()) {
+ ClassLoaderDataGraph::clear_claimed_marks();
+ }
if (G1CollectedHeap::use_parallel_gc_threads()) {
// The individual threads will set their evac-failure closures.
@@ -6603,7 +6727,7 @@
// We really only need to do this for old regions given that we
// should never scan survivors. But it doesn't hurt to do it
// for survivors too.
- new_alloc_region->set_saved_mark();
+ new_alloc_region->record_top_and_timestamp();
if (survivor) {
new_alloc_region->set_survivor();
_hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
@@ -6867,106 +6991,6 @@
g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);
}
-// Mark all the code roots that point into regions *not* in the
-// collection set.
-//
-// Note we do not want to use a "marking" CodeBlobToOopClosure while
-// walking the the code roots lists of regions not in the collection
-// set. Suppose we have an nmethod (M) that points to objects in two
-// separate regions - one in the collection set (R1) and one not (R2).
-// Using a "marking" CodeBlobToOopClosure here would result in "marking"
-// nmethod M when walking the code roots for R1. When we come to scan
-// the code roots for R2, we would see that M is already marked and it
-// would be skipped and the objects in R2 that are referenced from M
-// would not be evacuated.
-
-class MarkStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
-
- class MarkStrongCodeRootOopClosure: public OopClosure {
- ConcurrentMark* _cm;
- HeapRegion* _hr;
- uint _worker_id;
-
- template <class T> void do_oop_work(T* p) {
- T heap_oop = oopDesc::load_heap_oop(p);
- if (!oopDesc::is_null(heap_oop)) {
- oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
- // Only mark objects in the region (which is assumed
- // to be not in the collection set).
- if (_hr->is_in(obj)) {
- _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
- }
- }
- }
-
- public:
- MarkStrongCodeRootOopClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id) :
- _cm(cm), _hr(hr), _worker_id(worker_id) {
- assert(!_hr->in_collection_set(), "sanity");
- }
-
- void do_oop(narrowOop* p) { do_oop_work(p); }
- void do_oop(oop* p) { do_oop_work(p); }
- };
-
- MarkStrongCodeRootOopClosure _oop_cl;
-
-public:
- MarkStrongCodeRootCodeBlobClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id):
- _oop_cl(cm, hr, worker_id) {}
-
- void do_code_blob(CodeBlob* cb) {
- nmethod* nm = (cb == NULL) ? NULL : cb->as_nmethod_or_null();
- if (nm != NULL) {
- nm->oops_do(&_oop_cl);
- }
- }
-};
-
-class MarkStrongCodeRootsHRClosure: public HeapRegionClosure {
- G1CollectedHeap* _g1h;
- uint _worker_id;
-
-public:
- MarkStrongCodeRootsHRClosure(G1CollectedHeap* g1h, uint worker_id) :
- _g1h(g1h), _worker_id(worker_id) {}
-
- bool doHeapRegion(HeapRegion *hr) {
- HeapRegionRemSet* hrrs = hr->rem_set();
- if (hr->continuesHumongous()) {
- // Code roots should never be attached to a continuation of a humongous region
- assert(hrrs->strong_code_roots_list_length() == 0,
- err_msg("code roots should never be attached to continuations of humongous region "HR_FORMAT
- " starting at "HR_FORMAT", but has "SIZE_FORMAT,
- HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()),
- hrrs->strong_code_roots_list_length()));
- return false;
- }
-
- if (hr->in_collection_set()) {
- // Don't mark code roots into regions in the collection set here.
- // They will be marked when we scan them.
- return false;
- }
-
- MarkStrongCodeRootCodeBlobClosure cb_cl(_g1h->concurrent_mark(), hr, _worker_id);
- hr->strong_code_roots_do(&cb_cl);
- return false;
- }
-};
-
-void G1CollectedHeap::mark_strong_code_roots(uint worker_id) {
- MarkStrongCodeRootsHRClosure cl(this, worker_id);
- if (G1CollectedHeap::use_parallel_gc_threads()) {
- heap_region_par_iterate_chunked(&cl,
- worker_id,
- workers()->active_workers(),
- HeapRegion::ParMarkRootClaimValue);
- } else {
- heap_region_iterate(&cl);
- }
-}
-
class RebuildStrongCodeRootClosure: public CodeBlobClosure {
G1CollectedHeap* _g1h;
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -31,7 +31,6 @@
#include "gc_implementation/g1/g1BiasedArray.hpp"
#include "gc_implementation/g1/g1HRPrinter.hpp"
#include "gc_implementation/g1/g1MonitoringSupport.hpp"
-#include "gc_implementation/g1/g1RemSet.hpp"
#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
#include "gc_implementation/g1/g1YCTypes.hpp"
#include "gc_implementation/g1/heapRegionSeq.hpp"
@@ -211,6 +210,7 @@
class RefineCardTableEntryClosure;
class G1CollectedHeap : public SharedHeap {
+ friend class VM_CollectForMetadataAllocation;
friend class VM_G1CollectForAllocation;
friend class VM_G1CollectFull;
friend class VM_G1IncCollectionPause;
@@ -220,7 +220,7 @@
friend class OldGCAllocRegion;
// Closures used in implementation.
- template <G1Barrier barrier, bool do_mark_object>
+ template <G1Barrier barrier, G1Mark do_mark_object>
friend class G1ParCopyClosure;
friend class G1IsAliveClosure;
friend class G1EvacuateFollowersClosure;
@@ -347,6 +347,9 @@
// It initializes the GC alloc regions at the start of a GC.
void init_gc_alloc_regions(EvacuationInfo& evacuation_info);
+ // Setup the retained old gc alloc region as the currrent old gc alloc region.
+ void use_retained_old_gc_alloc_region(EvacuationInfo& evacuation_info);
+
// It releases the GC alloc regions at the end of a GC.
void release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info);
@@ -828,12 +831,13 @@
// param is for use with parallel roots processing, and should be
// the "i" of the calling parallel worker thread's work(i) function.
// In the sequential case this param will be ignored.
- void g1_process_strong_roots(bool is_scavenging,
- ScanningOption so,
- OopClosure* scan_non_heap_roots,
- OopsInHeapRegionClosure* scan_rs,
- G1KlassScanClosure* scan_klasses,
- uint worker_i);
+ void g1_process_roots(OopClosure* scan_non_heap_roots,
+ OopClosure* scan_non_heap_weak_roots,
+ OopsInHeapRegionClosure* scan_rs,
+ CLDClosure* scan_strong_clds,
+ CLDClosure* scan_weak_clds,
+ CodeBlobClosure* scan_strong_code,
+ uint worker_i);
// Notifies all the necessary spaces that the committed space has
// been updated (either expanded or shrunk). It should be called
@@ -1026,7 +1030,7 @@
// of G1CollectedHeap::_gc_time_stamp.
unsigned int* _worker_cset_start_region_time_stamp;
- enum G1H_process_strong_roots_tasks {
+ enum G1H_process_roots_tasks {
G1H_PS_filter_satb_buffers,
G1H_PS_refProcessor_oops_do,
// Leave this one last.
@@ -1608,10 +1612,6 @@
// Free up superfluous code root memory.
void purge_code_root_memory();
- // During an initial mark pause, mark all the code roots that
- // point into regions *not* in the collection set.
- void mark_strong_code_roots(uint worker_id);
-
// Rebuild the strong code root lists for each region
// after a full GC.
void rebuild_strong_code_roots();
@@ -1620,6 +1620,9 @@
// in symbol table, possibly in parallel.
void unlink_string_and_symbol_table(BoolObjectClosure* is_alive, bool unlink_strings = true, bool unlink_symbols = true);
+ // Parallel phase of unloading/cleaning after G1 concurrent mark.
+ void parallel_cleaning(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, bool class_unloading_occurred);
+
// Redirty logged cards in the refinement queue.
void redirty_logged_cards();
// Verification
@@ -1715,256 +1718,4 @@
}
};
-class G1ParScanThreadState : public StackObj {
-protected:
- G1CollectedHeap* _g1h;
- RefToScanQueue* _refs;
- DirtyCardQueue _dcq;
- G1SATBCardTableModRefBS* _ct_bs;
- G1RemSet* _g1_rem;
-
- G1ParGCAllocBuffer _surviving_alloc_buffer;
- G1ParGCAllocBuffer _tenured_alloc_buffer;
- G1ParGCAllocBuffer* _alloc_buffers[GCAllocPurposeCount];
- ageTable _age_table;
-
- G1ParScanClosure _scanner;
-
- size_t _alloc_buffer_waste;
- size_t _undo_waste;
-
- OopsInHeapRegionClosure* _evac_failure_cl;
-
- int _hash_seed;
- uint _queue_num;
-
- size_t _term_attempts;
-
- double _start;
- double _start_strong_roots;
- double _strong_roots_time;
- double _start_term;
- double _term_time;
-
- // Map from young-age-index (0 == not young, 1 is youngest) to
- // surviving words. base is what we get back from the malloc call
- size_t* _surviving_young_words_base;
- // this points into the array, as we use the first few entries for padding
- size_t* _surviving_young_words;
-
-#define PADDING_ELEM_NUM (DEFAULT_CACHE_LINE_SIZE / sizeof(size_t))
-
- void add_to_alloc_buffer_waste(size_t waste) { _alloc_buffer_waste += waste; }
-
- void add_to_undo_waste(size_t waste) { _undo_waste += waste; }
-
- DirtyCardQueue& dirty_card_queue() { return _dcq; }
- G1SATBCardTableModRefBS* ctbs() { return _ct_bs; }
-
- template <class T> inline void immediate_rs_update(HeapRegion* from, T* p, int tid);
-
- template <class T> void deferred_rs_update(HeapRegion* from, T* p, int tid) {
- // If the new value of the field points to the same region or
- // is the to-space, we don't need to include it in the Rset updates.
- if (!from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) && !from->is_survivor()) {
- size_t card_index = ctbs()->index_for(p);
- // If the card hasn't been added to the buffer, do it.
- if (ctbs()->mark_card_deferred(card_index)) {
- dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
- }
- }
- }
-
-public:
- G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp);
-
- ~G1ParScanThreadState() {
- retire_alloc_buffers();
- FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base, mtGC);
- }
-
- RefToScanQueue* refs() { return _refs; }
- ageTable* age_table() { return &_age_table; }
-
- G1ParGCAllocBuffer* alloc_buffer(GCAllocPurpose purpose) {
- return _alloc_buffers[purpose];
- }
-
- size_t alloc_buffer_waste() const { return _alloc_buffer_waste; }
- size_t undo_waste() const { return _undo_waste; }
-
-#ifdef ASSERT
- bool verify_ref(narrowOop* ref) const;
- bool verify_ref(oop* ref) const;
- bool verify_task(StarTask ref) const;
-#endif // ASSERT
-
- template <class T> void push_on_queue(T* ref) {
- assert(verify_ref(ref), "sanity");
- refs()->push(ref);
- }
-
- template <class T> inline void update_rs(HeapRegion* from, T* p, int tid);
-
- HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
- HeapWord* obj = NULL;
- size_t gclab_word_size = _g1h->desired_plab_sz(purpose);
- if (word_sz * 100 < gclab_word_size * ParallelGCBufferWastePct) {
- G1ParGCAllocBuffer* alloc_buf = alloc_buffer(purpose);
- add_to_alloc_buffer_waste(alloc_buf->words_remaining());
- alloc_buf->retire(false /* end_of_gc */, false /* retain */);
-
- HeapWord* buf = _g1h->par_allocate_during_gc(purpose, gclab_word_size);
- if (buf == NULL) return NULL; // Let caller handle allocation failure.
- // Otherwise.
- alloc_buf->set_word_size(gclab_word_size);
- alloc_buf->set_buf(buf);
-
- obj = alloc_buf->allocate(word_sz);
- assert(obj != NULL, "buffer was definitely big enough...");
- } else {
- obj = _g1h->par_allocate_during_gc(purpose, word_sz);
- }
- return obj;
- }
-
- HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz) {
- HeapWord* obj = alloc_buffer(purpose)->allocate(word_sz);
- if (obj != NULL) return obj;
- return allocate_slow(purpose, word_sz);
- }
-
- void undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz) {
- if (alloc_buffer(purpose)->contains(obj)) {
- assert(alloc_buffer(purpose)->contains(obj + word_sz - 1),
- "should contain whole object");
- alloc_buffer(purpose)->undo_allocation(obj, word_sz);
- } else {
- CollectedHeap::fill_with_object(obj, word_sz);
- add_to_undo_waste(word_sz);
- }
- }
-
- void set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_cl) {
- _evac_failure_cl = evac_failure_cl;
- }
- OopsInHeapRegionClosure* evac_failure_closure() {
- return _evac_failure_cl;
- }
-
- int* hash_seed() { return &_hash_seed; }
- uint queue_num() { return _queue_num; }
-
- size_t term_attempts() const { return _term_attempts; }
- void note_term_attempt() { _term_attempts++; }
-
- void start_strong_roots() {
- _start_strong_roots = os::elapsedTime();
- }
- void end_strong_roots() {
- _strong_roots_time += (os::elapsedTime() - _start_strong_roots);
- }
- double strong_roots_time() const { return _strong_roots_time; }
-
- void start_term_time() {
- note_term_attempt();
- _start_term = os::elapsedTime();
- }
- void end_term_time() {
- _term_time += (os::elapsedTime() - _start_term);
- }
- double term_time() const { return _term_time; }
-
- double elapsed_time() const {
- return os::elapsedTime() - _start;
- }
-
- static void
- print_termination_stats_hdr(outputStream* const st = gclog_or_tty);
- void
- print_termination_stats(int i, outputStream* const st = gclog_or_tty) const;
-
- size_t* surviving_young_words() {
- // We add on to hide entry 0 which accumulates surviving words for
- // age -1 regions (i.e. non-young ones)
- return _surviving_young_words;
- }
-
-private:
- void retire_alloc_buffers() {
- for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
- size_t waste = _alloc_buffers[ap]->words_remaining();
- add_to_alloc_buffer_waste(waste);
- _alloc_buffers[ap]->flush_stats_and_retire(_g1h->stats_for_purpose((GCAllocPurpose)ap),
- true /* end_of_gc */,
- false /* retain */);
- }
- }
-
-#define G1_PARTIAL_ARRAY_MASK 0x2
-
- inline bool has_partial_array_mask(oop* ref) const {
- return ((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) == G1_PARTIAL_ARRAY_MASK;
- }
-
- // We never encode partial array oops as narrowOop*, so return false immediately.
- // This allows the compiler to create optimized code when popping references from
- // the work queue.
- inline bool has_partial_array_mask(narrowOop* ref) const {
- assert(((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) != G1_PARTIAL_ARRAY_MASK, "Partial array oop reference encoded as narrowOop*");
- return false;
- }
-
- // Only implement set_partial_array_mask() for regular oops, not for narrowOops.
- // We always encode partial arrays as regular oop, to allow the
- // specialization for has_partial_array_mask() for narrowOops above.
- // This means that unintentional use of this method with narrowOops are caught
- // by the compiler.
- inline oop* set_partial_array_mask(oop obj) const {
- assert(((uintptr_t)(void *)obj & G1_PARTIAL_ARRAY_MASK) == 0, "Information loss!");
- return (oop*) ((uintptr_t)(void *)obj | G1_PARTIAL_ARRAY_MASK);
- }
-
- inline oop clear_partial_array_mask(oop* ref) const {
- return cast_to_oop((intptr_t)ref & ~G1_PARTIAL_ARRAY_MASK);
- }
-
- inline void do_oop_partial_array(oop* p);
-
- // This method is applied to the fields of the objects that have just been copied.
- template <class T> void do_oop_evac(T* p, HeapRegion* from) {
- assert(!oopDesc::is_null(oopDesc::load_decode_heap_oop(p)),
- "Reference should not be NULL here as such are never pushed to the task queue.");
- oop obj = oopDesc::load_decode_heap_oop_not_null(p);
-
- // Although we never intentionally push references outside of the collection
- // set, due to (benign) races in the claim mechanism during RSet scanning more
- // than one thread might claim the same card. So the same card may be
- // processed multiple times. So redo this check.
- if (_g1h->in_cset_fast_test(obj)) {
- oop forwardee;
- if (obj->is_forwarded()) {
- forwardee = obj->forwardee();
- } else {
- forwardee = copy_to_survivor_space(obj);
- }
- assert(forwardee != NULL, "forwardee should not be NULL");
- oopDesc::encode_store_heap_oop(p, forwardee);
- }
-
- assert(obj != NULL, "Must be");
- update_rs(from, p, queue_num());
- }
-public:
-
- oop copy_to_survivor_space(oop const obj);
-
- template <class T> inline void deal_with_reference(T* ref_to_scan);
-
- inline void deal_with_reference(StarTask ref);
-
-public:
- void trim_queue();
-};
-
#endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1COLLECTEDHEAP_HPP
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,7 +29,6 @@
#include "gc_implementation/g1/g1CollectedHeap.hpp"
#include "gc_implementation/g1/g1AllocRegion.inline.hpp"
#include "gc_implementation/g1/g1CollectorPolicy.hpp"
-#include "gc_implementation/g1/g1RemSet.inline.hpp"
#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
#include "gc_implementation/g1/heapRegionSet.inline.hpp"
#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
@@ -289,89 +288,4 @@
return is_obj_ill(obj, heap_region_containing(obj));
}
-template <class T> inline void G1ParScanThreadState::immediate_rs_update(HeapRegion* from, T* p, int tid) {
- if (!from->is_survivor()) {
- _g1_rem->par_write_ref(from, p, tid);
- }
-}
-
-template <class T> void G1ParScanThreadState::update_rs(HeapRegion* from, T* p, int tid) {
- if (G1DeferredRSUpdate) {
- deferred_rs_update(from, p, tid);
- } else {
- immediate_rs_update(from, p, tid);
- }
-}
-
-
-inline void G1ParScanThreadState::do_oop_partial_array(oop* p) {
- assert(has_partial_array_mask(p), "invariant");
- oop from_obj = clear_partial_array_mask(p);
-
- assert(Universe::heap()->is_in_reserved(from_obj), "must be in heap.");
- assert(from_obj->is_objArray(), "must be obj array");
- objArrayOop from_obj_array = objArrayOop(from_obj);
- // The from-space object contains the real length.
- int length = from_obj_array->length();
-
- assert(from_obj->is_forwarded(), "must be forwarded");
- oop to_obj = from_obj->forwardee();
- assert(from_obj != to_obj, "should not be chunking self-forwarded objects");
- objArrayOop to_obj_array = objArrayOop(to_obj);
- // We keep track of the next start index in the length field of the
- // to-space object.
- int next_index = to_obj_array->length();
- assert(0 <= next_index && next_index < length,
- err_msg("invariant, next index: %d, length: %d", next_index, length));
-
- int start = next_index;
- int end = length;
- int remainder = end - start;
- // We'll try not to push a range that's smaller than ParGCArrayScanChunk.
- if (remainder > 2 * ParGCArrayScanChunk) {
- end = start + ParGCArrayScanChunk;
- to_obj_array->set_length(end);
- // Push the remainder before we process the range in case another
- // worker has run out of things to do and can steal it.
- oop* from_obj_p = set_partial_array_mask(from_obj);
- push_on_queue(from_obj_p);
- } else {
- assert(length == end, "sanity");
- // We'll process the final range for this object. Restore the length
- // so that the heap remains parsable in case of evacuation failure.
- to_obj_array->set_length(end);
- }
- _scanner.set_region(_g1h->heap_region_containing_raw(to_obj));
- // Process indexes [start,end). It will also process the header
- // along with the first chunk (i.e., the chunk with start == 0).
- // Note that at this point the length field of to_obj_array is not
- // correct given that we are using it to keep track of the next
- // start index. oop_iterate_range() (thankfully!) ignores the length
- // field and only relies on the start / end parameters. It does
- // however return the size of the object which will be incorrect. So
- // we have to ignore it even if we wanted to use it.
- to_obj_array->oop_iterate_range(&_scanner, start, end);
-}
-
-template <class T> inline void G1ParScanThreadState::deal_with_reference(T* ref_to_scan) {
- if (!has_partial_array_mask(ref_to_scan)) {
- // Note: we can use "raw" versions of "region_containing" because
- // "obj_to_scan" is definitely in the heap, and is not in a
- // humongous region.
- HeapRegion* r = _g1h->heap_region_containing_raw(ref_to_scan);
- do_oop_evac(ref_to_scan, r);
- } else {
- do_oop_partial_array((oop*)ref_to_scan);
- }
-}
-
-inline void G1ParScanThreadState::deal_with_reference(StarTask ref) {
- assert(verify_task(ref), "sanity");
- if (ref.is_narrow()) {
- deal_with_reference((narrowOop*)ref);
- } else {
- deal_with_reference((oop*)ref);
- }
-}
-
#endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1COLLECTEDHEAP_INLINE_HPP
--- a/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -71,6 +71,9 @@
bool _during_initial_mark;
bool _during_conc_mark;
uint _worker_id;
+ HeapWord* _end_of_last_gap;
+ HeapWord* _last_gap_threshold;
+ HeapWord* _last_obj_threshold;
public:
RemoveSelfForwardPtrObjClosure(G1CollectedHeap* g1, ConcurrentMark* cm,
@@ -83,7 +86,10 @@
_update_rset_cl(update_rset_cl),
_during_initial_mark(during_initial_mark),
_during_conc_mark(during_conc_mark),
- _worker_id(worker_id) { }
+ _worker_id(worker_id),
+ _end_of_last_gap(hr->bottom()),
+ _last_gap_threshold(hr->bottom()),
+ _last_obj_threshold(hr->bottom()) { }
size_t marked_bytes() { return _marked_bytes; }
@@ -107,7 +113,12 @@
HeapWord* obj_addr = (HeapWord*) obj;
assert(_hr->is_in(obj_addr), "sanity");
size_t obj_size = obj->size();
- _hr->update_bot_for_object(obj_addr, obj_size);
+ HeapWord* obj_end = obj_addr + obj_size;
+
+ if (_end_of_last_gap != obj_addr) {
+ // there was a gap before obj_addr
+ _last_gap_threshold = _hr->cross_threshold(_end_of_last_gap, obj_addr);
+ }
if (obj->is_forwarded() && obj->forwardee() == obj) {
// The object failed to move.
@@ -115,7 +126,9 @@
// We consider all objects that we find self-forwarded to be
// live. What we'll do is that we'll update the prev marking
// info so that they are all under PTAMS and explicitly marked.
- _cm->markPrev(obj);
+ if (!_cm->isPrevMarked(obj)) {
+ _cm->markPrev(obj);
+ }
if (_during_initial_mark) {
// For the next marking info we'll only mark the
// self-forwarded objects explicitly if we are during
@@ -145,13 +158,18 @@
// remembered set entries missing given that we skipped cards on
// the collection set. So, we'll recreate such entries now.
obj->oop_iterate(_update_rset_cl);
- assert(_cm->isPrevMarked(obj), "Should be marked!");
} else {
+
// The object has been either evacuated or is dead. Fill it with a
// dummy object.
- MemRegion mr((HeapWord*) obj, obj_size);
+ MemRegion mr(obj_addr, obj_size);
CollectedHeap::fill_with_object(mr);
+
+ // must nuke all dead objects which we skipped when iterating over the region
+ _cm->clearRangePrevBitmap(MemRegion(_end_of_last_gap, obj_end));
}
+ _end_of_last_gap = obj_end;
+ _last_obj_threshold = _hr->cross_threshold(obj_addr, obj_end);
}
};
@@ -182,13 +200,6 @@
during_conc_mark,
_worker_id);
- MemRegion mr(hr->bottom(), hr->end());
- // We'll recreate the prev marking info so we'll first clear
- // the prev bitmap range for this region. We never mark any
- // CSet objects explicitly so the next bitmap range should be
- // cleared anyway.
- _cm->clearRangePrevBitmap(mr);
-
hr->note_self_forwarding_removal_start(during_initial_mark,
during_conc_mark);
_g1h->check_bitmaps("Self-Forwarding Ptr Removal", hr);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -167,7 +167,6 @@
_last_update_rs_processed_buffers(_max_gc_threads, "%d"),
_last_scan_rs_times_ms(_max_gc_threads, "%.1lf"),
_last_strong_code_root_scan_times_ms(_max_gc_threads, "%.1lf"),
- _last_strong_code_root_mark_times_ms(_max_gc_threads, "%.1lf"),
_last_obj_copy_times_ms(_max_gc_threads, "%.1lf"),
_last_termination_times_ms(_max_gc_threads, "%.1lf"),
_last_termination_attempts(_max_gc_threads, SIZE_FORMAT),
@@ -194,7 +193,6 @@
_last_update_rs_processed_buffers.reset();
_last_scan_rs_times_ms.reset();
_last_strong_code_root_scan_times_ms.reset();
- _last_strong_code_root_mark_times_ms.reset();
_last_obj_copy_times_ms.reset();
_last_termination_times_ms.reset();
_last_termination_attempts.reset();
@@ -215,7 +213,6 @@
_last_update_rs_processed_buffers.verify();
_last_scan_rs_times_ms.verify();
_last_strong_code_root_scan_times_ms.verify();
- _last_strong_code_root_mark_times_ms.verify();
_last_obj_copy_times_ms.verify();
_last_termination_times_ms.verify();
_last_termination_attempts.verify();
@@ -230,7 +227,6 @@
_last_update_rs_times_ms.get(i) +
_last_scan_rs_times_ms.get(i) +
_last_strong_code_root_scan_times_ms.get(i) +
- _last_strong_code_root_mark_times_ms.get(i) +
_last_obj_copy_times_ms.get(i) +
_last_termination_times_ms.get(i);
@@ -302,9 +298,6 @@
if (_last_satb_filtering_times_ms.sum() > 0.0) {
_last_satb_filtering_times_ms.print(2, "SATB Filtering (ms)");
}
- if (_last_strong_code_root_mark_times_ms.sum() > 0.0) {
- _last_strong_code_root_mark_times_ms.print(2, "Code Root Marking (ms)");
- }
_last_update_rs_times_ms.print(2, "Update RS (ms)");
_last_update_rs_processed_buffers.print(3, "Processed Buffers");
_last_scan_rs_times_ms.print(2, "Scan RS (ms)");
@@ -322,9 +315,6 @@
if (_last_satb_filtering_times_ms.sum() > 0.0) {
_last_satb_filtering_times_ms.print(1, "SATB Filtering (ms)");
}
- if (_last_strong_code_root_mark_times_ms.sum() > 0.0) {
- _last_strong_code_root_mark_times_ms.print(1, "Code Root Marking (ms)");
- }
_last_update_rs_times_ms.print(1, "Update RS (ms)");
_last_update_rs_processed_buffers.print(2, "Processed Buffers");
_last_scan_rs_times_ms.print(1, "Scan RS (ms)");
--- a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -120,7 +120,6 @@
WorkerDataArray<int> _last_update_rs_processed_buffers;
WorkerDataArray<double> _last_scan_rs_times_ms;
WorkerDataArray<double> _last_strong_code_root_scan_times_ms;
- WorkerDataArray<double> _last_strong_code_root_mark_times_ms;
WorkerDataArray<double> _last_obj_copy_times_ms;
WorkerDataArray<double> _last_termination_times_ms;
WorkerDataArray<size_t> _last_termination_attempts;
@@ -199,10 +198,6 @@
_last_strong_code_root_scan_times_ms.set(worker_i, ms);
}
- void record_strong_code_root_mark_time(uint worker_i, double ms) {
- _last_strong_code_root_mark_times_ms.set(worker_i, ms);
- }
-
void record_obj_copy_time(uint worker_i, double ms) {
_last_obj_copy_times_ms.set(worker_i, ms);
}
@@ -369,10 +364,6 @@
return _last_strong_code_root_scan_times_ms.average();
}
- double average_last_strong_code_root_mark_time(){
- return _last_strong_code_root_mark_times_ms.average();
- }
-
double average_last_obj_copy_time() {
return _last_obj_copy_times_ms.average();
}
--- a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -129,13 +129,15 @@
SharedHeap* sh = SharedHeap::heap();
- // Need cleared claim bits for the strong roots processing
+ // Need cleared claim bits for the roots processing
ClassLoaderDataGraph::clear_claimed_marks();
- sh->process_strong_roots(true, // activate StrongRootsScope
- SharedHeap::SO_SystemClasses,
+ MarkingCodeBlobClosure follow_code_closure(&GenMarkSweep::follow_root_closure, !CodeBlobToOopClosure::FixRelocations);
+ sh->process_strong_roots(true, // activate StrongRootsScope
+ SharedHeap::SO_None,
&GenMarkSweep::follow_root_closure,
- &GenMarkSweep::follow_klass_closure);
+ &GenMarkSweep::follow_cld_closure,
+ &follow_code_closure);
// Process reference objects found during marking
ReferenceProcessor* rp = GenMarkSweep::ref_processor();
@@ -304,13 +306,15 @@
SharedHeap* sh = SharedHeap::heap();
- // Need cleared claim bits for the strong roots processing
+ // Need cleared claim bits for the roots processing
ClassLoaderDataGraph::clear_claimed_marks();
- sh->process_strong_roots(true, // activate StrongRootsScope
- SharedHeap::SO_AllClasses | SharedHeap::SO_Strings | SharedHeap::SO_AllCodeCache,
- &GenMarkSweep::adjust_pointer_closure,
- &GenMarkSweep::adjust_klass_closure);
+ CodeBlobToOopClosure adjust_code_closure(&GenMarkSweep::adjust_pointer_closure, CodeBlobToOopClosure::FixRelocations);
+ sh->process_all_roots(true, // activate StrongRootsScope
+ SharedHeap::SO_AllCodeCache,
+ &GenMarkSweep::adjust_pointer_closure,
+ &GenMarkSweep::adjust_cld_closure,
+ &adjust_code_closure);
assert(GenMarkSweep::ref_processor() == g1h->ref_processor_stw(), "Sanity");
g1h->ref_processor_stw()->weak_oops_do(&GenMarkSweep::adjust_pointer_closure);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,7 +25,28 @@
#include "precompiled.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
+#include "gc_implementation/g1/g1ParScanThreadState.hpp"
G1ParCopyHelper::G1ParCopyHelper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
G1ParClosureSuper(g1, par_scan_state), _scanned_klass(NULL),
_cm(_g1->concurrent_mark()) {}
+
+G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1) :
+ _g1(g1), _par_scan_state(NULL), _worker_id(UINT_MAX) { }
+
+G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
+ _g1(g1), _par_scan_state(NULL),
+ _worker_id(UINT_MAX) {
+ set_par_scan_thread_state(par_scan_state);
+}
+
+void G1ParClosureSuper::set_par_scan_thread_state(G1ParScanThreadState* par_scan_state) {
+ assert(_par_scan_state == NULL, "_par_scan_state must only be set once");
+ assert(par_scan_state != NULL, "Must set par_scan_state to non-NULL.");
+
+ _par_scan_state = par_scan_state;
+ _worker_id = par_scan_state->queue_num();
+
+ assert(_worker_id < MAX2((uint)ParallelGCThreads, 1u),
+ err_msg("The given worker id %u must be less than the number of threads %u", _worker_id, MAX2((uint)ParallelGCThreads, 1u)));
+}
--- a/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,6 +25,8 @@
#ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP
#define SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP
+#include "memory/iterator.hpp"
+
class HeapRegion;
class G1CollectedHeap;
class G1RemSet;
@@ -51,8 +53,13 @@
G1ParScanThreadState* _par_scan_state;
uint _worker_id;
public:
+ // Initializes the instance, leaving _par_scan_state uninitialized. Must be done
+ // later using the set_par_scan_thread_state() method.
+ G1ParClosureSuper(G1CollectedHeap* g1);
G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state);
bool apply_to_weak_ref_discovered_field() { return true; }
+
+ void set_par_scan_thread_state(G1ParScanThreadState* par_scan_state);
};
class G1ParPushHeapRSClosure : public G1ParClosureSuper {
@@ -68,9 +75,8 @@
class G1ParScanClosure : public G1ParClosureSuper {
public:
- G1ParScanClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) :
- G1ParClosureSuper(g1, par_scan_state)
- {
+ G1ParScanClosure(G1CollectedHeap* g1, ReferenceProcessor* rp) :
+ G1ParClosureSuper(g1) {
assert(_ref_processor == NULL, "sanity");
_ref_processor = rp;
}
@@ -102,7 +108,7 @@
template <class T> void do_klass_barrier(T* p, oop new_obj);
};
-template <G1Barrier barrier, bool do_mark_object>
+template <G1Barrier barrier, G1Mark do_mark_object>
class G1ParCopyClosure : public G1ParCopyHelper {
private:
template <class T> void do_oop_work(T* p);
@@ -117,19 +123,19 @@
template <class T> void do_oop_nv(T* p) { do_oop_work(p); }
virtual void do_oop(oop* p) { do_oop_nv(p); }
virtual void do_oop(narrowOop* p) { do_oop_nv(p); }
+
+ G1CollectedHeap* g1() { return _g1; };
+ G1ParScanThreadState* pss() { return _par_scan_state; }
+ ReferenceProcessor* rp() { return _ref_processor; };
};
-typedef G1ParCopyClosure<G1BarrierNone, false> G1ParScanExtRootClosure;
-typedef G1ParCopyClosure<G1BarrierKlass, false> G1ParScanMetadataClosure;
-
-
-typedef G1ParCopyClosure<G1BarrierNone, true> G1ParScanAndMarkExtRootClosure;
-typedef G1ParCopyClosure<G1BarrierKlass, true> G1ParScanAndMarkMetadataClosure;
-
+typedef G1ParCopyClosure<G1BarrierNone, G1MarkNone> G1ParScanExtRootClosure;
+typedef G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot> G1ParScanAndMarkExtRootClosure;
+typedef G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> G1ParScanAndMarkWeakExtRootClosure;
// We use a separate closure to handle references during evacuation
// failure processing.
-typedef G1ParCopyClosure<G1BarrierEvac, false> G1ParScanHeapEvacFailureClosure;
+typedef G1ParCopyClosure<G1BarrierEvac, G1MarkNone> G1ParScanHeapEvacFailureClosure;
class FilterIntoCSClosure: public ExtendedOopClosure {
G1CollectedHeap* _g1;
@@ -160,10 +166,11 @@
};
// Closure for iterating over object fields during concurrent marking
-class G1CMOopClosure : public ExtendedOopClosure {
+class G1CMOopClosure : public MetadataAwareOopClosure {
+protected:
+ ConcurrentMark* _cm;
private:
G1CollectedHeap* _g1h;
- ConcurrentMark* _cm;
CMTask* _task;
public:
G1CMOopClosure(G1CollectedHeap* g1h, ConcurrentMark* cm, CMTask* task);
@@ -173,7 +180,7 @@
};
// Closure to scan the root regions during concurrent marking
-class G1RootRegionScanClosure : public ExtendedOopClosure {
+class G1RootRegionScanClosure : public MetadataAwareOopClosure {
private:
G1CollectedHeap* _g1h;
ConcurrentMark* _cm;
--- a/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -28,9 +28,11 @@
#include "gc_implementation/g1/concurrentMark.inline.hpp"
#include "gc_implementation/g1/g1CollectedHeap.hpp"
#include "gc_implementation/g1/g1OopClosures.hpp"
+#include "gc_implementation/g1/g1ParScanThreadState.inline.hpp"
#include "gc_implementation/g1/g1RemSet.hpp"
#include "gc_implementation/g1/g1RemSet.inline.hpp"
#include "gc_implementation/g1/heapRegionRemSet.hpp"
+#include "memory/iterator.inline.hpp"
#include "runtime/prefetch.inline.hpp"
/*
@@ -107,10 +109,6 @@
template <class T>
inline void G1CMOopClosure::do_oop_nv(T* p) {
- assert(_g1h->is_in_g1_reserved((HeapWord*) p), "invariant");
- assert(!_g1h->is_on_master_free_list(
- _g1h->heap_region_containing((HeapWord*) p)), "invariant");
-
oop obj = oopDesc::load_decode_heap_oop(p);
if (_cm->verbose_high()) {
gclog_or_tty->print_cr("[%u] we're looking at location "
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,306 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
+#include "gc_implementation/g1/g1OopClosures.inline.hpp"
+#include "gc_implementation/g1/g1ParScanThreadState.inline.hpp"
+#include "oops/oop.inline.hpp"
+#include "oops/oop.pcgc.inline.hpp"
+#include "runtime/prefetch.inline.hpp"
+
+G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp)
+ : _g1h(g1h),
+ _refs(g1h->task_queue(queue_num)),
+ _dcq(&g1h->dirty_card_queue_set()),
+ _ct_bs(g1h->g1_barrier_set()),
+ _g1_rem(g1h->g1_rem_set()),
+ _hash_seed(17), _queue_num(queue_num),
+ _term_attempts(0),
+ _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
+ _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
+ _age_table(false), _scanner(g1h, rp),
+ _strong_roots_time(0), _term_time(0),
+ _alloc_buffer_waste(0), _undo_waste(0) {
+ _scanner.set_par_scan_thread_state(this);
+ // we allocate G1YoungSurvRateNumRegions plus one entries, since
+ // we "sacrifice" entry 0 to keep track of surviving bytes for
+ // non-young regions (where the age is -1)
+ // We also add a few elements at the beginning and at the end in
+ // an attempt to eliminate cache contention
+ uint real_length = 1 + _g1h->g1_policy()->young_cset_region_length();
+ uint array_length = PADDING_ELEM_NUM +
+ real_length +
+ PADDING_ELEM_NUM;
+ _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
+ if (_surviving_young_words_base == NULL)
+ vm_exit_out_of_memory(array_length * sizeof(size_t), OOM_MALLOC_ERROR,
+ "Not enough space for young surv histo.");
+ _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
+ memset(_surviving_young_words, 0, (size_t) real_length * sizeof(size_t));
+
+ _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
+ _alloc_buffers[GCAllocForTenured] = &_tenured_alloc_buffer;
+
+ _start = os::elapsedTime();
+}
+
+G1ParScanThreadState::~G1ParScanThreadState() {
+ retire_alloc_buffers();
+ FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base, mtGC);
+}
+
+void
+G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
+{
+ st->print_raw_cr("GC Termination Stats");
+ st->print_raw_cr(" elapsed --strong roots-- -------termination-------"
+ " ------waste (KiB)------");
+ st->print_raw_cr("thr ms ms % ms % attempts"
+ " total alloc undo");
+ st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
+ " ------- ------- -------");
+}
+
+void
+G1ParScanThreadState::print_termination_stats(int i,
+ outputStream* const st) const
+{
+ const double elapsed_ms = elapsed_time() * 1000.0;
+ const double s_roots_ms = strong_roots_time() * 1000.0;
+ const double term_ms = term_time() * 1000.0;
+ st->print_cr("%3d %9.2f %9.2f %6.2f "
+ "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
+ SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
+ i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
+ term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
+ (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
+ alloc_buffer_waste() * HeapWordSize / K,
+ undo_waste() * HeapWordSize / K);
+}
+
+#ifdef ASSERT
+bool G1ParScanThreadState::verify_ref(narrowOop* ref) const {
+ assert(ref != NULL, "invariant");
+ assert(UseCompressedOops, "sanity");
+ assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, p2i(ref)));
+ oop p = oopDesc::load_decode_heap_oop(ref);
+ assert(_g1h->is_in_g1_reserved(p),
+ err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, p2i(ref), p2i(p)));
+ return true;
+}
+
+bool G1ParScanThreadState::verify_ref(oop* ref) const {
+ assert(ref != NULL, "invariant");
+ if (has_partial_array_mask(ref)) {
+ // Must be in the collection set--it's already been copied.
+ oop p = clear_partial_array_mask(ref);
+ assert(_g1h->obj_in_cs(p),
+ err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, p2i(ref), p2i(p)));
+ } else {
+ oop p = oopDesc::load_decode_heap_oop(ref);
+ assert(_g1h->is_in_g1_reserved(p),
+ err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, p2i(ref), p2i(p)));
+ }
+ return true;
+}
+
+bool G1ParScanThreadState::verify_task(StarTask ref) const {
+ if (ref.is_narrow()) {
+ return verify_ref((narrowOop*) ref);
+ } else {
+ return verify_ref((oop*) ref);
+ }
+}
+#endif // ASSERT
+
+void G1ParScanThreadState::trim_queue() {
+ assert(_evac_failure_cl != NULL, "not set");
+
+ StarTask ref;
+ do {
+ // Drain the overflow stack first, so other threads can steal.
+ while (_refs->pop_overflow(ref)) {
+ dispatch_reference(ref);
+ }
+
+ while (_refs->pop_local(ref)) {
+ dispatch_reference(ref);
+ }
+ } while (!_refs->is_empty());
+}
+
+oop G1ParScanThreadState::copy_to_survivor_space(oop const old) {
+ size_t word_sz = old->size();
+ HeapRegion* from_region = _g1h->heap_region_containing_raw(old);
+ // +1 to make the -1 indexes valid...
+ int young_index = from_region->young_index_in_cset()+1;
+ assert( (from_region->is_young() && young_index > 0) ||
+ (!from_region->is_young() && young_index == 0), "invariant" );
+ G1CollectorPolicy* g1p = _g1h->g1_policy();
+ markOop m = old->mark();
+ int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
+ : m->age();
+ GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
+ word_sz);
+ HeapWord* obj_ptr = allocate(alloc_purpose, word_sz);
+#ifndef PRODUCT
+ // Should this evacuation fail?
+ if (_g1h->evacuation_should_fail()) {
+ if (obj_ptr != NULL) {
+ undo_allocation(alloc_purpose, obj_ptr, word_sz);
+ obj_ptr = NULL;
+ }
+ }
+#endif // !PRODUCT
+
+ if (obj_ptr == NULL) {
+ // This will either forward-to-self, or detect that someone else has
+ // installed a forwarding pointer.
+ return _g1h->handle_evacuation_failure_par(this, old);
+ }
+
+ oop obj = oop(obj_ptr);
+
+ // We're going to allocate linearly, so might as well prefetch ahead.
+ Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
+
+ oop forward_ptr = old->forward_to_atomic(obj);
+ if (forward_ptr == NULL) {
+ Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
+
+ // alloc_purpose is just a hint to allocate() above, recheck the type of region
+ // we actually allocated from and update alloc_purpose accordingly
+ HeapRegion* to_region = _g1h->heap_region_containing_raw(obj_ptr);
+ alloc_purpose = to_region->is_young() ? GCAllocForSurvived : GCAllocForTenured;
+
+ if (g1p->track_object_age(alloc_purpose)) {
+ // We could simply do obj->incr_age(). However, this causes a
+ // performance issue. obj->incr_age() will first check whether
+ // the object has a displaced mark by checking its mark word;
+ // getting the mark word from the new location of the object
+ // stalls. So, given that we already have the mark word and we
+ // are about to install it anyway, it's better to increase the
+ // age on the mark word, when the object does not have a
+ // displaced mark word. We're not expecting many objects to have
+ // a displaced marked word, so that case is not optimized
+ // further (it could be...) and we simply call obj->incr_age().
+
+ if (m->has_displaced_mark_helper()) {
+ // in this case, we have to install the mark word first,
+ // otherwise obj looks to be forwarded (the old mark word,
+ // which contains the forward pointer, was copied)
+ obj->set_mark(m);
+ obj->incr_age();
+ } else {
+ m = m->incr_age();
+ obj->set_mark(m);
+ }
+ age_table()->add(obj, word_sz);
+ } else {
+ obj->set_mark(m);
+ }
+
+ if (G1StringDedup::is_enabled()) {
+ G1StringDedup::enqueue_from_evacuation(from_region->is_young(),
+ to_region->is_young(),
+ queue_num(),
+ obj);
+ }
+
+ size_t* surv_young_words = surviving_young_words();
+ surv_young_words[young_index] += word_sz;
+
+ if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
+ // We keep track of the next start index in the length field of
+ // the to-space object. The actual length can be found in the
+ // length field of the from-space object.
+ arrayOop(obj)->set_length(0);
+ oop* old_p = set_partial_array_mask(old);
+ push_on_queue(old_p);
+ } else {
+ // No point in using the slower heap_region_containing() method,
+ // given that we know obj is in the heap.
+ _scanner.set_region(_g1h->heap_region_containing_raw(obj));
+ obj->oop_iterate_backwards(&_scanner);
+ }
+ } else {
+ undo_allocation(alloc_purpose, obj_ptr, word_sz);
+ obj = forward_ptr;
+ }
+ return obj;
+}
+
+HeapWord* G1ParScanThreadState::allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
+ HeapWord* obj = NULL;
+ size_t gclab_word_size = _g1h->desired_plab_sz(purpose);
+ if (word_sz * 100 < gclab_word_size * ParallelGCBufferWastePct) {
+ G1ParGCAllocBuffer* alloc_buf = alloc_buffer(purpose);
+ add_to_alloc_buffer_waste(alloc_buf->words_remaining());
+ alloc_buf->retire(false /* end_of_gc */, false /* retain */);
+
+ HeapWord* buf = _g1h->par_allocate_during_gc(purpose, gclab_word_size);
+ if (buf == NULL) {
+ return NULL; // Let caller handle allocation failure.
+ }
+ // Otherwise.
+ alloc_buf->set_word_size(gclab_word_size);
+ alloc_buf->set_buf(buf);
+
+ obj = alloc_buf->allocate(word_sz);
+ assert(obj != NULL, "buffer was definitely big enough...");
+ } else {
+ obj = _g1h->par_allocate_during_gc(purpose, word_sz);
+ }
+ return obj;
+}
+
+void G1ParScanThreadState::undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz) {
+ if (alloc_buffer(purpose)->contains(obj)) {
+ assert(alloc_buffer(purpose)->contains(obj + word_sz - 1),
+ "should contain whole object");
+ alloc_buffer(purpose)->undo_allocation(obj, word_sz);
+ } else {
+ CollectedHeap::fill_with_object(obj, word_sz);
+ add_to_undo_waste(word_sz);
+ }
+}
+
+HeapWord* G1ParScanThreadState::allocate(GCAllocPurpose purpose, size_t word_sz) {
+ HeapWord* obj = alloc_buffer(purpose)->allocate(word_sz);
+ if (obj != NULL) {
+ return obj;
+ }
+ return allocate_slow(purpose, word_sz);
+}
+
+void G1ParScanThreadState::retire_alloc_buffers() {
+ for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
+ size_t waste = _alloc_buffers[ap]->words_remaining();
+ add_to_alloc_buffer_waste(waste);
+ _alloc_buffers[ap]->flush_stats_and_retire(_g1h->stats_for_purpose((GCAllocPurpose)ap),
+ true /* end_of_gc */,
+ false /* retain */);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1PARSCANTHREADSTATE_HPP
+#define SHARE_VM_GC_IMPLEMENTATION_G1_G1PARSCANTHREADSTATE_HPP
+
+#include "gc_implementation/g1/dirtyCardQueue.hpp"
+#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
+#include "gc_implementation/g1/g1CollectedHeap.hpp"
+#include "gc_implementation/g1/g1CollectorPolicy.hpp"
+#include "gc_implementation/g1/g1OopClosures.hpp"
+#include "gc_implementation/g1/g1RemSet.hpp"
+#include "gc_implementation/shared/ageTable.hpp"
+#include "memory/allocation.hpp"
+#include "oops/oop.hpp"
+
+class HeapRegion;
+class outputStream;
+
+class G1ParScanThreadState : public StackObj {
+ private:
+ G1CollectedHeap* _g1h;
+ RefToScanQueue* _refs;
+ DirtyCardQueue _dcq;
+ G1SATBCardTableModRefBS* _ct_bs;
+ G1RemSet* _g1_rem;
+
+ G1ParGCAllocBuffer _surviving_alloc_buffer;
+ G1ParGCAllocBuffer _tenured_alloc_buffer;
+ G1ParGCAllocBuffer* _alloc_buffers[GCAllocPurposeCount];
+ ageTable _age_table;
+
+ G1ParScanClosure _scanner;
+
+ size_t _alloc_buffer_waste;
+ size_t _undo_waste;
+
+ OopsInHeapRegionClosure* _evac_failure_cl;
+
+ int _hash_seed;
+ uint _queue_num;
+
+ size_t _term_attempts;
+
+ double _start;
+ double _start_strong_roots;
+ double _strong_roots_time;
+ double _start_term;
+ double _term_time;
+
+ // Map from young-age-index (0 == not young, 1 is youngest) to
+ // surviving words. base is what we get back from the malloc call
+ size_t* _surviving_young_words_base;
+ // this points into the array, as we use the first few entries for padding
+ size_t* _surviving_young_words;
+
+#define PADDING_ELEM_NUM (DEFAULT_CACHE_LINE_SIZE / sizeof(size_t))
+
+ void add_to_alloc_buffer_waste(size_t waste) { _alloc_buffer_waste += waste; }
+
+ void add_to_undo_waste(size_t waste) { _undo_waste += waste; }
+
+ DirtyCardQueue& dirty_card_queue() { return _dcq; }
+ G1SATBCardTableModRefBS* ctbs() { return _ct_bs; }
+
+ template <class T> inline void immediate_rs_update(HeapRegion* from, T* p, int tid);
+
+ template <class T> void deferred_rs_update(HeapRegion* from, T* p, int tid) {
+ // If the new value of the field points to the same region or
+ // is the to-space, we don't need to include it in the Rset updates.
+ if (!from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) && !from->is_survivor()) {
+ size_t card_index = ctbs()->index_for(p);
+ // If the card hasn't been added to the buffer, do it.
+ if (ctbs()->mark_card_deferred(card_index)) {
+ dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
+ }
+ }
+ }
+
+ public:
+ G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp);
+ ~G1ParScanThreadState();
+
+ ageTable* age_table() { return &_age_table; }
+
+ G1ParGCAllocBuffer* alloc_buffer(GCAllocPurpose purpose) {
+ return _alloc_buffers[purpose];
+ }
+
+ size_t alloc_buffer_waste() const { return _alloc_buffer_waste; }
+ size_t undo_waste() const { return _undo_waste; }
+
+#ifdef ASSERT
+ bool queue_is_empty() const { return _refs->is_empty(); }
+
+ bool verify_ref(narrowOop* ref) const;
+ bool verify_ref(oop* ref) const;
+ bool verify_task(StarTask ref) const;
+#endif // ASSERT
+
+ template <class T> void push_on_queue(T* ref) {
+ assert(verify_ref(ref), "sanity");
+ _refs->push(ref);
+ }
+
+ template <class T> inline void update_rs(HeapRegion* from, T* p, int tid);
+
+ private:
+
+ inline HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz);
+ inline HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz);
+ inline void undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz);
+
+ public:
+
+ void set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_cl) {
+ _evac_failure_cl = evac_failure_cl;
+ }
+
+ OopsInHeapRegionClosure* evac_failure_closure() { return _evac_failure_cl; }
+
+ int* hash_seed() { return &_hash_seed; }
+ uint queue_num() { return _queue_num; }
+
+ size_t term_attempts() const { return _term_attempts; }
+ void note_term_attempt() { _term_attempts++; }
+
+ void start_strong_roots() {
+ _start_strong_roots = os::elapsedTime();
+ }
+ void end_strong_roots() {
+ _strong_roots_time += (os::elapsedTime() - _start_strong_roots);
+ }
+ double strong_roots_time() const { return _strong_roots_time; }
+
+ void start_term_time() {
+ note_term_attempt();
+ _start_term = os::elapsedTime();
+ }
+ void end_term_time() {
+ _term_time += (os::elapsedTime() - _start_term);
+ }
+ double term_time() const { return _term_time; }
+
+ double elapsed_time() const {
+ return os::elapsedTime() - _start;
+ }
+
+ static void print_termination_stats_hdr(outputStream* const st = gclog_or_tty);
+ void print_termination_stats(int i, outputStream* const st = gclog_or_tty) const;
+
+ size_t* surviving_young_words() {
+ // We add on to hide entry 0 which accumulates surviving words for
+ // age -1 regions (i.e. non-young ones)
+ return _surviving_young_words;
+ }
+
+ private:
+ void retire_alloc_buffers();
+
+ #define G1_PARTIAL_ARRAY_MASK 0x2
+
+ inline bool has_partial_array_mask(oop* ref) const {
+ return ((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) == G1_PARTIAL_ARRAY_MASK;
+ }
+
+ // We never encode partial array oops as narrowOop*, so return false immediately.
+ // This allows the compiler to create optimized code when popping references from
+ // the work queue.
+ inline bool has_partial_array_mask(narrowOop* ref) const {
+ assert(((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) != G1_PARTIAL_ARRAY_MASK, "Partial array oop reference encoded as narrowOop*");
+ return false;
+ }
+
+ // Only implement set_partial_array_mask() for regular oops, not for narrowOops.
+ // We always encode partial arrays as regular oop, to allow the
+ // specialization for has_partial_array_mask() for narrowOops above.
+ // This means that unintentional use of this method with narrowOops are caught
+ // by the compiler.
+ inline oop* set_partial_array_mask(oop obj) const {
+ assert(((uintptr_t)(void *)obj & G1_PARTIAL_ARRAY_MASK) == 0, "Information loss!");
+ return (oop*) ((uintptr_t)(void *)obj | G1_PARTIAL_ARRAY_MASK);
+ }
+
+ inline oop clear_partial_array_mask(oop* ref) const {
+ return cast_to_oop((intptr_t)ref & ~G1_PARTIAL_ARRAY_MASK);
+ }
+
+ inline void do_oop_partial_array(oop* p);
+
+ // This method is applied to the fields of the objects that have just been copied.
+ template <class T> inline void do_oop_evac(T* p, HeapRegion* from);
+
+ template <class T> inline void deal_with_reference(T* ref_to_scan);
+
+ inline void dispatch_reference(StarTask ref);
+ public:
+
+ oop copy_to_survivor_space(oop const obj);
+
+ void trim_queue();
+
+ inline void steal_and_trim_queue(RefToScanQueueSet *task_queues);
+};
+
+#endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1PARSCANTHREADSTATE_HPP
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1PARSCANTHREADSTATE_INLINE_HPP
+#define SHARE_VM_GC_IMPLEMENTATION_G1_G1PARSCANTHREADSTATE_INLINE_HPP
+
+#include "gc_implementation/g1/g1ParScanThreadState.hpp"
+#include "gc_implementation/g1/g1RemSet.inline.hpp"
+#include "oops/oop.inline.hpp"
+
+template <class T> inline void G1ParScanThreadState::immediate_rs_update(HeapRegion* from, T* p, int tid) {
+ if (!from->is_survivor()) {
+ _g1_rem->par_write_ref(from, p, tid);
+ }
+}
+
+template <class T> void G1ParScanThreadState::update_rs(HeapRegion* from, T* p, int tid) {
+ if (G1DeferredRSUpdate) {
+ deferred_rs_update(from, p, tid);
+ } else {
+ immediate_rs_update(from, p, tid);
+ }
+}
+
+template <class T> void G1ParScanThreadState::do_oop_evac(T* p, HeapRegion* from) {
+ assert(!oopDesc::is_null(oopDesc::load_decode_heap_oop(p)),
+ "Reference should not be NULL here as such are never pushed to the task queue.");
+ oop obj = oopDesc::load_decode_heap_oop_not_null(p);
+
+ // Although we never intentionally push references outside of the collection
+ // set, due to (benign) races in the claim mechanism during RSet scanning more
+ // than one thread might claim the same card. So the same card may be
+ // processed multiple times. So redo this check.
+ if (_g1h->in_cset_fast_test(obj)) {
+ oop forwardee;
+ if (obj->is_forwarded()) {
+ forwardee = obj->forwardee();
+ } else {
+ forwardee = copy_to_survivor_space(obj);
+ }
+ assert(forwardee != NULL, "forwardee should not be NULL");
+ oopDesc::encode_store_heap_oop(p, forwardee);
+ }
+
+ assert(obj != NULL, "Must be");
+ update_rs(from, p, queue_num());
+}
+
+inline void G1ParScanThreadState::do_oop_partial_array(oop* p) {
+ assert(has_partial_array_mask(p), "invariant");
+ oop from_obj = clear_partial_array_mask(p);
+
+ assert(Universe::heap()->is_in_reserved(from_obj), "must be in heap.");
+ assert(from_obj->is_objArray(), "must be obj array");
+ objArrayOop from_obj_array = objArrayOop(from_obj);
+ // The from-space object contains the real length.
+ int length = from_obj_array->length();
+
+ assert(from_obj->is_forwarded(), "must be forwarded");
+ oop to_obj = from_obj->forwardee();
+ assert(from_obj != to_obj, "should not be chunking self-forwarded objects");
+ objArrayOop to_obj_array = objArrayOop(to_obj);
+ // We keep track of the next start index in the length field of the
+ // to-space object.
+ int next_index = to_obj_array->length();
+ assert(0 <= next_index && next_index < length,
+ err_msg("invariant, next index: %d, length: %d", next_index, length));
+
+ int start = next_index;
+ int end = length;
+ int remainder = end - start;
+ // We'll try not to push a range that's smaller than ParGCArrayScanChunk.
+ if (remainder > 2 * ParGCArrayScanChunk) {
+ end = start + ParGCArrayScanChunk;
+ to_obj_array->set_length(end);
+ // Push the remainder before we process the range in case another
+ // worker has run out of things to do and can steal it.
+ oop* from_obj_p = set_partial_array_mask(from_obj);
+ push_on_queue(from_obj_p);
+ } else {
+ assert(length == end, "sanity");
+ // We'll process the final range for this object. Restore the length
+ // so that the heap remains parsable in case of evacuation failure.
+ to_obj_array->set_length(end);
+ }
+ _scanner.set_region(_g1h->heap_region_containing_raw(to_obj));
+ // Process indexes [start,end). It will also process the header
+ // along with the first chunk (i.e., the chunk with start == 0).
+ // Note that at this point the length field of to_obj_array is not
+ // correct given that we are using it to keep track of the next
+ // start index. oop_iterate_range() (thankfully!) ignores the length
+ // field and only relies on the start / end parameters. It does
+ // however return the size of the object which will be incorrect. So
+ // we have to ignore it even if we wanted to use it.
+ to_obj_array->oop_iterate_range(&_scanner, start, end);
+}
+
+template <class T> inline void G1ParScanThreadState::deal_with_reference(T* ref_to_scan) {
+ if (!has_partial_array_mask(ref_to_scan)) {
+ // Note: we can use "raw" versions of "region_containing" because
+ // "obj_to_scan" is definitely in the heap, and is not in a
+ // humongous region.
+ HeapRegion* r = _g1h->heap_region_containing_raw(ref_to_scan);
+ do_oop_evac(ref_to_scan, r);
+ } else {
+ do_oop_partial_array((oop*)ref_to_scan);
+ }
+}
+
+inline void G1ParScanThreadState::dispatch_reference(StarTask ref) {
+ assert(verify_task(ref), "sanity");
+ if (ref.is_narrow()) {
+ deal_with_reference((narrowOop*)ref);
+ } else {
+ deal_with_reference((oop*)ref);
+ }
+}
+
+void G1ParScanThreadState::steal_and_trim_queue(RefToScanQueueSet *task_queues) {
+ StarTask stolen_task;
+ while (task_queues->steal(queue_num(), hash_seed(), stolen_task)) {
+ assert(verify_task(stolen_task), "sanity");
+ dispatch_reference(stolen_task);
+
+ // We've just processed a reference and we might have made
+ // available new entries on the queues. So we have to make sure
+ // we drain the queues as necessary.
+ trim_queue();
+ }
+}
+
+#endif /* SHARE_VM_GC_IMPLEMENTATION_G1_G1PARSCANTHREADSTATE_INLINE_HPP */
+
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,6 +26,7 @@
#define SHARE_VM_GC_IMPLEMENTATION_G1_G1REMSET_INLINE_HPP
#include "gc_implementation/g1/g1RemSet.hpp"
+#include "gc_implementation/g1/heapRegion.hpp"
#include "gc_implementation/g1/heapRegionRemSet.hpp"
#include "oops/oop.inline.hpp"
--- a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -66,6 +66,17 @@
}
}
+void G1SATBCardTableModRefBS::write_ref_array_pre(oop* dst, int count, bool dest_uninitialized) {
+ if (!dest_uninitialized) {
+ write_ref_array_pre_work(dst, count);
+ }
+}
+void G1SATBCardTableModRefBS::write_ref_array_pre(narrowOop* dst, int count, bool dest_uninitialized) {
+ if (!dest_uninitialized) {
+ write_ref_array_pre_work(dst, count);
+ }
+}
+
bool G1SATBCardTableModRefBS::mark_card_deferred(size_t card_index) {
jbyte val = _byte_map[card_index];
// It's already processed
--- a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -86,16 +86,8 @@
}
template <class T> void write_ref_array_pre_work(T* dst, int count);
- virtual void write_ref_array_pre(oop* dst, int count, bool dest_uninitialized) {
- if (!dest_uninitialized) {
- write_ref_array_pre_work(dst, count);
- }
- }
- virtual void write_ref_array_pre(narrowOop* dst, int count, bool dest_uninitialized) {
- if (!dest_uninitialized) {
- write_ref_array_pre_work(dst, count);
- }
- }
+ virtual void write_ref_array_pre(oop* dst, int count, bool dest_uninitialized);
+ virtual void write_ref_array_pre(narrowOop* dst, int count, bool dest_uninitialized);
/*
Claimed and deferred bits are used together in G1 during the evacuation
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_specialized_oop_closures.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_specialized_oop_closures.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -30,14 +30,21 @@
// non-virtually, using a mechanism defined in this file. Extend these
// macros in the obvious way to add specializations for new closures.
-// Forward declarations.
enum G1Barrier {
G1BarrierNone,
G1BarrierEvac,
G1BarrierKlass
};
-template<G1Barrier barrier, bool do_mark_object>
+enum G1Mark {
+ G1MarkNone,
+ G1MarkFromRoot,
+ G1MarkPromotedFromRoot
+};
+
+// Forward declarations.
+
+template<G1Barrier barrier, G1Mark do_mark_object>
class G1ParCopyClosure;
class G1ParScanClosure;
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -30,6 +30,7 @@
#include "gc_implementation/g1/heapRegion.inline.hpp"
#include "gc_implementation/g1/heapRegionRemSet.hpp"
#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
+#include "gc_implementation/shared/liveRange.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/iterator.hpp"
#include "memory/space.inline.hpp"
@@ -61,7 +62,7 @@
HeapRegion* hr,
HeapWord* cur, HeapWord* top) {
oop cur_oop = oop(cur);
- int oop_size = cur_oop->size();
+ size_t oop_size = hr->block_size(cur);
HeapWord* next_obj = cur + oop_size;
while (next_obj < top) {
// Keep filtering the remembered set.
@@ -72,7 +73,7 @@
}
cur = next_obj;
cur_oop = oop(cur);
- oop_size = cur_oop->size();
+ oop_size = hr->block_size(cur);
next_obj = cur + oop_size;
}
return cur;
@@ -82,7 +83,7 @@
HeapWord* bottom,
HeapWord* top) {
G1CollectedHeap* g1h = _g1;
- int oop_size;
+ size_t oop_size;
ExtendedOopClosure* cl2 = NULL;
FilterIntoCSClosure intoCSFilt(this, g1h, _cl);
@@ -102,7 +103,7 @@
if (!g1h->is_obj_dead(oop(bottom), _hr)) {
oop_size = oop(bottom)->oop_iterate(cl2, mr);
} else {
- oop_size = oop(bottom)->size();
+ oop_size = _hr->block_size(bottom);
}
bottom += oop_size;
@@ -374,7 +375,7 @@
// region.
hr_clear(false /*par*/, false /*clear_space*/);
set_top(bottom());
- set_saved_mark();
+ record_top_and_timestamp();
assert(HeapRegionRemSet::num_par_rem_sets() > 0, "Invariant.");
}
@@ -394,38 +395,11 @@
return NULL;
}
-void HeapRegion::save_marks() {
- set_saved_mark();
-}
-
-void HeapRegion::oops_in_mr_iterate(MemRegion mr, ExtendedOopClosure* cl) {
- HeapWord* p = mr.start();
- HeapWord* e = mr.end();
- oop obj;
- while (p < e) {
- obj = oop(p);
- p += obj->oop_iterate(cl);
- }
- assert(p == e, "bad memregion: doesn't end on obj boundary");
-}
-
-#define HeapRegion_OOP_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix) \
-void HeapRegion::oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \
- ContiguousSpace::oop_since_save_marks_iterate##nv_suffix(cl); \
-}
-SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES(HeapRegion_OOP_SINCE_SAVE_MARKS_DEFN)
-
-
-void HeapRegion::oop_before_save_marks_iterate(ExtendedOopClosure* cl) {
- oops_in_mr_iterate(MemRegion(bottom(), saved_mark_word()), cl);
-}
-
void HeapRegion::note_self_forwarding_removal_start(bool during_initial_mark,
bool during_conc_mark) {
// We always recreate the prev marking info and we'll explicitly
// mark all objects we find to be self-forwarded on the prev
// bitmap. So all objects need to be below PTAMS.
- _prev_top_at_mark_start = top();
_prev_marked_bytes = 0;
if (during_initial_mark) {
@@ -449,6 +423,7 @@
assert(0 <= marked_bytes && marked_bytes <= used(),
err_msg("marked: "SIZE_FORMAT" used: "SIZE_FORMAT,
marked_bytes, used()));
+ _prev_top_at_mark_start = top();
_prev_marked_bytes = marked_bytes;
}
@@ -476,7 +451,7 @@
} else if (!g1h->is_obj_dead(obj)) {
cl->do_object(obj);
}
- cur += obj->size();
+ cur += block_size(cur);
}
return NULL;
}
@@ -548,7 +523,7 @@
return cur;
}
// Otherwise...
- next = (cur + obj->size());
+ next = cur + block_size(cur);
}
// If we finish the above loop...We have a parseable object that
@@ -556,10 +531,9 @@
// inside or spans the entire region.
assert(obj == oop(cur), "sanity");
- assert(cur <= start &&
- obj->klass_or_null() != NULL &&
- (cur + obj->size()) > start,
- "Loop postcondition");
+ assert(cur <= start, "Loop postcondition");
+ assert(obj->klass_or_null() != NULL, "Loop postcondition");
+ assert((cur + block_size(cur)) > start, "Loop postcondition");
if (!g1h->is_obj_dead(obj)) {
obj->oop_iterate(cl, mr);
@@ -573,7 +547,7 @@
};
// Otherwise:
- next = (cur + obj->size());
+ next = cur + block_size(cur);
if (!g1h->is_obj_dead(obj)) {
if (next < end || !obj->is_objArray()) {
@@ -928,10 +902,11 @@
size_t object_num = 0;
while (p < top()) {
oop obj = oop(p);
- size_t obj_size = obj->size();
+ size_t obj_size = block_size(p);
object_num += 1;
- if (is_humongous != g1->isHumongous(obj_size)) {
+ if (is_humongous != g1->isHumongous(obj_size) &&
+ !g1->is_obj_dead(obj, this)) { // Dead objects may have bigger block_size since they span several objects.
gclog_or_tty->print_cr("obj "PTR_FORMAT" is of %shumongous size ("
SIZE_FORMAT" words) in a %shumongous region",
p, g1->isHumongous(obj_size) ? "" : "non-",
@@ -942,7 +917,9 @@
// If it returns false, verify_for_object() will output the
// appropriate messasge.
- if (do_bot_verify && !_offsets.verify_for_object(p, obj_size)) {
+ if (do_bot_verify &&
+ !g1->is_obj_dead(obj, this) &&
+ !_offsets.verify_for_object(p, obj_size)) {
*failures = true;
return;
}
@@ -950,7 +927,10 @@
if (!g1->is_obj_dead_cond(obj, this, vo)) {
if (obj->is_oop()) {
Klass* klass = obj->klass();
- if (!klass->is_metaspace_object()) {
+ bool is_metaspace_object = Metaspace::contains(klass) ||
+ (vo == VerifyOption_G1UsePrevMarking &&
+ ClassLoaderDataGraph::unload_list_contains(klass));
+ if (!is_metaspace_object) {
gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
"not metadata", klass, (void *)obj);
*failures = true;
@@ -1064,7 +1044,9 @@
// away eventually.
void G1OffsetTableContigSpace::clear(bool mangle_space) {
- ContiguousSpace::clear(mangle_space);
+ set_top(bottom());
+ set_saved_mark_word(bottom());
+ CompactibleSpace::clear(mangle_space);
_offsets.zero_bottom_entry();
_offsets.initialize_threshold();
}
@@ -1102,10 +1084,10 @@
if (_gc_time_stamp < g1h->get_gc_time_stamp())
return top();
else
- return ContiguousSpace::saved_mark_word();
+ return Space::saved_mark_word();
}
-void G1OffsetTableContigSpace::set_saved_mark() {
+void G1OffsetTableContigSpace::record_top_and_timestamp() {
G1CollectedHeap* g1h = G1CollectedHeap::heap();
unsigned curr_gc_time_stamp = g1h->get_gc_time_stamp();
@@ -1117,7 +1099,7 @@
// of region. If it does so after _gc_time_stamp = ..., then it
// will pick up the right saved_mark_word() as the high water mark
// of the region. Either way, the behavior will be correct.
- ContiguousSpace::set_saved_mark();
+ Space::set_saved_mark_word(top());
OrderAccess::storestore();
_gc_time_stamp = curr_gc_time_stamp;
// No need to do another barrier to flush the writes above. If
@@ -1128,6 +1110,26 @@
}
}
+void G1OffsetTableContigSpace::safe_object_iterate(ObjectClosure* blk) {
+ object_iterate(blk);
+}
+
+void G1OffsetTableContigSpace::object_iterate(ObjectClosure* blk) {
+ HeapWord* p = bottom();
+ while (p < top()) {
+ if (block_is_obj(p)) {
+ blk->do_object(oop(p));
+ }
+ p += block_size(p);
+ }
+}
+
+#define block_is_always_obj(q) true
+void G1OffsetTableContigSpace::prepare_for_compaction(CompactPoint* cp) {
+ SCAN_AND_FORWARD(cp, top, block_is_always_obj, block_size);
+}
+#undef block_is_always_obj
+
G1OffsetTableContigSpace::
G1OffsetTableContigSpace(G1BlockOffsetSharedArray* sharedOffsetArray,
MemRegion mr) :
@@ -1137,7 +1139,8 @@
{
_offsets.set_space(this);
// false ==> we'll do the clearing if there's clearing to be done.
- ContiguousSpace::initialize(mr, false, SpaceDecorator::Mangle);
+ CompactibleSpace::initialize(mr, false, SpaceDecorator::Mangle);
+ _top = bottom();
_offsets.zero_bottom_entry();
_offsets.initialize_threshold();
}
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -46,8 +46,6 @@
// The solution is to remove this method from the definition
// of a Space.
-class CompactibleSpace;
-class ContiguousSpace;
class HeapRegionRemSet;
class HeapRegionRemSetIterator;
class HeapRegion;
@@ -125,9 +123,9 @@
// the regions anyway) and at the end of a Full GC. The current scheme
// that uses sequential unsigned ints will fail only if we have 4b
// evacuation pauses between two cleanups, which is _highly_ unlikely.
-
-class G1OffsetTableContigSpace: public ContiguousSpace {
+class G1OffsetTableContigSpace: public CompactibleSpace {
friend class VMStructs;
+ HeapWord* _top;
protected:
G1BlockOffsetArrayContigSpace _offsets;
Mutex _par_alloc_lock;
@@ -144,11 +142,32 @@
G1OffsetTableContigSpace(G1BlockOffsetSharedArray* sharedOffsetArray,
MemRegion mr);
+ void set_top(HeapWord* value) { _top = value; }
+ HeapWord* top() const { return _top; }
+
+ protected:
+ HeapWord** top_addr() { return &_top; }
+ // Allocation helpers (return NULL if full).
+ inline HeapWord* allocate_impl(size_t word_size, HeapWord* end_value);
+ inline HeapWord* par_allocate_impl(size_t word_size, HeapWord* end_value);
+
+ public:
+ void reset_after_compaction() { set_top(compaction_top()); }
+
+ size_t used() const { return byte_size(bottom(), top()); }
+ size_t free() const { return byte_size(top(), end()); }
+ bool is_free_block(const HeapWord* p) const { return p >= top(); }
+
+ MemRegion used_region() const { return MemRegion(bottom(), top()); }
+
+ void object_iterate(ObjectClosure* blk);
+ void safe_object_iterate(ObjectClosure* blk);
+
void set_bottom(HeapWord* value);
void set_end(HeapWord* value);
virtual HeapWord* saved_mark_word() const;
- virtual void set_saved_mark();
+ void record_top_and_timestamp();
void reset_gc_time_stamp() { _gc_time_stamp = 0; }
unsigned get_gc_time_stamp() { return _gc_time_stamp; }
@@ -168,6 +187,8 @@
HeapWord* block_start(const void* p);
HeapWord* block_start_const(const void* p) const;
+ void prepare_for_compaction(CompactPoint* cp);
+
// Add offset table update.
virtual HeapWord* allocate(size_t word_size);
HeapWord* par_allocate(size_t word_size);
@@ -202,10 +223,6 @@
ContinuesHumongous
};
- // Requires that the region "mr" be dense with objects, and begin and end
- // with an object.
- void oops_in_mr_iterate(MemRegion mr, ExtendedOopClosure* cl);
-
// The remembered set for this region.
// (Might want to make this "inline" later, to avoid some alloc failure
// issues.)
@@ -230,11 +247,9 @@
bool _evacuation_failed;
// A heap region may be a member one of a number of special subsets, each
- // represented as linked lists through the field below. Currently, these
- // sets include:
+ // represented as linked lists through the field below. Currently, there
+ // is only one set:
// The collection set.
- // The set of allocation regions used in a collection pause.
- // Spaces that may contain gray objects.
HeapRegion* _next_in_special_set;
// next region in the young "generation" region set
@@ -353,14 +368,15 @@
ParMarkRootClaimValue = 9
};
- inline HeapWord* par_allocate_no_bot_updates(size_t word_size) {
- assert(is_young(), "we can only skip BOT updates on young regions");
- return ContiguousSpace::par_allocate(word_size);
- }
- inline HeapWord* allocate_no_bot_updates(size_t word_size) {
- assert(is_young(), "we can only skip BOT updates on young regions");
- return ContiguousSpace::allocate(word_size);
- }
+ // All allocated blocks are occupied by objects in a HeapRegion
+ bool block_is_obj(const HeapWord* p) const;
+
+ // Returns the object size for all valid block starts
+ // and the amount of unallocated words if called on top()
+ size_t block_size(const HeapWord* p) const;
+
+ inline HeapWord* par_allocate_no_bot_updates(size_t word_size);
+ inline HeapWord* allocate_no_bot_updates(size_t word_size);
// If this region is a member of a HeapRegionSeq, the index in that
// sequence, otherwise -1.
@@ -569,9 +585,6 @@
HeapWord* orig_end() { return _orig_end; }
- // Allows logical separation between objects allocated before and after.
- void save_marks();
-
// Reset HR stuff to default values.
void hr_clear(bool par, bool clear_space, bool locked = false);
void par_clear();
@@ -580,10 +593,6 @@
HeapWord* prev_top_at_mark_start() const { return _prev_top_at_mark_start; }
HeapWord* next_top_at_mark_start() const { return _next_top_at_mark_start; }
- // Apply "cl->do_oop" to (the addresses of) all reference fields in objects
- // allocated in the current region before the last call to "save_mark".
- void oop_before_save_marks_iterate(ExtendedOopClosure* cl);
-
// Note the start or end of marking. This tells the heap region
// that the collector is about to start or has finished (concurrently)
// marking the heap.
@@ -769,10 +778,6 @@
_predicted_bytes_to_copy = bytes;
}
-#define HeapRegion_OOP_SINCE_SAVE_MARKS_DECL(OopClosureType, nv_suffix) \
- virtual void oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl);
- SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES(HeapRegion_OOP_SINCE_SAVE_MARKS_DECL)
-
virtual CompactibleSpace* next_compaction_space() const;
virtual void reset_after_compaction();
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,9 +26,48 @@
#define SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_INLINE_HPP
#include "gc_implementation/g1/g1BlockOffsetTable.inline.hpp"
+#include "gc_implementation/g1/g1CollectedHeap.hpp"
+#include "gc_implementation/g1/heapRegion.hpp"
+#include "memory/space.hpp"
+#include "runtime/atomic.inline.hpp"
+
+// This version requires locking.
+inline HeapWord* G1OffsetTableContigSpace::allocate_impl(size_t size,
+ HeapWord* const end_value) {
+ HeapWord* obj = top();
+ if (pointer_delta(end_value, obj) >= size) {
+ HeapWord* new_top = obj + size;
+ set_top(new_top);
+ assert(is_aligned(obj) && is_aligned(new_top), "checking alignment");
+ return obj;
+ } else {
+ return NULL;
+ }
+}
+
+// This version is lock-free.
+inline HeapWord* G1OffsetTableContigSpace::par_allocate_impl(size_t size,
+ HeapWord* const end_value) {
+ do {
+ HeapWord* obj = top();
+ if (pointer_delta(end_value, obj) >= size) {
+ HeapWord* new_top = obj + size;
+ HeapWord* result = (HeapWord*)Atomic::cmpxchg_ptr(new_top, top_addr(), obj);
+ // result can be one of two:
+ // the old top value: the exchange succeeded
+ // otherwise: the new value of the top is returned.
+ if (result == obj) {
+ assert(is_aligned(obj) && is_aligned(new_top), "checking alignment");
+ return obj;
+ }
+ } else {
+ return NULL;
+ }
+ } while (true);
+}
inline HeapWord* G1OffsetTableContigSpace::allocate(size_t size) {
- HeapWord* res = ContiguousSpace::allocate(size);
+ HeapWord* res = allocate_impl(size, end());
if (res != NULL) {
_offsets.alloc_block(res, size);
}
@@ -40,12 +79,7 @@
// this is used for larger LAB allocations only.
inline HeapWord* G1OffsetTableContigSpace::par_allocate(size_t size) {
MutexLocker x(&_par_alloc_lock);
- // Given that we take the lock no need to use par_allocate() here.
- HeapWord* res = ContiguousSpace::allocate(size);
- if (res != NULL) {
- _offsets.alloc_block(res, size);
- }
- return res;
+ return allocate(size);
}
inline HeapWord* G1OffsetTableContigSpace::block_start(const void* p) {
@@ -57,6 +91,41 @@
return _offsets.block_start_const(p);
}
+inline bool
+HeapRegion::block_is_obj(const HeapWord* p) const {
+ G1CollectedHeap* g1h = G1CollectedHeap::heap();
+ return !g1h->is_obj_dead(oop(p), this);
+}
+
+inline size_t
+HeapRegion::block_size(const HeapWord *addr) const {
+ // Old regions' dead objects may have dead classes
+ // We need to find the next live object in some other
+ // manner than getting the oop size
+ G1CollectedHeap* g1h = G1CollectedHeap::heap();
+ if (g1h->is_obj_dead(oop(addr), this)) {
+ HeapWord* next = g1h->concurrent_mark()->prevMarkBitMap()->
+ getNextMarkedWordAddress(addr, prev_top_at_mark_start());
+
+ assert(next > addr, "must get the next live object");
+
+ return pointer_delta(next, addr);
+ } else if (addr == top()) {
+ return pointer_delta(end(), addr);
+ }
+ return oop(addr)->size();
+}
+
+inline HeapWord* HeapRegion::par_allocate_no_bot_updates(size_t word_size) {
+ assert(is_young(), "we can only skip BOT updates on young regions");
+ return par_allocate_impl(word_size, end());
+}
+
+inline HeapWord* HeapRegion::allocate_no_bot_updates(size_t word_size) {
+ assert(is_young(), "we can only skip BOT updates on young regions");
+ return allocate_impl(word_size, end());
+}
+
inline void HeapRegion::note_start_of_marking() {
_next_marked_bytes = 0;
_next_top_at_mark_start = top();
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -931,7 +931,10 @@
void HeapRegionRemSet::remove_strong_code_root(nmethod* nm) {
assert(nm != NULL, "sanity");
- _code_roots.remove(nm);
+ assert_locked_or_safepoint(CodeCache_lock);
+
+ _code_roots.remove_lock_free(nm);
+
// Check that there were no duplicates
guarantee(!_code_roots.contains(nm), "duplicate entry found");
}
--- a/hotspot/src/share/vm/gc_implementation/g1/satbQueue.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/satbQueue.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -285,37 +285,6 @@
_par_closures[i] = par_closure;
}
-void SATBMarkQueueSet::iterate_closure_all_threads() {
- for(JavaThread* t = Threads::first(); t; t = t->next()) {
- t->satb_mark_queue().apply_closure_and_empty(_closure);
- }
- shared_satb_queue()->apply_closure_and_empty(_closure);
-}
-
-void SATBMarkQueueSet::par_iterate_closure_all_threads(uint worker) {
- SharedHeap* sh = SharedHeap::heap();
- int parity = sh->strong_roots_parity();
-
- for(JavaThread* t = Threads::first(); t; t = t->next()) {
- if (t->claim_oops_do(true, parity)) {
- t->satb_mark_queue().apply_closure_and_empty(_par_closures[worker]);
- }
- }
-
- // We also need to claim the VMThread so that its parity is updated
- // otherwise the next call to Thread::possibly_parallel_oops_do inside
- // a StrongRootsScope might skip the VMThread because it has a stale
- // parity that matches the parity set by the StrongRootsScope
- //
- // Whichever worker succeeds in claiming the VMThread gets to do
- // the shared queue.
-
- VMThread* vmt = VMThread::vm_thread();
- if (vmt->claim_oops_do(true, parity)) {
- shared_satb_queue()->apply_closure_and_empty(_par_closures[worker]);
- }
-}
-
bool SATBMarkQueueSet::apply_closure_to_completed_buffer_work(bool par,
uint worker) {
BufferNode* nd = NULL;
--- a/hotspot/src/share/vm/gc_implementation/g1/satbQueue.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/satbQueue.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -33,7 +33,9 @@
// A ptrQueue whose elements are "oops", pointers to object heads.
class ObjPtrQueue: public PtrQueue {
+ friend class Threads;
friend class SATBMarkQueueSet;
+ friend class G1RemarkThreadsClosure;
private:
// Filter out unwanted entries from the buffer.
@@ -119,13 +121,6 @@
// closures, one for each parallel GC thread.
void set_par_closure(int i, ObjectClosure* closure);
- // Apply the registered closure to all entries on each
- // currently-active buffer and then empty the buffer. It should only
- // be called serially and at a safepoint.
- void iterate_closure_all_threads();
- // Parallel version of the above.
- void par_iterate_closure_all_threads(uint worker);
-
// If there exists some completed buffer, pop it, then apply the
// registered closure to all its elements, and return true. If no
// completed buffers exist, return false.
--- a/hotspot/src/share/vm/gc_implementation/g1/vmStructs_g1.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/vmStructs_g1.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -34,6 +34,8 @@
static_field(HeapRegion, GrainBytes, size_t) \
static_field(HeapRegion, LogOfHRGrainBytes, int) \
\
+ nonstatic_field(G1OffsetTableContigSpace, _top, HeapWord*) \
+ \
nonstatic_field(G1HeapRegionTable, _base, address) \
nonstatic_field(G1HeapRegionTable, _length, size_t) \
nonstatic_field(G1HeapRegionTable, _biased_base, address) \
@@ -69,7 +71,8 @@
\
declare_type(G1CollectedHeap, SharedHeap) \
\
- declare_type(HeapRegion, ContiguousSpace) \
+ declare_type(G1OffsetTableContigSpace, CompactibleSpace) \
+ declare_type(HeapRegion, G1OffsetTableContigSpace) \
declare_toplevel_type(HeapRegionSeq) \
declare_toplevel_type(HeapRegionSetBase) \
declare_toplevel_type(HeapRegionSetCount) \
--- a/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,657 +0,0 @@
-/*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
-#include "gc_implementation/parNew/asParNewGeneration.hpp"
-#include "gc_implementation/parNew/parNewGeneration.hpp"
-#include "gc_implementation/shared/markSweep.inline.hpp"
-#include "gc_implementation/shared/spaceDecorator.hpp"
-#include "memory/defNewGeneration.inline.hpp"
-#include "memory/referencePolicy.hpp"
-#include "oops/markOop.inline.hpp"
-#include "oops/oop.pcgc.inline.hpp"
-
-ASParNewGeneration::ASParNewGeneration(ReservedSpace rs,
- size_t initial_byte_size,
- size_t min_byte_size,
- int level) :
- ParNewGeneration(rs, initial_byte_size, level),
- _min_gen_size(min_byte_size) {}
-
-const char* ASParNewGeneration::name() const {
- return "adaptive size par new generation";
-}
-
-void ASParNewGeneration::adjust_desired_tenuring_threshold() {
- assert(UseAdaptiveSizePolicy,
- "Should only be used with UseAdaptiveSizePolicy");
-}
-
-void ASParNewGeneration::resize(size_t eden_size, size_t survivor_size) {
- // Resize the generation if needed. If the generation resize
- // reports false, do not attempt to resize the spaces.
- if (resize_generation(eden_size, survivor_size)) {
- // Then we lay out the spaces inside the generation
- resize_spaces(eden_size, survivor_size);
-
- space_invariants();
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("Young generation size: "
- "desired eden: " SIZE_FORMAT " survivor: " SIZE_FORMAT
- " used: " SIZE_FORMAT " capacity: " SIZE_FORMAT
- " gen limits: " SIZE_FORMAT " / " SIZE_FORMAT,
- eden_size, survivor_size, used(), capacity(),
- max_gen_size(), min_gen_size());
- }
- }
-}
-
-size_t ASParNewGeneration::available_to_min_gen() {
- assert(virtual_space()->committed_size() >= min_gen_size(), "Invariant");
- return virtual_space()->committed_size() - min_gen_size();
-}
-
-// This method assumes that from-space has live data and that
-// any shrinkage of the young gen is limited by location of
-// from-space.
-size_t ASParNewGeneration::available_to_live() const {
-#undef SHRINKS_AT_END_OF_EDEN
-#ifdef SHRINKS_AT_END_OF_EDEN
- size_t delta_in_survivor = 0;
- ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
- const size_t space_alignment = heap->intra_heap_alignment();
- const size_t gen_alignment = heap->object_heap_alignment();
-
- MutableSpace* space_shrinking = NULL;
- if (from_space()->end() > to_space()->end()) {
- space_shrinking = from_space();
- } else {
- space_shrinking = to_space();
- }
-
- // Include any space that is committed but not included in
- // the survivor spaces.
- assert(((HeapWord*)virtual_space()->high()) >= space_shrinking->end(),
- "Survivor space beyond high end");
- size_t unused_committed = pointer_delta(virtual_space()->high(),
- space_shrinking->end(), sizeof(char));
-
- if (space_shrinking->is_empty()) {
- // Don't let the space shrink to 0
- assert(space_shrinking->capacity_in_bytes() >= space_alignment,
- "Space is too small");
- delta_in_survivor = space_shrinking->capacity_in_bytes() - space_alignment;
- } else {
- delta_in_survivor = pointer_delta(space_shrinking->end(),
- space_shrinking->top(),
- sizeof(char));
- }
-
- size_t delta_in_bytes = unused_committed + delta_in_survivor;
- delta_in_bytes = align_size_down(delta_in_bytes, gen_alignment);
- return delta_in_bytes;
-#else
- // The only space available for shrinking is in to-space if it
- // is above from-space.
- if (to()->bottom() > from()->bottom()) {
- const size_t alignment = os::vm_page_size();
- if (to()->capacity() < alignment) {
- return 0;
- } else {
- return to()->capacity() - alignment;
- }
- } else {
- return 0;
- }
-#endif
-}
-
-// Return the number of bytes available for resizing down the young
-// generation. This is the minimum of
-// input "bytes"
-// bytes to the minimum young gen size
-// bytes to the size currently being used + some small extra
-size_t ASParNewGeneration::limit_gen_shrink (size_t bytes) {
- // Allow shrinkage into the current eden but keep eden large enough
- // to maintain the minimum young gen size
- bytes = MIN3(bytes, available_to_min_gen(), available_to_live());
- return align_size_down(bytes, os::vm_page_size());
-}
-
-// Note that the the alignment used is the OS page size as
-// opposed to an alignment associated with the virtual space
-// (as is done in the ASPSYoungGen/ASPSOldGen)
-bool ASParNewGeneration::resize_generation(size_t eden_size,
- size_t survivor_size) {
- const size_t alignment = os::vm_page_size();
- size_t orig_size = virtual_space()->committed_size();
- bool size_changed = false;
-
- // There used to be this guarantee there.
- // guarantee ((eden_size + 2*survivor_size) <= _max_gen_size, "incorrect input arguments");
- // Code below forces this requirement. In addition the desired eden
- // size and desired survivor sizes are desired goals and may
- // exceed the total generation size.
-
- assert(min_gen_size() <= orig_size && orig_size <= max_gen_size(),
- "just checking");
-
- // Adjust new generation size
- const size_t eden_plus_survivors =
- align_size_up(eden_size + 2 * survivor_size, alignment);
- size_t desired_size = MAX2(MIN2(eden_plus_survivors, max_gen_size()),
- min_gen_size());
- assert(desired_size <= max_gen_size(), "just checking");
-
- if (desired_size > orig_size) {
- // Grow the generation
- size_t change = desired_size - orig_size;
- assert(change % alignment == 0, "just checking");
- if (expand(change)) {
- return false; // Error if we fail to resize!
- }
- size_changed = true;
- } else if (desired_size < orig_size) {
- size_t desired_change = orig_size - desired_size;
- assert(desired_change % alignment == 0, "just checking");
-
- desired_change = limit_gen_shrink(desired_change);
-
- if (desired_change > 0) {
- virtual_space()->shrink_by(desired_change);
- reset_survivors_after_shrink();
-
- size_changed = true;
- }
- } else {
- if (Verbose && PrintGC) {
- if (orig_size == max_gen_size()) {
- gclog_or_tty->print_cr("ASParNew generation size at maximum: "
- SIZE_FORMAT "K", orig_size/K);
- } else if (orig_size == min_gen_size()) {
- gclog_or_tty->print_cr("ASParNew generation size at minium: "
- SIZE_FORMAT "K", orig_size/K);
- }
- }
- }
-
- if (size_changed) {
- MemRegion cmr((HeapWord*)virtual_space()->low(),
- (HeapWord*)virtual_space()->high());
- GenCollectedHeap::heap()->barrier_set()->resize_covered_region(cmr);
-
- if (Verbose && PrintGC) {
- size_t current_size = virtual_space()->committed_size();
- gclog_or_tty->print_cr("ASParNew generation size changed: "
- SIZE_FORMAT "K->" SIZE_FORMAT "K",
- orig_size/K, current_size/K);
- }
- }
-
- guarantee(eden_plus_survivors <= virtual_space()->committed_size() ||
- virtual_space()->committed_size() == max_gen_size(), "Sanity");
-
- return true;
-}
-
-void ASParNewGeneration::reset_survivors_after_shrink() {
-
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- HeapWord* new_end = (HeapWord*)virtual_space()->high();
-
- if (from()->end() > to()->end()) {
- assert(new_end >= from()->end(), "Shrinking past from-space");
- } else {
- assert(new_end >= to()->bottom(), "Shrink was too large");
- // Was there a shrink of the survivor space?
- if (new_end < to()->end()) {
- MemRegion mr(to()->bottom(), new_end);
- to()->initialize(mr,
- SpaceDecorator::DontClear,
- SpaceDecorator::DontMangle);
- }
- }
-}
-void ASParNewGeneration::resize_spaces(size_t requested_eden_size,
- size_t requested_survivor_size) {
- assert(UseAdaptiveSizePolicy, "sanity check");
- assert(requested_eden_size > 0 && requested_survivor_size > 0,
- "just checking");
- CollectedHeap* heap = Universe::heap();
- assert(heap->kind() == CollectedHeap::GenCollectedHeap, "Sanity");
-
-
- // We require eden and to space to be empty
- if ((!eden()->is_empty()) || (!to()->is_empty())) {
- return;
- }
-
- size_t cur_eden_size = eden()->capacity();
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("ASParNew::resize_spaces(requested_eden_size: "
- SIZE_FORMAT
- ", requested_survivor_size: " SIZE_FORMAT ")",
- requested_eden_size, requested_survivor_size);
- gclog_or_tty->print_cr(" eden: [" PTR_FORMAT ".." PTR_FORMAT ") "
- SIZE_FORMAT,
- p2i(eden()->bottom()),
- p2i(eden()->end()),
- pointer_delta(eden()->end(),
- eden()->bottom(),
- sizeof(char)));
- gclog_or_tty->print_cr(" from: [" PTR_FORMAT ".." PTR_FORMAT ") "
- SIZE_FORMAT,
- p2i(from()->bottom()),
- p2i(from()->end()),
- pointer_delta(from()->end(),
- from()->bottom(),
- sizeof(char)));
- gclog_or_tty->print_cr(" to: [" PTR_FORMAT ".." PTR_FORMAT ") "
- SIZE_FORMAT,
- p2i(to()->bottom()),
- p2i(to()->end()),
- pointer_delta( to()->end(),
- to()->bottom(),
- sizeof(char)));
- }
-
- // There's nothing to do if the new sizes are the same as the current
- if (requested_survivor_size == to()->capacity() &&
- requested_survivor_size == from()->capacity() &&
- requested_eden_size == eden()->capacity()) {
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" capacities are the right sizes, returning");
- }
- return;
- }
-
- char* eden_start = (char*)eden()->bottom();
- char* eden_end = (char*)eden()->end();
- char* from_start = (char*)from()->bottom();
- char* from_end = (char*)from()->end();
- char* to_start = (char*)to()->bottom();
- char* to_end = (char*)to()->end();
-
- const size_t alignment = os::vm_page_size();
- const bool maintain_minimum =
- (requested_eden_size + 2 * requested_survivor_size) <= min_gen_size();
-
- // Check whether from space is below to space
- if (from_start < to_start) {
- // Eden, from, to
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" Eden, from, to:");
- }
-
- // Set eden
- // "requested_eden_size" is a goal for the size of eden
- // and may not be attainable. "eden_size" below is
- // calculated based on the location of from-space and
- // the goal for the size of eden. from-space is
- // fixed in place because it contains live data.
- // The calculation is done this way to avoid 32bit
- // overflow (i.e., eden_start + requested_eden_size
- // may too large for representation in 32bits).
- size_t eden_size;
- if (maintain_minimum) {
- // Only make eden larger than the requested size if
- // the minimum size of the generation has to be maintained.
- // This could be done in general but policy at a higher
- // level is determining a requested size for eden and that
- // should be honored unless there is a fundamental reason.
- eden_size = pointer_delta(from_start,
- eden_start,
- sizeof(char));
- } else {
- eden_size = MIN2(requested_eden_size,
- pointer_delta(from_start, eden_start, sizeof(char)));
- }
-
- eden_size = align_size_down(eden_size, alignment);
- eden_end = eden_start + eden_size;
- assert(eden_end >= eden_start, "addition overflowed");
-
- // To may resize into from space as long as it is clear of live data.
- // From space must remain page aligned, though, so we need to do some
- // extra calculations.
-
- // First calculate an optimal to-space
- to_end = (char*)virtual_space()->high();
- to_start = (char*)pointer_delta(to_end, (char*)requested_survivor_size,
- sizeof(char));
-
- // Does the optimal to-space overlap from-space?
- if (to_start < (char*)from()->end()) {
- // Calculate the minimum offset possible for from_end
- size_t from_size = pointer_delta(from()->top(), from_start, sizeof(char));
-
- // Should we be in this method if from_space is empty? Why not the set_space method? FIX ME!
- if (from_size == 0) {
- from_size = alignment;
- } else {
- from_size = align_size_up(from_size, alignment);
- }
-
- from_end = from_start + from_size;
- assert(from_end > from_start, "addition overflow or from_size problem");
-
- guarantee(from_end <= (char*)from()->end(), "from_end moved to the right");
-
- // Now update to_start with the new from_end
- to_start = MAX2(from_end, to_start);
- } else {
- // If shrinking, move to-space down to abut the end of from-space
- // so that shrinking will move to-space down. If not shrinking
- // to-space is moving up to allow for growth on the next expansion.
- if (requested_eden_size <= cur_eden_size) {
- to_start = from_end;
- if (to_start + requested_survivor_size > to_start) {
- to_end = to_start + requested_survivor_size;
- }
- }
- // else leave to_end pointing to the high end of the virtual space.
- }
-
- guarantee(to_start != to_end, "to space is zero sized");
-
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" [eden_start .. eden_end): "
- "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT,
- p2i(eden_start),
- p2i(eden_end),
- pointer_delta(eden_end, eden_start, sizeof(char)));
- gclog_or_tty->print_cr(" [from_start .. from_end): "
- "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT,
- p2i(from_start),
- p2i(from_end),
- pointer_delta(from_end, from_start, sizeof(char)));
- gclog_or_tty->print_cr(" [ to_start .. to_end): "
- "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT,
- p2i(to_start),
- p2i(to_end),
- pointer_delta( to_end, to_start, sizeof(char)));
- }
- } else {
- // Eden, to, from
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" Eden, to, from:");
- }
-
- // Calculate the to-space boundaries based on
- // the start of from-space.
- to_end = from_start;
- to_start = (char*)pointer_delta(from_start,
- (char*)requested_survivor_size,
- sizeof(char));
- // Calculate the ideal eden boundaries.
- // eden_end is already at the bottom of the generation
- assert(eden_start == virtual_space()->low(),
- "Eden is not starting at the low end of the virtual space");
- if (eden_start + requested_eden_size >= eden_start) {
- eden_end = eden_start + requested_eden_size;
- } else {
- eden_end = to_start;
- }
-
- // Does eden intrude into to-space? to-space
- // gets priority but eden is not allowed to shrink
- // to 0.
- if (eden_end > to_start) {
- eden_end = to_start;
- }
-
- // Don't let eden shrink down to 0 or less.
- eden_end = MAX2(eden_end, eden_start + alignment);
- assert(eden_start + alignment >= eden_start, "Overflow");
-
- size_t eden_size;
- if (maintain_minimum) {
- // Use all the space available.
- eden_end = MAX2(eden_end, to_start);
- eden_size = pointer_delta(eden_end, eden_start, sizeof(char));
- eden_size = MIN2(eden_size, cur_eden_size);
- } else {
- eden_size = pointer_delta(eden_end, eden_start, sizeof(char));
- }
- eden_size = align_size_down(eden_size, alignment);
- assert(maintain_minimum || eden_size <= requested_eden_size,
- "Eden size is too large");
- assert(eden_size >= alignment, "Eden size is too small");
- eden_end = eden_start + eden_size;
-
- // Move to-space down to eden.
- if (requested_eden_size < cur_eden_size) {
- to_start = eden_end;
- if (to_start + requested_survivor_size > to_start) {
- to_end = MIN2(from_start, to_start + requested_survivor_size);
- } else {
- to_end = from_start;
- }
- }
-
- // eden_end may have moved so again make sure
- // the to-space and eden don't overlap.
- to_start = MAX2(eden_end, to_start);
-
- // from-space
- size_t from_used = from()->used();
- if (requested_survivor_size > from_used) {
- if (from_start + requested_survivor_size >= from_start) {
- from_end = from_start + requested_survivor_size;
- }
- if (from_end > virtual_space()->high()) {
- from_end = virtual_space()->high();
- }
- }
-
- assert(to_start >= eden_end, "to-space should be above eden");
- if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr(" [eden_start .. eden_end): "
- "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT,
- p2i(eden_start),
- p2i(eden_end),
- pointer_delta(eden_end, eden_start, sizeof(char)));
- gclog_or_tty->print_cr(" [ to_start .. to_end): "
- "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT,
- p2i(to_start),
- p2i(to_end),
- pointer_delta( to_end, to_start, sizeof(char)));
- gclog_or_tty->print_cr(" [from_start .. from_end): "
- "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT,
- p2i(from_start),
- p2i(from_end),
- pointer_delta(from_end, from_start, sizeof(char)));
- }
- }
-
-
- guarantee((HeapWord*)from_start <= from()->bottom(),
- "from start moved to the right");
- guarantee((HeapWord*)from_end >= from()->top(),
- "from end moved into live data");
- assert(is_object_aligned((intptr_t)eden_start), "checking alignment");
- assert(is_object_aligned((intptr_t)from_start), "checking alignment");
- assert(is_object_aligned((intptr_t)to_start), "checking alignment");
-
- MemRegion edenMR((HeapWord*)eden_start, (HeapWord*)eden_end);
- MemRegion toMR ((HeapWord*)to_start, (HeapWord*)to_end);
- MemRegion fromMR((HeapWord*)from_start, (HeapWord*)from_end);
-
- // Let's make sure the call to initialize doesn't reset "top"!
- HeapWord* old_from_top = from()->top();
-
- // For PrintAdaptiveSizePolicy block below
- size_t old_from = from()->capacity();
- size_t old_to = to()->capacity();
-
- // If not clearing the spaces, do some checking to verify that
- // the spaces are already mangled.
-
- // Must check mangling before the spaces are reshaped. Otherwise,
- // the bottom or end of one space may have moved into another
- // a failure of the check may not correctly indicate which space
- // is not properly mangled.
- if (ZapUnusedHeapArea) {
- HeapWord* limit = (HeapWord*) virtual_space()->high();
- eden()->check_mangled_unused_area(limit);
- from()->check_mangled_unused_area(limit);
- to()->check_mangled_unused_area(limit);
- }
-
- // The call to initialize NULL's the next compaction space
- eden()->initialize(edenMR,
- SpaceDecorator::Clear,
- SpaceDecorator::DontMangle);
- eden()->set_next_compaction_space(from());
- to()->initialize(toMR ,
- SpaceDecorator::Clear,
- SpaceDecorator::DontMangle);
- from()->initialize(fromMR,
- SpaceDecorator::DontClear,
- SpaceDecorator::DontMangle);
-
- assert(from()->top() == old_from_top, "from top changed!");
-
- if (PrintAdaptiveSizePolicy) {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- assert(gch->kind() == CollectedHeap::GenCollectedHeap, "Sanity");
-
- gclog_or_tty->print("AdaptiveSizePolicy::survivor space sizes: "
- "collection: %d "
- "(" SIZE_FORMAT ", " SIZE_FORMAT ") -> "
- "(" SIZE_FORMAT ", " SIZE_FORMAT ") ",
- gch->total_collections(),
- old_from, old_to,
- from()->capacity(),
- to()->capacity());
- gclog_or_tty->cr();
- }
-}
-
-void ASParNewGeneration::compute_new_size() {
- GenCollectedHeap* gch = GenCollectedHeap::heap();
- assert(gch->kind() == CollectedHeap::GenCollectedHeap,
- "not a CMS generational heap");
-
-
- CMSAdaptiveSizePolicy* size_policy =
- (CMSAdaptiveSizePolicy*)gch->gen_policy()->size_policy();
- assert(size_policy->is_gc_cms_adaptive_size_policy(),
- "Wrong type of size policy");
-
- size_t survived = from()->used();
- if (!survivor_overflow()) {
- // Keep running averages on how much survived
- size_policy->avg_survived()->sample(survived);
- } else {
- size_t promoted =
- (size_t) next_gen()->gc_stats()->avg_promoted()->last_sample();
- assert(promoted < gch->capacity(), "Conversion problem?");
- size_t survived_guess = survived + promoted;
- size_policy->avg_survived()->sample(survived_guess);
- }
-
- size_t survivor_limit = max_survivor_size();
- _tenuring_threshold =
- size_policy->compute_survivor_space_size_and_threshold(
- _survivor_overflow,
- _tenuring_threshold,
- survivor_limit);
- size_policy->avg_young_live()->sample(used());
- size_policy->avg_eden_live()->sample(eden()->used());
-
- size_policy->compute_eden_space_size(eden()->capacity(), max_gen_size());
-
- resize(size_policy->calculated_eden_size_in_bytes(),
- size_policy->calculated_survivor_size_in_bytes());
-
- if (UsePerfData) {
- CMSGCAdaptivePolicyCounters* counters =
- (CMSGCAdaptivePolicyCounters*) gch->collector_policy()->counters();
- assert(counters->kind() ==
- GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
- "Wrong kind of counters");
- counters->update_tenuring_threshold(_tenuring_threshold);
- counters->update_survivor_overflowed(_survivor_overflow);
- counters->update_young_capacity(capacity());
- }
-}
-
-
-#ifndef PRODUCT
-// Changes from PSYoungGen version
-// value of "alignment"
-void ASParNewGeneration::space_invariants() {
- const size_t alignment = os::vm_page_size();
-
- // Currently, our eden size cannot shrink to zero
- guarantee(eden()->capacity() >= alignment, "eden too small");
- guarantee(from()->capacity() >= alignment, "from too small");
- guarantee(to()->capacity() >= alignment, "to too small");
-
- // Relationship of spaces to each other
- char* eden_start = (char*)eden()->bottom();
- char* eden_end = (char*)eden()->end();
- char* from_start = (char*)from()->bottom();
- char* from_end = (char*)from()->end();
- char* to_start = (char*)to()->bottom();
- char* to_end = (char*)to()->end();
-
- guarantee(eden_start >= virtual_space()->low(), "eden bottom");
- guarantee(eden_start < eden_end, "eden space consistency");
- guarantee(from_start < from_end, "from space consistency");
- guarantee(to_start < to_end, "to space consistency");
-
- // Check whether from space is below to space
- if (from_start < to_start) {
- // Eden, from, to
- guarantee(eden_end <= from_start, "eden/from boundary");
- guarantee(from_end <= to_start, "from/to boundary");
- guarantee(to_end <= virtual_space()->high(), "to end");
- } else {
- // Eden, to, from
- guarantee(eden_end <= to_start, "eden/to boundary");
- guarantee(to_end <= from_start, "to/from boundary");
- guarantee(from_end <= virtual_space()->high(), "from end");
- }
-
- // More checks that the virtual space is consistent with the spaces
- assert(virtual_space()->committed_size() >=
- (eden()->capacity() +
- to()->capacity() +
- from()->capacity()), "Committed size is inconsistent");
- assert(virtual_space()->committed_size() <= virtual_space()->reserved_size(),
- "Space invariant");
- char* eden_top = (char*)eden()->top();
- char* from_top = (char*)from()->top();
- char* to_top = (char*)to()->top();
- assert(eden_top <= virtual_space()->high(), "eden top");
- assert(from_top <= virtual_space()->high(), "from top");
- assert(to_top <= virtual_space()->high(), "to top");
-}
-#endif
--- a/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.hpp Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#ifndef SHARE_VM_GC_IMPLEMENTATION_PARNEW_ASPARNEWGENERATION_HPP
-#define SHARE_VM_GC_IMPLEMENTATION_PARNEW_ASPARNEWGENERATION_HPP
-
-#include "gc_implementation/parNew/parNewGeneration.hpp"
-#include "gc_implementation/shared/adaptiveSizePolicy.hpp"
-
-// A Generation that does parallel young-gen collection extended
-// for adaptive size policy.
-
-// Division of generation into spaces
-// done by DefNewGeneration::compute_space_boundaries()
-// +---------------+
-// | uncommitted |
-// |---------------|
-// | ss0 |
-// |---------------|
-// | ss1 |
-// |---------------|
-// | |
-// | eden |
-// | |
-// +---------------+ <-- low end of VirtualSpace
-//
-class ASParNewGeneration: public ParNewGeneration {
-
- size_t _min_gen_size;
-
- // Resize the generation based on the desired sizes of
- // the constituent spaces.
- bool resize_generation(size_t eden_size, size_t survivor_size);
- // Resize the spaces based on their desired sizes but
- // respecting the maximum size of the generation.
- void resize_spaces(size_t eden_size, size_t survivor_size);
- // Return the byte size remaining to the minimum generation size.
- size_t available_to_min_gen();
- // Return the byte size remaining to the live data in the generation.
- size_t available_to_live() const;
- // Return the byte size that the generation is allowed to shrink.
- size_t limit_gen_shrink(size_t bytes);
- // Reset the size of the spaces after a shrink of the generation.
- void reset_survivors_after_shrink();
-
- // Accessor
- VirtualSpace* virtual_space() { return &_virtual_space; }
-
- virtual void adjust_desired_tenuring_threshold();
-
- public:
-
- ASParNewGeneration(ReservedSpace rs,
- size_t initial_byte_size,
- size_t min_byte_size,
- int level);
-
- virtual const char* short_name() const { return "ASParNew"; }
- virtual const char* name() const;
- virtual Generation::Name kind() { return ASParNew; }
-
- // Change the sizes of eden and the survivor spaces in
- // the generation. The parameters are desired sizes
- // and are not guaranteed to be met. For example, if
- // the total is larger than the generation.
- void resize(size_t eden_size, size_t survivor_size);
-
- virtual void compute_new_size();
-
- size_t max_gen_size() { return _reserved.byte_size(); }
- size_t min_gen_size() const { return _min_gen_size; }
-
- // Space boundary invariant checker
- void space_invariants() PRODUCT_RETURN;
-};
-
-#endif // SHARE_VM_GC_IMPLEMENTATION_PARNEW_ASPARNEWGENERATION_HPP
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -614,18 +614,21 @@
KlassScanClosure klass_scan_closure(&par_scan_state.to_space_root_closure(),
gch->rem_set()->klass_rem_set());
-
- int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings | SharedHeap::SO_ScavengeCodeCache;
+ CLDToKlassAndOopClosure cld_scan_closure(&klass_scan_closure,
+ &par_scan_state.to_space_root_closure(),
+ false);
par_scan_state.start_strong_roots();
- gch->gen_process_strong_roots(_gen->level(),
- true, // Process younger gens, if any,
- // as strong roots.
- false, // no scope; this is parallel code
- SharedHeap::ScanningOption(so),
- &par_scan_state.to_space_root_closure(),
- &par_scan_state.older_gen_closure(),
- &klass_scan_closure);
+ gch->gen_process_roots(_gen->level(),
+ true, // Process younger gens, if any,
+ // as strong roots.
+ false, // no scope; this is parallel code
+ SharedHeap::SO_ScavengeCodeCache,
+ GenCollectedHeap::StrongAndWeakRoots,
+ &par_scan_state.to_space_root_closure(),
+ &par_scan_state.older_gen_closure(),
+ &cld_scan_closure);
+
par_scan_state.end_strong_roots();
// "evacuate followers".
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -69,7 +69,7 @@
ParScanWithoutBarrierClosure _to_space_closure; // scan_without_gc_barrier
ParScanWithBarrierClosure _old_gen_closure; // scan_with_gc_barrier
ParRootScanWithoutBarrierClosure _to_space_root_closure; // scan_root_without_gc_barrier
- // One of these two will be passed to process_strong_roots, which will
+ // One of these two will be passed to process_roots, which will
// set its generation. The first is for two-gen configs where the
// old gen collects the perm gen; the second is for arbitrary configs.
// The second isn't used right now (it used to be used for the train, an
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,21 +30,6 @@
#include "runtime/os.hpp"
#include "utilities/bitMap.inline.hpp"
#include "services/memTracker.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
bool
ParMarkBitMap::initialize(MemRegion covered_region)
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -59,7 +59,7 @@
PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
CLDToOopClosure mark_and_push_from_clds(&mark_and_push_closure, true);
- CodeBlobToOopClosure mark_and_push_in_blobs(&mark_and_push_closure, /*do_marking=*/ true);
+ MarkingCodeBlobClosure mark_and_push_in_blobs(&mark_and_push_closure, !CodeBlobToOopClosure::FixRelocations);
if (_java_thread != NULL)
_java_thread->oops_do(
@@ -100,7 +100,7 @@
case threads:
{
ResourceMark rm;
- CodeBlobToOopClosure each_active_code_blob(&mark_and_push_closure, /*do_marking=*/ true);
+ MarkingCodeBlobClosure each_active_code_blob(&mark_and_push_closure, !CodeBlobToOopClosure::FixRelocations);
CLDToOopClosure mark_and_push_from_cld(&mark_and_push_closure);
Threads::oops_do(&mark_and_push_closure, &mark_and_push_from_cld, &each_active_code_blob);
}
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -536,14 +536,14 @@
Universe::oops_do(mark_and_push_closure());
JNIHandles::oops_do(mark_and_push_closure()); // Global (strong) JNI handles
CLDToOopClosure mark_and_push_from_cld(mark_and_push_closure());
- CodeBlobToOopClosure each_active_code_blob(mark_and_push_closure(), /*do_marking=*/ true);
+ MarkingCodeBlobClosure each_active_code_blob(mark_and_push_closure(), !CodeBlobToOopClosure::FixRelocations);
Threads::oops_do(mark_and_push_closure(), &mark_and_push_from_cld, &each_active_code_blob);
ObjectSynchronizer::oops_do(mark_and_push_closure());
FlatProfiler::oops_do(mark_and_push_closure());
Management::oops_do(mark_and_push_closure());
JvmtiExport::oops_do(mark_and_push_closure());
SystemDictionary::always_strong_oops_do(mark_and_push_closure());
- ClassLoaderDataGraph::always_strong_oops_do(mark_and_push_closure(), follow_klass_closure(), true);
+ ClassLoaderDataGraph::always_strong_cld_do(follow_cld_closure());
// Do not treat nmethods as strong roots for mark/sweep, since we can unload them.
//CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure(mark_and_push_closure()));
}
@@ -633,16 +633,16 @@
FlatProfiler::oops_do(adjust_pointer_closure());
Management::oops_do(adjust_pointer_closure());
JvmtiExport::oops_do(adjust_pointer_closure());
- // SO_AllClasses
SystemDictionary::oops_do(adjust_pointer_closure());
- ClassLoaderDataGraph::oops_do(adjust_pointer_closure(), adjust_klass_closure(), true);
+ ClassLoaderDataGraph::cld_do(adjust_cld_closure());
// Now adjust pointers in remaining weak roots. (All of which should
// have been cleared if they pointed to non-surviving objects.)
// Global (weak) JNI handles
JNIHandles::weak_oops_do(&always_true, adjust_pointer_closure());
- CodeCache::oops_do(adjust_pointer_closure());
+ CodeBlobToOopClosure adjust_from_blobs(adjust_pointer_closure(), CodeBlobToOopClosure::FixRelocations);
+ CodeCache::blobs_do(&adjust_from_blobs);
StringTable::oops_do(adjust_pointer_closure());
ref_processor()->weak_oops_do(adjust_pointer_closure());
PSScavenge::reference_processor()->weak_oops_do(adjust_pointer_closure());
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -40,11 +40,11 @@
static CollectorCounters* _counters;
// Closure accessors
- static OopClosure* mark_and_push_closure() { return &MarkSweep::mark_and_push_closure; }
- static KlassClosure* follow_klass_closure() { return &MarkSweep::follow_klass_closure; }
- static VoidClosure* follow_stack_closure() { return (VoidClosure*)&MarkSweep::follow_stack_closure; }
- static OopClosure* adjust_pointer_closure() { return (OopClosure*)&MarkSweep::adjust_pointer_closure; }
- static KlassClosure* adjust_klass_closure() { return &MarkSweep::adjust_klass_closure; }
+ static OopClosure* mark_and_push_closure() { return &MarkSweep::mark_and_push_closure; }
+ static VoidClosure* follow_stack_closure() { return (VoidClosure*)&MarkSweep::follow_stack_closure; }
+ static CLDClosure* follow_cld_closure() { return &MarkSweep::follow_cld_closure; }
+ static OopClosure* adjust_pointer_closure() { return (OopClosure*)&MarkSweep::adjust_pointer_closure; }
+ static CLDClosure* adjust_cld_closure() { return &MarkSweep::adjust_cld_closure; }
static BoolObjectClosure* is_alive_closure() { return (BoolObjectClosure*)&MarkSweep::is_alive; }
debug_only(public:) // Used for PSParallelCompact debugging
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -2474,7 +2474,6 @@
FlatProfiler::oops_do(adjust_pointer_closure());
Management::oops_do(adjust_pointer_closure());
JvmtiExport::oops_do(adjust_pointer_closure());
- // SO_AllClasses
SystemDictionary::oops_do(adjust_pointer_closure());
ClassLoaderDataGraph::oops_do(adjust_pointer_closure(), adjust_klass_closure(), true);
@@ -2483,7 +2482,8 @@
// Global (weak) JNI handles
JNIHandles::weak_oops_do(&always_true, adjust_pointer_closure());
- CodeCache::oops_do(adjust_pointer_closure());
+ CodeBlobToOopClosure adjust_from_blobs(adjust_pointer_closure(), CodeBlobToOopClosure::FixRelocations);
+ CodeCache::blobs_do(&adjust_from_blobs);
StringTable::oops_do(adjust_pointer_closure());
ref_processor()->weak_oops_do(adjust_pointer_closure());
// Roots were visited so references into the young gen in roots
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psTasks.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psTasks.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -100,7 +100,7 @@
case code_cache:
{
- CodeBlobToOopClosure each_scavengable_code_blob(&roots_to_old_closure, /*do_marking=*/ true);
+ MarkingCodeBlobClosure each_scavengable_code_blob(&roots_to_old_closure, CodeBlobToOopClosure::FixRelocations);
CodeCache::scavenge_root_nmethods_do(&each_scavengable_code_blob);
}
break;
@@ -123,7 +123,7 @@
PSPromotionManager* pm = PSPromotionManager::gc_thread_promotion_manager(which);
PSScavengeRootsClosure roots_closure(pm);
CLDClosure* roots_from_clds = NULL; // Not needed. All CLDs are already visited.
- CodeBlobToOopClosure roots_in_blobs(&roots_closure, /*do_marking=*/ true);
+ MarkingCodeBlobClosure roots_in_blobs(&roots_closure, CodeBlobToOopClosure::FixRelocations);
if (_java_thread != NULL)
_java_thread->oops_do(&roots_closure, roots_from_clds, &roots_in_blobs);
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,21 +26,6 @@
#include "gc_implementation/parallelScavenge/psVirtualspace.hpp"
#include "runtime/os.hpp"
#include "runtime/virtualspace.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
--- a/hotspot/src/share/vm/gc_implementation/shared/adaptiveSizePolicy.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/adaptiveSizePolicy.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -507,7 +507,7 @@
// always fail (never do the print based on the interval test).
return PrintGCDetails &&
UseAdaptiveSizePolicy &&
- (UseParallelGC || UseConcMarkSweepGC) &&
+ UseParallelGC &&
(AdaptiveSizePolicyOutputInterval > 0) &&
((count == 0) ||
((count % AdaptiveSizePolicyOutputInterval) == 0));
--- a/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -134,7 +134,7 @@
Threads::add(res);
Thread::start(res);
}
- os::yield(); // This seems to help with initial start-up of SLT
+ os::naked_yield(); // This seems to help with initial start-up of SLT
return res;
}
--- a/hotspot/src/share/vm/gc_implementation/shared/gcUtil.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/gcUtil.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -216,16 +216,4 @@
bool increment_will_decrease();
};
-class GCPauseTimer : StackObj {
- elapsedTimer* _timer;
- public:
- GCPauseTimer(elapsedTimer* timer) {
- _timer = timer;
- _timer->stop();
- }
- ~GCPauseTimer() {
- _timer->start();
- }
-};
-
#endif // SHARE_VM_GC_IMPLEMENTATION_SHARED_GCUTIL_HPP
--- a/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -54,21 +54,14 @@
void MarkSweep::FollowRootClosure::do_oop(narrowOop* p) { follow_root(p); }
MarkSweep::MarkAndPushClosure MarkSweep::mark_and_push_closure;
-MarkSweep::FollowKlassClosure MarkSweep::follow_klass_closure;
-MarkSweep::AdjustKlassClosure MarkSweep::adjust_klass_closure;
+CLDToOopClosure MarkSweep::follow_cld_closure(&mark_and_push_closure);
+CLDToOopClosure MarkSweep::adjust_cld_closure(&adjust_pointer_closure);
void MarkSweep::MarkAndPushClosure::do_oop(oop* p) { mark_and_push(p); }
void MarkSweep::MarkAndPushClosure::do_oop(narrowOop* p) { mark_and_push(p); }
-void MarkSweep::FollowKlassClosure::do_klass(Klass* klass) {
- klass->oops_do(&MarkSweep::mark_and_push_closure);
-}
-void MarkSweep::AdjustKlassClosure::do_klass(Klass* klass) {
- klass->oops_do(&MarkSweep::adjust_pointer_closure);
-}
-
void MarkSweep::follow_class_loader(ClassLoaderData* cld) {
- cld->oops_do(&MarkSweep::mark_and_push_closure, &MarkSweep::follow_klass_closure, true);
+ MarkSweep::follow_cld_closure.do_cld(cld);
}
void MarkSweep::follow_stack() {
--- a/hotspot/src/share/vm/gc_implementation/shared/markSweep.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/markSweep.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -65,17 +65,6 @@
virtual void do_oop(narrowOop* p);
};
- // The one and only place to start following the classes.
- // Should only be applied to the ClassLoaderData klasses list.
- class FollowKlassClosure : public KlassClosure {
- public:
- void do_klass(Klass* klass);
- };
- class AdjustKlassClosure : public KlassClosure {
- public:
- void do_klass(Klass* klass);
- };
-
class FollowStackClosure: public VoidClosure {
public:
virtual void do_void();
@@ -144,10 +133,10 @@
static IsAliveClosure is_alive;
static FollowRootClosure follow_root_closure;
static MarkAndPushClosure mark_and_push_closure;
- static FollowKlassClosure follow_klass_closure;
static FollowStackClosure follow_stack_closure;
+ static CLDToOopClosure follow_cld_closure;
static AdjustPointerClosure adjust_pointer_closure;
- static AdjustKlassClosure adjust_klass_closure;
+ static CLDToOopClosure adjust_cld_closure;
// Accessors
static uint total_invocations() { return _total_invocations; }
--- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -195,6 +195,43 @@
gch->do_full_collection(gch->must_clear_all_soft_refs(), _max_level);
}
+bool VM_CollectForMetadataAllocation::initiate_concurrent_GC() {
+#if INCLUDE_ALL_GCS
+ if (UseConcMarkSweepGC || UseG1GC) {
+ if (UseConcMarkSweepGC && CMSClassUnloadingEnabled) {
+ MetaspaceGC::set_should_concurrent_collect(true);
+ } else if (UseG1GC) {
+ G1CollectedHeap* g1h = G1CollectedHeap::heap();
+ g1h->g1_policy()->set_initiate_conc_mark_if_possible();
+
+ GCCauseSetter x(g1h, _gc_cause);
+
+ // At this point we are supposed to start a concurrent cycle. We
+ // will do so if one is not already in progress.
+ bool should_start = g1h->g1_policy()->force_initial_mark_if_outside_cycle(_gc_cause);
+
+ if (should_start) {
+ double pause_target = g1h->g1_policy()->max_pause_time_ms();
+ g1h->do_collection_pause_at_safepoint(pause_target);
+ }
+ }
+
+ return true;
+ }
+#endif
+ return false;
+}
+
+static void log_metaspace_alloc_failure_for_concurrent_GC() {
+ if (Verbose && PrintGCDetails) {
+ if (UseConcMarkSweepGC) {
+ gclog_or_tty->print_cr("\nCMS full GC for Metaspace");
+ } else if (UseG1GC) {
+ gclog_or_tty->print_cr("\nG1 full GC for Metaspace");
+ }
+ }
+}
+
void VM_CollectForMetadataAllocation::doit() {
SvcGCMarker sgcm(SvcGCMarker::FULL);
@@ -206,54 +243,57 @@
// a GC that freed space for the allocation.
if (!MetadataAllocationFailALot) {
_result = _loader_data->metaspace_non_null()->allocate(_size, _mdtype);
- }
-
- if (_result == NULL) {
- if (UseConcMarkSweepGC) {
- if (CMSClassUnloadingEnabled) {
- MetaspaceGC::set_should_concurrent_collect(true);
- }
- // For CMS expand since the collection is going to be concurrent.
- _result =
- _loader_data->metaspace_non_null()->expand_and_allocate(_size, _mdtype);
- }
- if (_result == NULL) {
- // Don't clear the soft refs yet.
- if (Verbose && PrintGCDetails && UseConcMarkSweepGC) {
- gclog_or_tty->print_cr("\nCMS full GC for Metaspace");
- }
- heap->collect_as_vm_thread(GCCause::_metadata_GC_threshold);
- // After a GC try to allocate without expanding. Could fail
- // and expansion will be tried below.
- _result =
- _loader_data->metaspace_non_null()->allocate(_size, _mdtype);
- }
- if (_result == NULL) {
- // If still failing, allow the Metaspace to expand.
- // See delta_capacity_until_GC() for explanation of the
- // amount of the expansion.
- // This should work unless there really is no more space
- // or a MaxMetaspaceSize has been specified on the command line.
- _result =
- _loader_data->metaspace_non_null()->expand_and_allocate(_size, _mdtype);
- if (_result == NULL) {
- // If expansion failed, do a last-ditch collection and try allocating
- // again. A last-ditch collection will clear softrefs. This
- // behavior is similar to the last-ditch collection done for perm
- // gen when it was full and a collection for failed allocation
- // did not free perm gen space.
- heap->collect_as_vm_thread(GCCause::_last_ditch_collection);
- _result =
- _loader_data->metaspace_non_null()->allocate(_size, _mdtype);
- }
- }
- if (Verbose && PrintGCDetails && _result == NULL) {
- gclog_or_tty->print_cr("\nAfter Metaspace GC failed to allocate size "
- SIZE_FORMAT, _size);
+ if (_result != NULL) {
+ return;
}
}
- if (_result == NULL && GC_locker::is_active_and_needs_gc()) {
+ if (initiate_concurrent_GC()) {
+ // For CMS and G1 expand since the collection is going to be concurrent.
+ _result = _loader_data->metaspace_non_null()->expand_and_allocate(_size, _mdtype);
+ if (_result != NULL) {
+ return;
+ }
+
+ log_metaspace_alloc_failure_for_concurrent_GC();
+ }
+
+ // Don't clear the soft refs yet.
+ heap->collect_as_vm_thread(GCCause::_metadata_GC_threshold);
+ // After a GC try to allocate without expanding. Could fail
+ // and expansion will be tried below.
+ _result = _loader_data->metaspace_non_null()->allocate(_size, _mdtype);
+ if (_result != NULL) {
+ return;
+ }
+
+ // If still failing, allow the Metaspace to expand.
+ // See delta_capacity_until_GC() for explanation of the
+ // amount of the expansion.
+ // This should work unless there really is no more space
+ // or a MaxMetaspaceSize has been specified on the command line.
+ _result = _loader_data->metaspace_non_null()->expand_and_allocate(_size, _mdtype);
+ if (_result != NULL) {
+ return;
+ }
+
+ // If expansion failed, do a last-ditch collection and try allocating
+ // again. A last-ditch collection will clear softrefs. This
+ // behavior is similar to the last-ditch collection done for perm
+ // gen when it was full and a collection for failed allocation
+ // did not free perm gen space.
+ heap->collect_as_vm_thread(GCCause::_last_ditch_collection);
+ _result = _loader_data->metaspace_non_null()->allocate(_size, _mdtype);
+ if (_result != NULL) {
+ return;
+ }
+
+ if (Verbose && PrintGCDetails) {
+ gclog_or_tty->print_cr("\nAfter Metaspace GC failed to allocate size "
+ SIZE_FORMAT, _size);
+ }
+
+ if (GC_locker::is_active_and_needs_gc()) {
set_gc_locked();
}
}
--- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -217,6 +217,8 @@
virtual VMOp_Type type() const { return VMOp_CollectForMetadataAllocation; }
virtual void doit();
MetaWord* result() const { return _result; }
+
+ bool initiate_concurrent_GC();
};
class SvcGCMarker : public StackObj {
--- a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1093,6 +1093,7 @@
address SignatureHandlerLibrary::set_handler_blob() {
BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
if (handler_blob == NULL) {
+ CompileBroker::handle_full_code_cache();
return NULL;
}
address handler = handler_blob->code_begin();
--- a/hotspot/src/share/vm/interpreter/oopMapCache.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/interpreter/oopMapCache.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -180,7 +180,7 @@
}
}
-bool InterpreterOopMap::is_empty() {
+bool InterpreterOopMap::is_empty() const {
bool result = _method == NULL;
assert(_method != NULL || (_bci == 0 &&
(_mask_size == 0 || _mask_size == USHRT_MAX) &&
@@ -196,7 +196,7 @@
for (int i = 0; i < N; i++) _bit_mask[i] = 0;
}
-void InterpreterOopMap::iterate_oop(OffsetClosure* oop_closure) {
+void InterpreterOopMap::iterate_oop(OffsetClosure* oop_closure) const {
int n = number_of_entries();
int word_index = 0;
uintptr_t value = 0;
@@ -238,7 +238,7 @@
#endif
-void InterpreterOopMap::print() {
+void InterpreterOopMap::print() const {
int n = number_of_entries();
tty->print("oop map for ");
method()->print_value();
@@ -469,7 +469,7 @@
}
}
-inline unsigned int OopMapCache::hash_value_for(methodHandle method, int bci) {
+inline unsigned int OopMapCache::hash_value_for(methodHandle method, int bci) const {
// We use method->code_size() rather than method->identity_hash() below since
// the mark may not be present if a pointer to the method is already reversed.
return ((unsigned int) bci)
@@ -522,7 +522,7 @@
void OopMapCache::lookup(methodHandle method,
int bci,
- InterpreterOopMap* entry_for) {
+ InterpreterOopMap* entry_for) const {
MutexLocker x(&_mut);
OopMapCacheEntry* entry = NULL;
--- a/hotspot/src/share/vm/interpreter/oopMapCache.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/interpreter/oopMapCache.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -101,32 +101,31 @@
// access methods
Method* method() const { return _method; }
- void set_method(Method* v) { _method = v; }
+ void set_method(Method* v) { _method = v; }
int bci() const { return _bci; }
void set_bci(int v) { _bci = v; }
int mask_size() const { return _mask_size; }
void set_mask_size(int v) { _mask_size = v; }
- int number_of_entries() const { return mask_size() / bits_per_entry; }
// Test bit mask size and return either the in-line bit mask or allocated
// bit mask.
- uintptr_t* bit_mask() { return (uintptr_t*)(mask_size() <= small_mask_limit ? (intptr_t)_bit_mask : _bit_mask[0]); }
+ uintptr_t* bit_mask() const { return (uintptr_t*)(mask_size() <= small_mask_limit ? (intptr_t)_bit_mask : _bit_mask[0]); }
// return the word size of_bit_mask. mask_size() <= 4 * MAX_USHORT
- size_t mask_word_size() {
+ size_t mask_word_size() const {
return (mask_size() + BitsPerWord - 1) / BitsPerWord;
}
- uintptr_t entry_at(int offset) { int i = offset * bits_per_entry; return bit_mask()[i / BitsPerWord] >> (i % BitsPerWord); }
+ uintptr_t entry_at(int offset) const { int i = offset * bits_per_entry; return bit_mask()[i / BitsPerWord] >> (i % BitsPerWord); }
- void set_expression_stack_size(int sz) { _expression_stack_size = sz; }
+ void set_expression_stack_size(int sz) { _expression_stack_size = sz; }
#ifdef ENABLE_ZAP_DEAD_LOCALS
- bool is_dead(int offset) { return (entry_at(offset) & (1 << dead_bit_number)) != 0; }
+ bool is_dead(int offset) const { return (entry_at(offset) & (1 << dead_bit_number)) != 0; }
#endif
// Lookup
- bool match(methodHandle method, int bci) { return _method == method() && _bci == bci; }
- bool is_empty();
+ bool match(methodHandle method, int bci) const { return _method == method() && _bci == bci; }
+ bool is_empty() const;
// Initialization
void initialize();
@@ -141,12 +140,13 @@
// in-line), allocate the space from a Resource area.
void resource_copy(OopMapCacheEntry* from);
- void iterate_oop(OffsetClosure* oop_closure);
- void print();
+ void iterate_oop(OffsetClosure* oop_closure) const;
+ void print() const;
- bool is_oop (int offset) { return (entry_at(offset) & (1 << oop_bit_number )) != 0; }
+ int number_of_entries() const { return mask_size() / bits_per_entry; }
+ bool is_oop (int offset) const { return (entry_at(offset) & (1 << oop_bit_number )) != 0; }
- int expression_stack_size() { return _expression_stack_size; }
+ int expression_stack_size() const { return _expression_stack_size; }
#ifdef ENABLE_ZAP_DEAD_LOCALS
void iterate_all(OffsetClosure* oop_closure, OffsetClosure* value_closure, OffsetClosure* dead_closure);
@@ -161,10 +161,10 @@
OopMapCacheEntry* _array;
- unsigned int hash_value_for(methodHandle method, int bci);
+ unsigned int hash_value_for(methodHandle method, int bci) const;
OopMapCacheEntry* entry_at(int i) const;
- Mutex _mut;
+ mutable Mutex _mut;
void flush();
@@ -177,7 +177,7 @@
// Returns the oopMap for (method, bci) in parameter "entry".
// Returns false if an oop map was not found.
- void lookup(methodHandle method, int bci, InterpreterOopMap* entry);
+ void lookup(methodHandle method, int bci, InterpreterOopMap* entry) const;
// Compute an oop map without updating the cache or grabbing any locks (for debugging)
static void compute_one_oop_map(methodHandle method, int bci, InterpreterOopMap* entry);
--- a/hotspot/src/share/vm/memory/allocation.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/allocation.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -36,22 +36,6 @@
#include "services/memTracker.hpp"
#include "utilities/ostream.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
-
void* StackObj::operator new(size_t size) throw() { ShouldNotCallThis(); return 0; }
void StackObj::operator delete(void* p) { ShouldNotCallThis(); }
void* StackObj::operator new [](size_t size) throw() { ShouldNotCallThis(); return 0; }
--- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -429,7 +429,7 @@
OopsInGenClosure* cl,
CardTableRS* ct) {
if (!mr.is_empty()) {
- // Caller (process_strong_roots()) claims that all GC threads
+ // Caller (process_roots()) claims that all GC threads
// execute this call. With UseDynamicNumberOfGCThreads now all
// active GC threads execute this call. The number of active GC
// threads needs to be passed to par_non_clean_card_iterate_work()
@@ -438,7 +438,7 @@
// This is an example of where n_par_threads() is used instead
// of workers()->active_workers(). n_par_threads can be set to 0 to
// turn off parallelism. For example when this code is called as
- // part of verification and SharedHeap::process_strong_roots() is being
+ // part of verification and SharedHeap::process_roots() is being
// used, then n_par_threads() may have been set to 0. active_workers
// is not overloaded with the meaning that it is a switch to disable
// parallelism and so keeps the meaning of the number of
--- a/hotspot/src/share/vm/memory/collectorPolicy.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/collectorPolicy.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -40,10 +40,6 @@
#include "runtime/thread.inline.hpp"
#include "runtime/vmThread.hpp"
#include "utilities/macros.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
-#include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
-#endif // INCLUDE_ALL_GCS
// CollectorPolicy methods
--- a/hotspot/src/share/vm/memory/collectorPolicy.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/collectorPolicy.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -115,7 +115,6 @@
CollectorPolicyKind,
GenCollectorPolicyKind,
ConcurrentMarkSweepPolicyKind,
- ASConcurrentMarkSweepPolicyKind,
G1CollectorPolicyKind
};
--- a/hotspot/src/share/vm/memory/defNewGeneration.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -614,6 +614,9 @@
KlassScanClosure klass_scan_closure(&fsc_with_no_gc_barrier,
gch->rem_set()->klass_rem_set());
+ CLDToKlassAndOopClosure cld_scan_closure(&klass_scan_closure,
+ &fsc_with_no_gc_barrier,
+ false);
set_promo_failure_scan_stack_closure(&fsc_with_no_gc_barrier);
FastEvacuateFollowersClosure evacuate_followers(gch, _level, this,
@@ -623,16 +626,15 @@
assert(gch->no_allocs_since_save_marks(0),
"save marks have not been newly set.");
- int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings | SharedHeap::SO_ScavengeCodeCache;
-
- gch->gen_process_strong_roots(_level,
- true, // Process younger gens, if any,
- // as strong roots.
- true, // activate StrongRootsScope
- SharedHeap::ScanningOption(so),
- &fsc_with_no_gc_barrier,
- &fsc_with_gc_barrier,
- &klass_scan_closure);
+ gch->gen_process_roots(_level,
+ true, // Process younger gens, if any,
+ // as strong roots.
+ true, // activate StrongRootsScope
+ SharedHeap::SO_ScavengeCodeCache,
+ GenCollectedHeap::StrongAndWeakRoots,
+ &fsc_with_no_gc_barrier,
+ &fsc_with_gc_barrier,
+ &cld_scan_closure);
// "evacuate followers".
evacuate_followers.do_void();
--- a/hotspot/src/share/vm/memory/gcLocker.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/gcLocker.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,19 +29,6 @@
#include "memory/genCollectedHeap.hpp"
#include "memory/universe.hpp"
#include "oops/oop.hpp"
-#include "runtime/thread.inline.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
// The direct lock/unlock calls do not force a collection if an unlock
// decrements the count to zero. Avoid calling these if at all possible.
--- a/hotspot/src/share/vm/memory/genCollectedHeap.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/genCollectedHeap.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -61,8 +61,8 @@
GenCollectedHeap* GenCollectedHeap::_gch;
NOT_PRODUCT(size_t GenCollectedHeap::_skip_header_HeapWords = 0;)
-// The set of potentially parallel tasks in strong root scanning.
-enum GCH_process_strong_roots_tasks {
+// The set of potentially parallel tasks in root scanning.
+enum GCH_strong_roots_tasks {
// We probably want to parallelize both of these internally, but for now...
GCH_PS_younger_gens,
// Leave this one last.
@@ -72,11 +72,11 @@
GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) :
SharedHeap(policy),
_gen_policy(policy),
- _gen_process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)),
+ _gen_process_roots_tasks(new SubTasksDone(GCH_PS_NumElements)),
_full_collections_completed(0)
{
- if (_gen_process_strong_tasks == NULL ||
- !_gen_process_strong_tasks->valid()) {
+ if (_gen_process_roots_tasks == NULL ||
+ !_gen_process_roots_tasks->valid()) {
vm_exit_during_initialization("Failed necessary allocation.");
}
assert(policy != NULL, "Sanity check");
@@ -202,13 +202,11 @@
guarantee(policy->is_generation_policy(), "Illegal policy type");
DefNewGeneration* def_new_gen = (DefNewGeneration*) get_gen(0);
assert(def_new_gen->kind() == Generation::DefNew ||
- def_new_gen->kind() == Generation::ParNew ||
- def_new_gen->kind() == Generation::ASParNew,
+ def_new_gen->kind() == Generation::ParNew,
"Wrong generation kind");
Generation* old_gen = get_gen(1);
assert(old_gen->kind() == Generation::ConcurrentMarkSweep ||
- old_gen->kind() == Generation::ASConcurrentMarkSweep ||
old_gen->kind() == Generation::MarkSweepCompact,
"Wrong generation kind");
@@ -573,9 +571,6 @@
}
}
- AdaptiveSizePolicy* sp = gen_policy()->size_policy();
- AdaptiveSizePolicyOutput(sp, total_collections());
-
print_heap_after_gc();
#ifdef TRACESPINNING
@@ -589,24 +584,29 @@
void GenCollectedHeap::set_par_threads(uint t) {
SharedHeap::set_par_threads(t);
- _gen_process_strong_tasks->set_n_threads(t);
+ _gen_process_roots_tasks->set_n_threads(t);
}
void GenCollectedHeap::
-gen_process_strong_roots(int level,
- bool younger_gens_as_roots,
- bool activate_scope,
- SharedHeap::ScanningOption so,
- OopsInGenClosure* not_older_gens,
- OopsInGenClosure* older_gens,
- KlassClosure* klass_closure) {
- // General strong roots.
+gen_process_roots(int level,
+ bool younger_gens_as_roots,
+ bool activate_scope,
+ SharedHeap::ScanningOption so,
+ OopsInGenClosure* not_older_gens,
+ OopsInGenClosure* weak_roots,
+ OopsInGenClosure* older_gens,
+ CLDClosure* cld_closure,
+ CLDClosure* weak_cld_closure,
+ CodeBlobClosure* code_closure) {
- SharedHeap::process_strong_roots(activate_scope, so,
- not_older_gens, klass_closure);
+ // General roots.
+ SharedHeap::process_roots(activate_scope, so,
+ not_older_gens, weak_roots,
+ cld_closure, weak_cld_closure,
+ code_closure);
if (younger_gens_as_roots) {
- if (!_gen_process_strong_tasks->is_task_claimed(GCH_PS_younger_gens)) {
+ if (!_gen_process_roots_tasks->is_task_claimed(GCH_PS_younger_gens)) {
for (int i = 0; i < level; i++) {
not_older_gens->set_generation(_gens[i]);
_gens[i]->oop_iterate(not_older_gens);
@@ -622,7 +622,38 @@
older_gens->reset_generation();
}
- _gen_process_strong_tasks->all_tasks_completed();
+ _gen_process_roots_tasks->all_tasks_completed();
+}
+
+void GenCollectedHeap::
+gen_process_roots(int level,
+ bool younger_gens_as_roots,
+ bool activate_scope,
+ SharedHeap::ScanningOption so,
+ bool only_strong_roots,
+ OopsInGenClosure* not_older_gens,
+ OopsInGenClosure* older_gens,
+ CLDClosure* cld_closure) {
+
+ const bool is_adjust_phase = !only_strong_roots && !younger_gens_as_roots;
+
+ bool is_moving_collection = false;
+ if (level == 0 || is_adjust_phase) {
+ // young collections are always moving
+ is_moving_collection = true;
+ }
+
+ MarkingCodeBlobClosure mark_code_closure(not_older_gens, is_moving_collection);
+ CodeBlobClosure* code_closure = &mark_code_closure;
+
+ gen_process_roots(level,
+ younger_gens_as_roots,
+ activate_scope, so,
+ not_older_gens, only_strong_roots ? NULL : not_older_gens,
+ older_gens,
+ cld_closure, only_strong_roots ? NULL : cld_closure,
+ code_closure);
+
}
void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {
@@ -724,8 +755,7 @@
#if INCLUDE_ALL_GCS
bool GenCollectedHeap::create_cms_collector() {
- assert(((_gens[1]->kind() == Generation::ConcurrentMarkSweep) ||
- (_gens[1]->kind() == Generation::ASConcurrentMarkSweep)),
+ assert(_gens[1]->kind() == Generation::ConcurrentMarkSweep,
"Unexpected generation kinds");
// Skip two header words in the block content verification
NOT_PRODUCT(_skip_header_HeapWords = CMSCollector::skip_header_HeapWords();)
--- a/hotspot/src/share/vm/memory/genCollectedHeap.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/genCollectedHeap.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -78,9 +78,9 @@
unsigned int _full_collections_completed;
// Data structure for claiming the (potentially) parallel tasks in
- // (gen-specific) strong roots processing.
- SubTasksDone* _gen_process_strong_tasks;
- SubTasksDone* gen_process_strong_tasks() { return _gen_process_strong_tasks; }
+ // (gen-specific) roots processing.
+ SubTasksDone* _gen_process_roots_tasks;
+ SubTasksDone* gen_process_roots_tasks() { return _gen_process_roots_tasks; }
// In block contents verification, the number of header words to skip
NOT_PRODUCT(static size_t _skip_header_HeapWords;)
@@ -403,18 +403,30 @@
// The "so" argument determines which of the roots
// the closure is applied to:
// "SO_None" does none;
- // "SO_AllClasses" applies the closure to all entries in the SystemDictionary;
- // "SO_SystemClasses" to all the "system" classes and loaders;
- // "SO_Strings" applies the closure to all entries in the StringTable.
- void gen_process_strong_roots(int level,
- bool younger_gens_as_roots,
- // The remaining arguments are in an order
- // consistent with SharedHeap::process_strong_roots:
- bool activate_scope,
- SharedHeap::ScanningOption so,
- OopsInGenClosure* not_older_gens,
- OopsInGenClosure* older_gens,
- KlassClosure* klass_closure);
+ private:
+ void gen_process_roots(int level,
+ bool younger_gens_as_roots,
+ bool activate_scope,
+ SharedHeap::ScanningOption so,
+ OopsInGenClosure* not_older_gens,
+ OopsInGenClosure* weak_roots,
+ OopsInGenClosure* older_gens,
+ CLDClosure* cld_closure,
+ CLDClosure* weak_cld_closure,
+ CodeBlobClosure* code_closure);
+
+ public:
+ static const bool StrongAndWeakRoots = false;
+ static const bool StrongRootsOnly = true;
+
+ void gen_process_roots(int level,
+ bool younger_gens_as_roots,
+ bool activate_scope,
+ SharedHeap::ScanningOption so,
+ bool only_strong_roots,
+ OopsInGenClosure* not_older_gens,
+ OopsInGenClosure* older_gens,
+ CLDClosure* cld_closure);
// Apply "root_closure" to all the weak roots of the system.
// These include JNI weak roots, string table,
--- a/hotspot/src/share/vm/memory/genMarkSweep.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/genMarkSweep.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -207,13 +207,14 @@
// Need new claim bits before marking starts.
ClassLoaderDataGraph::clear_claimed_marks();
- gch->gen_process_strong_roots(level,
- false, // Younger gens are not roots.
- true, // activate StrongRootsScope
- SharedHeap::SO_SystemClasses,
- &follow_root_closure,
- &follow_root_closure,
- &follow_klass_closure);
+ gch->gen_process_roots(level,
+ false, // Younger gens are not roots.
+ true, // activate StrongRootsScope
+ SharedHeap::SO_None,
+ GenCollectedHeap::StrongRootsOnly,
+ &follow_root_closure,
+ &follow_root_closure,
+ &follow_cld_closure);
// Process reference objects found during marking
{
@@ -291,13 +292,14 @@
// are run.
adjust_pointer_closure.set_orig_generation(gch->get_gen(level));
- gch->gen_process_strong_roots(level,
- false, // Younger gens are not roots.
- true, // activate StrongRootsScope
- SharedHeap::SO_AllClasses | SharedHeap::SO_Strings | SharedHeap::SO_AllCodeCache,
- &adjust_pointer_closure,
- &adjust_pointer_closure,
- &adjust_klass_closure);
+ gch->gen_process_roots(level,
+ false, // Younger gens are not roots.
+ true, // activate StrongRootsScope
+ SharedHeap::SO_AllCodeCache,
+ GenCollectedHeap::StrongAndWeakRoots,
+ &adjust_pointer_closure,
+ &adjust_pointer_closure,
+ &adjust_cld_closure);
gch->gen_process_weak_roots(&adjust_pointer_closure);
--- a/hotspot/src/share/vm/memory/generation.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/generation.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -154,8 +154,7 @@
DefNewGeneration* Generation::as_DefNewGeneration() {
assert((kind() == Generation::DefNew) ||
- (kind() == Generation::ParNew) ||
- (kind() == Generation::ASParNew),
+ (kind() == Generation::ParNew),
"Wrong youngest generation type");
return (DefNewGeneration*) this;
}
--- a/hotspot/src/share/vm/memory/generation.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/generation.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -131,8 +131,6 @@
public:
// The set of possible generation kinds.
enum Name {
- ASParNew,
- ASConcurrentMarkSweep,
DefNew,
ParNew,
MarkSweepCompact,
--- a/hotspot/src/share/vm/memory/generationSpec.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/generationSpec.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -32,7 +32,6 @@
#include "runtime/java.hpp"
#include "utilities/macros.hpp"
#if INCLUDE_ALL_GCS
-#include "gc_implementation/parNew/asParNewGeneration.hpp"
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
#include "gc_implementation/parNew/parNewGeneration.hpp"
#endif // INCLUDE_ALL_GCS
@@ -50,12 +49,6 @@
case Generation::ParNew:
return new ParNewGeneration(rs, init_size(), level);
- case Generation::ASParNew:
- return new ASParNewGeneration(rs,
- init_size(),
- init_size() /* min size */,
- level);
-
case Generation::ConcurrentMarkSweep: {
assert(UseConcMarkSweepGC, "UseConcMarkSweepGC should be set");
CardTableRS* ctrs = remset->as_CardTableRS();
@@ -75,26 +68,6 @@
return g;
}
-
- case Generation::ASConcurrentMarkSweep: {
- assert(UseConcMarkSweepGC, "UseConcMarkSweepGC should be set");
- CardTableRS* ctrs = remset->as_CardTableRS();
- if (ctrs == NULL) {
- vm_exit_during_initialization("Rem set incompatibility.");
- }
- // Otherwise
- // The constructor creates the CMSCollector if needed,
- // else registers with an existing CMSCollector
-
- ASConcurrentMarkSweepGeneration* g = NULL;
- g = new ASConcurrentMarkSweepGeneration(rs,
- init_size(), level, ctrs, UseCMSAdaptiveFreeLists,
- (FreeBlockDictionary<FreeChunk>::DictionaryChoice)CMSDictionaryChoice);
-
- g->initialize_performance_counters();
-
- return g;
- }
#endif // INCLUDE_ALL_GCS
default:
--- a/hotspot/src/share/vm/memory/iterator.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/iterator.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -35,6 +35,10 @@
cld->oops_do(_oop_closure, &_klass_closure, _must_claim_cld);
}
+void CLDToKlassAndOopClosure::do_cld(ClassLoaderData* cld) {
+ cld->oops_do(_oop_closure, _klass_closure, _must_claim_cld);
+}
+
void ObjectToOopClosure::do_object(oop obj) {
obj->oop_iterate(_cl);
}
@@ -43,6 +47,20 @@
ShouldNotCallThis();
}
+void CodeBlobToOopClosure::do_nmethod(nmethod* nm) {
+ nm->oops_do(_cl);
+ if (_fix_relocations) {
+ nm->fix_oop_relocations();
+ }
+}
+
+void CodeBlobToOopClosure::do_code_blob(CodeBlob* cb) {
+ nmethod* nm = cb->as_nmethod_or_null();
+ if (nm != NULL) {
+ do_nmethod(nm);
+ }
+}
+
MarkingCodeBlobClosure::MarkScope::MarkScope(bool activate)
: _active(activate)
{
@@ -55,32 +73,7 @@
void MarkingCodeBlobClosure::do_code_blob(CodeBlob* cb) {
nmethod* nm = cb->as_nmethod_or_null();
- if (nm == NULL) return;
- if (!nm->test_set_oops_do_mark()) {
- NOT_PRODUCT(if (TraceScavenge) nm->print_on(tty, "oops_do, 1st visit\n"));
- do_newly_marked_nmethod(nm);
- } else {
- NOT_PRODUCT(if (TraceScavenge) nm->print_on(tty, "oops_do, skipped on 2nd visit\n"));
+ if (nm != NULL && !nm->test_set_oops_do_mark()) {
+ do_nmethod(nm);
}
}
-
-void CodeBlobToOopClosure::do_newly_marked_nmethod(nmethod* nm) {
- nm->oops_do(_cl, /*allow_zombie=*/ false);
-}
-
-void CodeBlobToOopClosure::do_code_blob(CodeBlob* cb) {
- if (!_do_marking) {
- nmethod* nm = cb->as_nmethod_or_null();
- NOT_PRODUCT(if (TraceScavenge && Verbose && nm != NULL) nm->print_on(tty, "oops_do, unmarked visit\n"));
- // This assert won't work, since there are lots of mini-passes
- // (mostly in debug mode) that co-exist with marking phases.
- //assert(!(cb->is_nmethod() && ((nmethod*)cb)->test_oops_do_mark()), "found marked nmethod during mark-free phase");
- if (nm != NULL) {
- nm->oops_do(_cl);
- }
- } else {
- MarkingCodeBlobClosure::do_code_blob(cb);
- }
-}
-
-
--- a/hotspot/src/share/vm/memory/iterator.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/iterator.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -70,8 +70,8 @@
//
// Providing default implementations of the _nv functions unfortunately
// removes the compile-time safeness, but reduces the clutter for the
- // ExtendedOopClosures that don't need to walk the metadata. Currently,
- // only CMS needs these.
+ // ExtendedOopClosures that don't need to walk the metadata.
+ // Currently, only CMS and G1 need these.
virtual bool do_metadata() { return do_metadata_nv(); }
bool do_metadata_v() { return do_metadata(); }
@@ -126,15 +126,16 @@
_oop_closure = oop_closure;
}
-public:
+ public:
KlassToOopClosure(OopClosure* oop_closure = NULL) : _oop_closure(oop_closure) {}
+
virtual void do_klass(Klass* k);
};
class CLDToOopClosure : public CLDClosure {
- OopClosure* _oop_closure;
+ OopClosure* _oop_closure;
KlassToOopClosure _klass_closure;
- bool _must_claim_cld;
+ bool _must_claim_cld;
public:
CLDToOopClosure(OopClosure* oop_closure, bool must_claim_cld = true) :
@@ -145,6 +146,23 @@
void do_cld(ClassLoaderData* cld);
};
+class CLDToKlassAndOopClosure : public CLDClosure {
+ friend class SharedHeap;
+ friend class G1CollectedHeap;
+ protected:
+ OopClosure* _oop_closure;
+ KlassClosure* _klass_closure;
+ bool _must_claim_cld;
+ public:
+ CLDToKlassAndOopClosure(KlassClosure* klass_closure,
+ OopClosure* oop_closure,
+ bool must_claim_cld) :
+ _oop_closure(oop_closure),
+ _klass_closure(klass_closure),
+ _must_claim_cld(must_claim_cld) {}
+ void do_cld(ClassLoaderData* cld);
+};
+
// The base class for all concurrent marking closures,
// that participates in class unloading.
// It's used to proxy through the metadata to the oops defined in them.
@@ -246,14 +264,26 @@
virtual void do_code_blob(CodeBlob* cb) = 0;
};
-
-class MarkingCodeBlobClosure : public CodeBlobClosure {
+// Applies an oop closure to all ref fields in code blobs
+// iterated over in an object iteration.
+class CodeBlobToOopClosure : public CodeBlobClosure {
+ OopClosure* _cl;
+ bool _fix_relocations;
+ protected:
+ void do_nmethod(nmethod* nm);
public:
+ CodeBlobToOopClosure(OopClosure* cl, bool fix_relocations) : _cl(cl), _fix_relocations(fix_relocations) {}
+ virtual void do_code_blob(CodeBlob* cb);
+
+ const static bool FixRelocations = true;
+};
+
+class MarkingCodeBlobClosure : public CodeBlobToOopClosure {
+ public:
+ MarkingCodeBlobClosure(OopClosure* cl, bool fix_relocations) : CodeBlobToOopClosure(cl, fix_relocations) {}
// Called for each code blob, but at most once per unique blob.
- virtual void do_newly_marked_nmethod(nmethod* nm) = 0;
virtual void do_code_blob(CodeBlob* cb);
- // = { if (!nmethod(cb)->test_set_oops_do_mark()) do_newly_marked_nmethod(cb); }
class MarkScope : public StackObj {
protected:
@@ -266,23 +296,6 @@
};
};
-
-// Applies an oop closure to all ref fields in code blobs
-// iterated over in an object iteration.
-class CodeBlobToOopClosure: public MarkingCodeBlobClosure {
- OopClosure* _cl;
- bool _do_marking;
-public:
- virtual void do_newly_marked_nmethod(nmethod* cb);
- // = { cb->oops_do(_cl); }
- virtual void do_code_blob(CodeBlob* cb);
- // = { if (_do_marking) super::do_code_blob(cb); else cb->oops_do(_cl); }
- CodeBlobToOopClosure(OopClosure* cl, bool do_marking)
- : _cl(cl), _do_marking(do_marking) {}
-};
-
-
-
// MonitorClosure is used for iterating over monitors in the monitors cache
class ObjectMonitor;
--- a/hotspot/src/share/vm/memory/metadataFactory.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/metadataFactory.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,6 +25,7 @@
#ifndef SHARE_VM_MEMORY_METADATAFACTORY_HPP
#define SHARE_VM_MEMORY_METADATAFACTORY_HPP
+#include "classfile/classLoaderData.hpp"
#include "utilities/array.hpp"
#include "utilities/exceptions.hpp"
#include "utilities/globalDefinitions.hpp"
--- a/hotspot/src/share/vm/memory/metaspaceShared.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/metaspaceShared.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -35,6 +35,7 @@
#include "memory/metaspaceShared.hpp"
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
+#include "runtime/os.hpp"
#include "runtime/signature.hpp"
#include "runtime/vm_operations.hpp"
#include "runtime/vmThread.hpp"
--- a/hotspot/src/share/vm/memory/sharedHeap.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/sharedHeap.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,6 +29,7 @@
#include "gc_interface/collectedHeap.inline.hpp"
#include "memory/sharedHeap.hpp"
#include "oops/oop.inline.hpp"
+#include "runtime/atomic.inline.hpp"
#include "runtime/fprofiler.hpp"
#include "runtime/java.hpp"
#include "services/management.hpp"
@@ -39,8 +40,8 @@
SharedHeap* SharedHeap::_sh;
-// The set of potentially parallel tasks in strong root scanning.
-enum SH_process_strong_roots_tasks {
+// The set of potentially parallel tasks in root scanning.
+enum SH_process_roots_tasks {
SH_PS_Universe_oops_do,
SH_PS_JNIHandles_oops_do,
SH_PS_ObjectSynchronizer_oops_do,
@@ -58,6 +59,7 @@
CollectedHeap(),
_collector_policy(policy_),
_rem_set(NULL),
+ _strong_roots_scope(NULL),
_strong_roots_parity(0),
_process_strong_tasks(new SubTasksDone(SH_PS_NumElements)),
_workers(NULL)
@@ -114,6 +116,19 @@
static AssertNonScavengableClosure assert_is_non_scavengable_closure;
#endif
+SharedHeap::StrongRootsScope* SharedHeap::active_strong_roots_scope() const {
+ return _strong_roots_scope;
+}
+void SharedHeap::register_strong_roots_scope(SharedHeap::StrongRootsScope* scope) {
+ assert(_strong_roots_scope == NULL, "Should only have one StrongRootsScope active");
+ assert(scope != NULL, "Illegal argument");
+ _strong_roots_scope = scope;
+}
+void SharedHeap::unregister_strong_roots_scope(SharedHeap::StrongRootsScope* scope) {
+ assert(_strong_roots_scope == scope, "Wrong scope unregistered");
+ _strong_roots_scope = NULL;
+}
+
void SharedHeap::change_strong_roots_parity() {
// Also set the new collection parity.
assert(_strong_roots_parity >= 0 && _strong_roots_parity <= 2,
@@ -124,111 +139,160 @@
"Not in range.");
}
-SharedHeap::StrongRootsScope::StrongRootsScope(SharedHeap* outer, bool activate)
- : MarkScope(activate)
+SharedHeap::StrongRootsScope::StrongRootsScope(SharedHeap* heap, bool activate)
+ : MarkScope(activate), _sh(heap), _n_workers_done_with_threads(0)
{
if (_active) {
- outer->change_strong_roots_parity();
+ _sh->register_strong_roots_scope(this);
+ _sh->change_strong_roots_parity();
// Zero the claimed high water mark in the StringTable
StringTable::clear_parallel_claimed_index();
}
}
SharedHeap::StrongRootsScope::~StrongRootsScope() {
- // nothing particular
+ if (_active) {
+ _sh->unregister_strong_roots_scope(this);
+ }
+}
+
+Monitor* SharedHeap::StrongRootsScope::_lock = new Monitor(Mutex::leaf, "StrongRootsScope lock", false);
+
+void SharedHeap::StrongRootsScope::mark_worker_done_with_threads(uint n_workers) {
+ // The Thread work barrier is only needed by G1.
+ // No need to use the barrier if this is single-threaded code.
+ if (UseG1GC && n_workers > 0) {
+ uint new_value = (uint)Atomic::add(1, &_n_workers_done_with_threads);
+ if (new_value == n_workers) {
+ // This thread is last. Notify the others.
+ MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
+ _lock->notify_all();
+ }
+ }
+}
+
+void SharedHeap::StrongRootsScope::wait_until_all_workers_done_with_threads(uint n_workers) {
+ // No need to use the barrier if this is single-threaded code.
+ if (n_workers > 0 && (uint)_n_workers_done_with_threads != n_workers) {
+ MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
+ while ((uint)_n_workers_done_with_threads != n_workers) {
+ _lock->wait(Mutex::_no_safepoint_check_flag, 0, false);
+ }
+ }
+}
+
+void SharedHeap::process_roots(bool activate_scope,
+ ScanningOption so,
+ OopClosure* strong_roots,
+ OopClosure* weak_roots,
+ CLDClosure* strong_cld_closure,
+ CLDClosure* weak_cld_closure,
+ CodeBlobClosure* code_roots) {
+ StrongRootsScope srs(this, activate_scope);
+
+ // General roots.
+ assert(_strong_roots_parity != 0, "must have called prologue code");
+ assert(code_roots != NULL, "code root closure should always be set");
+ // _n_termination for _process_strong_tasks should be set up stream
+ // in a method not running in a GC worker. Otherwise the GC worker
+ // could be trying to change the termination condition while the task
+ // is executing in another GC worker.
+
+ // Iterating over the CLDG and the Threads are done early to allow G1 to
+ // first process the strong CLDs and nmethods and then, after a barrier,
+ // let the thread process the weak CLDs and nmethods.
+
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_ClassLoaderDataGraph_oops_do)) {
+ ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);
+ }
+
+ // Some CLDs contained in the thread frames should be considered strong.
+ // Don't process them if they will be processed during the ClassLoaderDataGraph phase.
+ CLDClosure* roots_from_clds_p = (strong_cld_closure != weak_cld_closure) ? strong_cld_closure : NULL;
+ // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway
+ CodeBlobClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots;
+
+ Threads::possibly_parallel_oops_do(strong_roots, roots_from_clds_p, roots_from_code_p);
+
+ // This is the point where this worker thread will not find more strong CLDs/nmethods.
+ // Report this so G1 can synchronize the strong and weak CLDs/nmethods processing.
+ active_strong_roots_scope()->mark_worker_done_with_threads(n_par_threads());
+
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_Universe_oops_do)) {
+ Universe::oops_do(strong_roots);
+ }
+ // Global (strong) JNI handles
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_JNIHandles_oops_do))
+ JNIHandles::oops_do(strong_roots);
+
+ if (!_process_strong_tasks-> is_task_claimed(SH_PS_ObjectSynchronizer_oops_do))
+ ObjectSynchronizer::oops_do(strong_roots);
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_FlatProfiler_oops_do))
+ FlatProfiler::oops_do(strong_roots);
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_Management_oops_do))
+ Management::oops_do(strong_roots);
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_jvmti_oops_do))
+ JvmtiExport::oops_do(strong_roots);
+
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_SystemDictionary_oops_do)) {
+ SystemDictionary::roots_oops_do(strong_roots, weak_roots);
+ }
+
+ // All threads execute the following. A specific chunk of buckets
+ // from the StringTable are the individual tasks.
+ if (weak_roots != NULL) {
+ if (CollectedHeap::use_parallel_gc_threads()) {
+ StringTable::possibly_parallel_oops_do(weak_roots);
+ } else {
+ StringTable::oops_do(weak_roots);
+ }
+ }
+
+ if (!_process_strong_tasks->is_task_claimed(SH_PS_CodeCache_oops_do)) {
+ if (so & SO_ScavengeCodeCache) {
+ assert(code_roots != NULL, "must supply closure for code cache");
+
+ // We only visit parts of the CodeCache when scavenging.
+ CodeCache::scavenge_root_nmethods_do(code_roots);
+ }
+ if (so & SO_AllCodeCache) {
+ assert(code_roots != NULL, "must supply closure for code cache");
+
+ // CMSCollector uses this to do intermediate-strength collections.
+ // We scan the entire code cache, since CodeCache::do_unloading is not called.
+ CodeCache::blobs_do(code_roots);
+ }
+ // Verify that the code cache contents are not subject to
+ // movement by a scavenging collection.
+ DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations));
+ DEBUG_ONLY(CodeCache::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));
+ }
+
+ _process_strong_tasks->all_tasks_completed();
+}
+
+void SharedHeap::process_all_roots(bool activate_scope,
+ ScanningOption so,
+ OopClosure* roots,
+ CLDClosure* cld_closure,
+ CodeBlobClosure* code_closure) {
+ process_roots(activate_scope, so,
+ roots, roots,
+ cld_closure, cld_closure,
+ code_closure);
}
void SharedHeap::process_strong_roots(bool activate_scope,
ScanningOption so,
OopClosure* roots,
- KlassClosure* klass_closure) {
- StrongRootsScope srs(this, activate_scope);
-
- // General strong roots.
- assert(_strong_roots_parity != 0, "must have called prologue code");
- // _n_termination for _process_strong_tasks should be set up stream
- // in a method not running in a GC worker. Otherwise the GC worker
- // could be trying to change the termination condition while the task
- // is executing in another GC worker.
- if (!_process_strong_tasks->is_task_claimed(SH_PS_Universe_oops_do)) {
- Universe::oops_do(roots);
- }
- // Global (strong) JNI handles
- if (!_process_strong_tasks->is_task_claimed(SH_PS_JNIHandles_oops_do))
- JNIHandles::oops_do(roots);
-
- CodeBlobToOopClosure code_roots(roots, true);
-
- CLDToOopClosure roots_from_clds(roots);
- // If we limit class scanning to SO_SystemClasses we need to apply a CLD closure to
- // CLDs which are strongly reachable from the thread stacks.
- CLDToOopClosure* roots_from_clds_p = ((so & SO_SystemClasses) ? &roots_from_clds : NULL);
- // All threads execute this; the individual threads are task groups.
- if (CollectedHeap::use_parallel_gc_threads()) {
- Threads::possibly_parallel_oops_do(roots, roots_from_clds_p, &code_roots);
- } else {
- Threads::oops_do(roots, roots_from_clds_p, &code_roots);
- }
-
- if (!_process_strong_tasks-> is_task_claimed(SH_PS_ObjectSynchronizer_oops_do))
- ObjectSynchronizer::oops_do(roots);
- if (!_process_strong_tasks->is_task_claimed(SH_PS_FlatProfiler_oops_do))
- FlatProfiler::oops_do(roots);
- if (!_process_strong_tasks->is_task_claimed(SH_PS_Management_oops_do))
- Management::oops_do(roots);
- if (!_process_strong_tasks->is_task_claimed(SH_PS_jvmti_oops_do))
- JvmtiExport::oops_do(roots);
+ CLDClosure* cld_closure,
+ CodeBlobClosure* code_closure) {
+ process_roots(activate_scope, so,
+ roots, NULL,
+ cld_closure, NULL,
+ code_closure);
+}
- if (!_process_strong_tasks->is_task_claimed(SH_PS_SystemDictionary_oops_do)) {
- if (so & SO_AllClasses) {
- SystemDictionary::oops_do(roots);
- } else if (so & SO_SystemClasses) {
- SystemDictionary::always_strong_oops_do(roots);
- } else {
- fatal("We should always have selected either SO_AllClasses or SO_SystemClasses");
- }
- }
-
- if (!_process_strong_tasks->is_task_claimed(SH_PS_ClassLoaderDataGraph_oops_do)) {
- if (so & SO_AllClasses) {
- ClassLoaderDataGraph::oops_do(roots, klass_closure, /* must_claim */ false);
- } else if (so & SO_SystemClasses) {
- ClassLoaderDataGraph::always_strong_oops_do(roots, klass_closure, /* must_claim */ true);
- }
- }
-
- // All threads execute the following. A specific chunk of buckets
- // from the StringTable are the individual tasks.
- if (so & SO_Strings) {
- if (CollectedHeap::use_parallel_gc_threads()) {
- StringTable::possibly_parallel_oops_do(roots);
- } else {
- StringTable::oops_do(roots);
- }
- }
-
- if (!_process_strong_tasks->is_task_claimed(SH_PS_CodeCache_oops_do)) {
- if (so & SO_ScavengeCodeCache) {
- assert(&code_roots != NULL, "must supply closure for code cache");
-
- // We only visit parts of the CodeCache when scavenging.
- CodeCache::scavenge_root_nmethods_do(&code_roots);
- }
- if (so & SO_AllCodeCache) {
- assert(&code_roots != NULL, "must supply closure for code cache");
-
- // CMSCollector uses this to do intermediate-strength collections.
- // We scan the entire code cache, since CodeCache::do_unloading is not called.
- CodeCache::blobs_do(&code_roots);
- }
- // Verify that the code cache contents are not subject to
- // movement by a scavenging collection.
- DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, /*do_marking=*/ false));
- DEBUG_ONLY(CodeCache::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));
- }
-
- _process_strong_tasks->all_tasks_completed();
-}
class AlwaysTrueClosure: public BoolObjectClosure {
public:
--- a/hotspot/src/share/vm/memory/sharedHeap.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/sharedHeap.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -69,14 +69,10 @@
// number of active GC workers. CompactibleFreeListSpace and Space
// have SequentialSubTasksDone's.
// Example of using SubTasksDone and SequentialSubTasksDone
-// G1CollectedHeap::g1_process_strong_roots() calls
-// process_strong_roots(false, // no scoping; this is parallel code
-// is_scavenging, so,
-// &buf_scan_non_heap_roots,
-// &eager_scan_code_roots);
-// which delegates to SharedHeap::process_strong_roots() and uses
+// G1CollectedHeap::g1_process_roots()
+// to SharedHeap::process_roots() and uses
// SubTasksDone* _process_strong_tasks to claim tasks.
-// process_strong_roots() calls
+// process_roots() calls
// rem_set()->younger_refs_iterate()
// to scan the card table and which eventually calls down into
// CardTableModRefBS::par_non_clean_card_iterate_work(). This method
@@ -182,12 +178,12 @@
// task. (This also means that a parallel thread may only call
// process_strong_roots once.)
//
- // For calls to process_strong_roots by sequential code, the parity is
+ // For calls to process_roots by sequential code, the parity is
// updated automatically.
//
// The idea is that objects representing fine-grained tasks, such as
// threads, will contain a "parity" field. A task will is claimed in the
- // current "process_strong_roots" call only if its parity field is the
+ // current "process_roots" call only if its parity field is the
// same as the "strong_roots_parity"; task claiming is accomplished by
// updating the parity field to the strong_roots_parity with a CAS.
//
@@ -198,27 +194,44 @@
// c) to never return a distinguished value (zero) with which such
// task-claiming variables may be initialized, to indicate "never
// claimed".
- private:
- void change_strong_roots_parity();
public:
int strong_roots_parity() { return _strong_roots_parity; }
- // Call these in sequential code around process_strong_roots.
+ // Call these in sequential code around process_roots.
// strong_roots_prologue calls change_strong_roots_parity, if
// parallel tasks are enabled.
class StrongRootsScope : public MarkingCodeBlobClosure::MarkScope {
- public:
- StrongRootsScope(SharedHeap* outer, bool activate = true);
+ // Used to implement the Thread work barrier.
+ static Monitor* _lock;
+
+ SharedHeap* _sh;
+ volatile jint _n_workers_done_with_threads;
+
+ public:
+ StrongRootsScope(SharedHeap* heap, bool activate = true);
~StrongRootsScope();
+
+ // Mark that this thread is done with the Threads work.
+ void mark_worker_done_with_threads(uint n_workers);
+ // Wait until all n_workers are done with the Threads work.
+ void wait_until_all_workers_done_with_threads(uint n_workers);
};
friend class StrongRootsScope;
+ // The current active StrongRootScope
+ StrongRootsScope* _strong_roots_scope;
+
+ StrongRootsScope* active_strong_roots_scope() const;
+
+ private:
+ void register_strong_roots_scope(StrongRootsScope* scope);
+ void unregister_strong_roots_scope(StrongRootsScope* scope);
+ void change_strong_roots_parity();
+
+ public:
enum ScanningOption {
- SO_None = 0x0,
- SO_AllClasses = 0x1,
- SO_SystemClasses = 0x2,
- SO_Strings = 0x4,
- SO_AllCodeCache = 0x8,
+ SO_None = 0x0,
+ SO_AllCodeCache = 0x8,
SO_ScavengeCodeCache = 0x10
};
@@ -227,15 +240,26 @@
// Invoke the "do_oop" method the closure "roots" on all root locations.
// The "so" argument determines which roots the closure is applied to:
// "SO_None" does none;
- // "SO_AllClasses" applies the closure to all entries in the SystemDictionary;
- // "SO_SystemClasses" to all the "system" classes and loaders;
- // "SO_Strings" applies the closure to all entries in StringTable;
// "SO_AllCodeCache" applies the closure to all elements of the CodeCache.
// "SO_ScavengeCodeCache" applies the closure to elements on the scavenge root list in the CodeCache.
+ void process_roots(bool activate_scope,
+ ScanningOption so,
+ OopClosure* strong_roots,
+ OopClosure* weak_roots,
+ CLDClosure* strong_cld_closure,
+ CLDClosure* weak_cld_closure,
+ CodeBlobClosure* code_roots);
+ void process_all_roots(bool activate_scope,
+ ScanningOption so,
+ OopClosure* roots,
+ CLDClosure* cld_closure,
+ CodeBlobClosure* code_roots);
void process_strong_roots(bool activate_scope,
ScanningOption so,
OopClosure* roots,
- KlassClosure* klass_closure);
+ CLDClosure* cld_closure,
+ CodeBlobClosure* code_roots);
+
// Apply "root_closure" to the JNI weak roots..
void process_weak_roots(OopClosure* root_closure);
@@ -251,7 +275,7 @@
virtual void gc_epilogue(bool full) = 0;
// Sets the number of parallel threads that will be doing tasks
- // (such as process strong roots) subsequently.
+ // (such as process roots) subsequently.
virtual void set_par_threads(uint t);
int n_termination();
--- a/hotspot/src/share/vm/memory/space.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/space.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -685,14 +685,8 @@
// This version requires locking.
inline HeapWord* ContiguousSpace::allocate_impl(size_t size,
HeapWord* const end_value) {
- // In G1 there are places where a GC worker can allocates into a
- // region using this serial allocation code without being prone to a
- // race with other GC workers (we ensure that no other GC worker can
- // access the same region at the same time). So the assert below is
- // too strong in the case of G1.
assert(Heap_lock->owned_by_self() ||
- (SafepointSynchronize::is_at_safepoint() &&
- (Thread::current()->is_VM_thread() || UseG1GC)),
+ (SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread()),
"not locked");
HeapWord* obj = top();
if (pointer_delta(end_value, obj) >= size) {
--- a/hotspot/src/share/vm/memory/universe.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/memory/universe.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -72,7 +72,7 @@
#include "utilities/preserveException.hpp"
#include "utilities/macros.hpp"
#if INCLUDE_ALL_GCS
-#include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
+#include "gc_implementation/shared/adaptiveSizePolicy.hpp"
#include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1CollectorPolicy.hpp"
@@ -802,13 +802,9 @@
gc_policy = new MarkSweepPolicy();
} else if (UseConcMarkSweepGC) {
#if INCLUDE_ALL_GCS
- if (UseAdaptiveSizePolicy) {
- gc_policy = new ASConcurrentMarkSweepPolicy();
- } else {
- gc_policy = new ConcurrentMarkSweepPolicy();
- }
+ gc_policy = new ConcurrentMarkSweepPolicy();
#else // INCLUDE_ALL_GCS
- fatal("UseConcMarkSweepGC not supported in this VM.");
+ fatal("UseConcMarkSweepGC not supported in this VM.");
#endif // INCLUDE_ALL_GCS
} else { // default old generation
gc_policy = new MarkSweepPolicy();
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -245,6 +245,7 @@
set_static_oop_field_count(0);
set_nonstatic_field_size(0);
set_is_marked_dependent(false);
+ set_has_unloaded_dependent(false);
set_init_state(InstanceKlass::allocated);
set_init_thread(NULL);
set_reference_type(rt);
@@ -1801,6 +1802,9 @@
return id;
}
+int nmethodBucket::decrement() {
+ return Atomic::add(-1, (volatile int *)&_count);
+}
//
// Walk the list of dependent nmethods searching for nmethods which
@@ -1815,7 +1819,7 @@
nmethod* nm = b->get_nmethod();
// since dependencies aren't removed until an nmethod becomes a zombie,
// the dependency list may contain nmethods which aren't alive.
- if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
+ if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
if (TraceDependencies) {
ResourceMark rm;
tty->print_cr("Marked for deoptimization");
@@ -1832,6 +1836,43 @@
return found;
}
+void InstanceKlass::clean_dependent_nmethods() {
+ assert_locked_or_safepoint(CodeCache_lock);
+
+ if (has_unloaded_dependent()) {
+ nmethodBucket* b = _dependencies;
+ nmethodBucket* last = NULL;
+ while (b != NULL) {
+ assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
+
+ nmethodBucket* next = b->next();
+
+ if (b->count() == 0) {
+ if (last == NULL) {
+ _dependencies = next;
+ } else {
+ last->set_next(next);
+ }
+ delete b;
+ // last stays the same.
+ } else {
+ last = b;
+ }
+
+ b = next;
+ }
+ set_has_unloaded_dependent(false);
+ }
+#ifdef ASSERT
+ else {
+ // Verification
+ for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
+ assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
+ assert(b->count() != 0, "empty buckets need to be cleaned");
+ }
+ }
+#endif
+}
//
// Add an nmethodBucket to the list of dependencies for this nmethod.
@@ -1866,13 +1907,10 @@
nmethodBucket* last = NULL;
while (b != NULL) {
if (nm == b->get_nmethod()) {
- if (b->decrement() == 0) {
- if (last == NULL) {
- _dependencies = b->next();
- } else {
- last->set_next(b->next());
- }
- delete b;
+ int val = b->decrement();
+ guarantee(val >= 0, err_msg("Underflow: %d", val));
+ if (val == 0) {
+ set_has_unloaded_dependent(true);
}
return;
}
@@ -1911,6 +1949,10 @@
nmethodBucket* b = _dependencies;
while (b != NULL) {
if (nm == b->get_nmethod()) {
+#ifdef ASSERT
+ int count = b->count();
+ assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
+#endif
return true;
}
b = b->next();
@@ -2209,7 +2251,7 @@
#endif // INCLUDE_ALL_GCS
void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
- assert(is_loader_alive(is_alive), "this klass should be live");
+ assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
if (is_interface()) {
if (ClassUnloading) {
Klass* impl = implementor();
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -197,6 +197,7 @@
// _is_marked_dependent can be set concurrently, thus cannot be part of the
// _misc_flags.
bool _is_marked_dependent; // used for marking during flushing and deoptimization
+ bool _has_unloaded_dependent;
enum {
_misc_rewritten = 1 << 0, // methods rewritten.
@@ -444,6 +445,9 @@
bool is_marked_dependent() const { return _is_marked_dependent; }
void set_is_marked_dependent(bool value) { _is_marked_dependent = value; }
+ bool has_unloaded_dependent() const { return _has_unloaded_dependent; }
+ void set_has_unloaded_dependent(bool value) { _has_unloaded_dependent = value; }
+
// initialization (virtuals from Klass)
bool should_be_initialized() const; // means that initialize should be called
void initialize(TRAPS);
@@ -922,6 +926,7 @@
void clean_implementors_list(BoolObjectClosure* is_alive);
void clean_method_data(BoolObjectClosure* is_alive);
+ void clean_dependent_nmethods();
// Explicit metaspace deallocation of fields
// For RedefineClasses and class file parsing errors, we need to deallocate
@@ -1210,7 +1215,7 @@
}
int count() { return _count; }
int increment() { _count += 1; return _count; }
- int decrement() { _count -= 1; assert(_count >= 0, "don't underflow"); return _count; }
+ int decrement();
nmethodBucket* next() { return _next; }
void set_next(nmethodBucket* b) { _next = b; }
nmethod* get_nmethod() { return _nmethod; }
--- a/hotspot/src/share/vm/oops/klass.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/oops/klass.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -42,6 +42,7 @@
#include "utilities/stack.hpp"
#include "utilities/macros.hpp"
#if INCLUDE_ALL_GCS
+#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
#include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
#include "gc_implementation/parallelScavenge/psPromotionManager.hpp"
#include "gc_implementation/parallelScavenge/psScavenge.hpp"
@@ -159,7 +160,12 @@
_primary_supers[0] = k;
set_super_check_offset(in_bytes(primary_supers_offset()));
- set_java_mirror(NULL);
+ // The constructor is used from init_self_patching_vtbl_list,
+ // which doesn't zero out the memory before calling the constructor.
+ // Need to set the field explicitly to not hit an assert that the field
+ // should be NULL before setting it.
+ _java_mirror = NULL;
+
set_modifier_flags(0);
set_layout_helper(Klass::_lh_neutral_value);
set_name(NULL);
@@ -383,7 +389,7 @@
return mirror_alive;
}
-void Klass::clean_weak_klass_links(BoolObjectClosure* is_alive) {
+void Klass::clean_weak_klass_links(BoolObjectClosure* is_alive, bool clean_alive_klasses) {
if (!ClassUnloading) {
return;
}
@@ -428,7 +434,7 @@
}
// Clean the implementors list and method data.
- if (current->oop_is_instance()) {
+ if (clean_alive_klasses && current->oop_is_instance()) {
InstanceKlass* ik = InstanceKlass::cast(current);
ik->clean_implementors_list(is_alive);
ik->clean_method_data(is_alive);
@@ -440,12 +446,18 @@
record_modified_oops();
}
-void Klass::klass_update_barrier_set_pre(void* p, oop v) {
- // This barrier used by G1, where it's used remember the old oop values,
- // so that we don't forget any objects that were live at the snapshot at
- // the beginning. This function is only used when we write oops into
- // Klasses. Since the Klasses are used as roots in G1, we don't have to
- // do anything here.
+// This barrier is used by G1 to remember the old oop values, so
+// that we don't forget any objects that were live at the snapshot at
+// the beginning. This function is only used when we write oops into Klasses.
+void Klass::klass_update_barrier_set_pre(oop* p, oop v) {
+#if INCLUDE_ALL_GCS
+ if (UseG1GC) {
+ oop obj = *p;
+ if (obj != NULL) {
+ G1SATBCardTableModRefBS::enqueue(obj);
+ }
+ }
+#endif
}
void Klass::klass_oop_store(oop* p, oop v) {
@@ -456,7 +468,7 @@
if (always_do_update_barrier) {
klass_oop_store((volatile oop*)p, v);
} else {
- klass_update_barrier_set_pre((void*)p, v);
+ klass_update_barrier_set_pre(p, v);
*p = v;
klass_update_barrier_set(v);
}
@@ -466,7 +478,7 @@
assert(!Universe::heap()->is_in_reserved((void*)p), "Should store pointer into metadata");
assert(v == NULL || Universe::heap()->is_in_reserved((void*)v), "Should store pointer to an object");
- klass_update_barrier_set_pre((void*)p, v);
+ klass_update_barrier_set_pre((oop*)p, v); // Cast away volatile.
OrderAccess::release_store_ptr(p, v);
klass_update_barrier_set(v);
}
--- a/hotspot/src/share/vm/oops/klass.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/oops/klass.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -553,7 +553,10 @@
// The is_alive closure passed in depends on the Garbage Collector used.
bool is_loader_alive(BoolObjectClosure* is_alive);
- static void clean_weak_klass_links(BoolObjectClosure* is_alive);
+ static void clean_weak_klass_links(BoolObjectClosure* is_alive, bool clean_alive_klasses = true);
+ static void clean_subklass_tree(BoolObjectClosure* is_alive) {
+ clean_weak_klass_links(is_alive, false /* clean_alive_klasses */);
+ }
// iterators
virtual int oop_oop_iterate(oop obj, ExtendedOopClosure* blk) = 0;
@@ -660,7 +663,7 @@
private:
// barriers used by klass_oop_store
void klass_update_barrier_set(oop v);
- void klass_update_barrier_set_pre(void* p, oop v);
+ void klass_update_barrier_set_pre(oop* p, oop v);
};
#endif // SHARE_VM_OOPS_KLASS_HPP
--- a/hotspot/src/share/vm/oops/klassVtable.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/oops/klassVtable.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -251,6 +251,17 @@
// For bytecodes not produced by javac together it is possible that a method does not override
// the superclass's method, but might indirectly override a super-super class's vtable entry
// If none found, return a null superk, else return the superk of the method this does override
+// For public and protected methods: if they override a superclass, they will
+// also be overridden themselves appropriately.
+// Private methods do not override and are not overridden.
+// Package Private methods are trickier:
+// e.g. P1.A, pub m
+// P2.B extends A, package private m
+// P1.C extends B, public m
+// P1.C.m needs to override P1.A.m and can not override P2.B.m
+// Therefore: all package private methods need their own vtable entries for
+// them to be the root of an inheritance overriding decision
+// Package private methods may also override other vtable entries
InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, methodHandle target_method,
int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) {
InstanceKlass* superk = initialsuper;
@@ -398,8 +409,11 @@
target_classname, THREAD))
!= (InstanceKlass*)NULL))))
{
- // overriding, so no new entry
- allocate_new = false;
+ // Package private methods always need a new entry to root their own
+ // overriding. They may also override other methods.
+ if (!target_method()->is_package_private()) {
+ allocate_new = false;
+ }
if (checkconstraints) {
// Override vtable entry if passes loader constraint check
@@ -543,8 +557,9 @@
AccessFlags class_flags,
TRAPS) {
if (class_flags.is_interface()) {
- // Interfaces do not use vtables, so there is no point to assigning
- // a vtable index to any of their methods. If we refrain from doing this,
+ // Interfaces do not use vtables, except for java.lang.Object methods,
+ // so there is no point to assigning
+ // a vtable index to any of their local methods. If we refrain from doing this,
// we can use Method::_vtable_index to hold the itable index
return false;
}
@@ -582,6 +597,12 @@
return true;
}
+ // Package private methods always need a new entry to root their own
+ // overriding. This allows transitive overriding to work.
+ if (target_method()->is_package_private()) {
+ return true;
+ }
+
// search through the super class hierarchy to see if we need
// a new entry
ResourceMark rm;
--- a/hotspot/src/share/vm/oops/oopsHierarchy.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/oops/oopsHierarchy.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -124,7 +124,7 @@
operator oopDesc* () const volatile { return obj(); }
operator intptr_t* () const { return (intptr_t*)obj(); }
operator PromotedObject* () const { return (PromotedObject*)obj(); }
- operator markOop () const { return markOop(obj()); }
+ operator markOop () const volatile { return markOop(obj()); }
operator address () const { return (address)obj(); }
// from javaCalls.cpp
--- a/hotspot/src/share/vm/opto/callGenerator.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/callGenerator.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -871,8 +871,11 @@
Node* receiver_node = kit.argument(0);
const TypeOopPtr* receiver_type = gvn.type(receiver_node)->isa_oopptr();
// call_does_dispatch and vtable_index are out-parameters. They might be changed.
- target = C->optimize_virtual_call(caller, jvms->bci(), klass, target, receiver_type,
- is_virtual,
+ // optimize_virtual_call() takes 2 different holder
+ // arguments for a corner case that doesn't apply here (see
+ // Parse::do_call())
+ target = C->optimize_virtual_call(caller, jvms->bci(), klass, klass,
+ target, receiver_type, is_virtual,
call_does_dispatch, vtable_index); // out-parameters
// We lack profiling at this call but type speculation may
// provide us with a type
--- a/hotspot/src/share/vm/opto/compile.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/compile.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,6 +29,7 @@
#include "classfile/systemDictionary.hpp"
#include "code/exceptionHandlerTable.hpp"
#include "code/nmethod.hpp"
+#include "compiler/compileBroker.hpp"
#include "compiler/compileLog.hpp"
#include "compiler/disassembler.hpp"
#include "compiler/oopMap.hpp"
@@ -555,6 +556,7 @@
if (scratch_buffer_blob() == NULL) {
// Let CompilerBroker disable further compilations.
record_failure("Not enough space for scratch buffer in CodeCache");
+ CompileBroker::handle_full_code_cache();
return;
}
}
--- a/hotspot/src/share/vm/opto/compile.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/compile.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -852,8 +852,8 @@
// Helper functions to identify inlining potential at call-site
ciMethod* optimize_virtual_call(ciMethod* caller, int bci, ciInstanceKlass* klass,
- ciMethod* callee, const TypeOopPtr* receiver_type,
- bool is_virtual,
+ ciKlass* holder, ciMethod* callee,
+ const TypeOopPtr* receiver_type, bool is_virtual,
bool &call_does_dispatch, int &vtable_index);
ciMethod* optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
ciMethod* callee, const TypeOopPtr* receiver_type);
--- a/hotspot/src/share/vm/opto/doCall.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/doCall.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -468,8 +468,14 @@
Node* receiver_node = stack(sp() - nargs);
const TypeOopPtr* receiver_type = _gvn.type(receiver_node)->isa_oopptr();
// call_does_dispatch and vtable_index are out-parameters. They might be changed.
- callee = C->optimize_virtual_call(method(), bci(), klass, orig_callee, receiver_type,
- is_virtual,
+ // For arrays, klass below is Object. When vtable calls are used,
+ // resolving the call with Object would allow an illegal call to
+ // finalize() on an array. We use holder instead: illegal calls to
+ // finalize() won't be compiled as vtable calls (IC call
+ // resolution will catch the illegal call) and the few legal calls
+ // on array types won't be either.
+ callee = C->optimize_virtual_call(method(), bci(), klass, holder, orig_callee,
+ receiver_type, is_virtual,
call_does_dispatch, vtable_index); // out-parameters
speculative_receiver_type = receiver_type != NULL ? receiver_type->speculative_type() : NULL;
}
@@ -940,8 +946,8 @@
ciMethod* Compile::optimize_virtual_call(ciMethod* caller, int bci, ciInstanceKlass* klass,
- ciMethod* callee, const TypeOopPtr* receiver_type,
- bool is_virtual,
+ ciKlass* holder, ciMethod* callee,
+ const TypeOopPtr* receiver_type, bool is_virtual,
bool& call_does_dispatch, int& vtable_index) {
// Set default values for out-parameters.
call_does_dispatch = true;
@@ -956,7 +962,7 @@
call_does_dispatch = false;
} else if (!UseInlineCaches && is_virtual && callee->is_loaded()) {
// We can make a vtable call at this site
- vtable_index = callee->resolve_vtable_index(caller->holder(), klass);
+ vtable_index = callee->resolve_vtable_index(caller->holder(), holder);
}
return callee;
}
@@ -979,8 +985,10 @@
ciInstanceKlass* actual_receiver = klass;
if (receiver_type != NULL) {
// Array methods are all inherited from Object, and are monomorphic.
+ // finalize() call on array is not allowed.
if (receiver_type->isa_aryptr() &&
- callee->holder() == env()->Object_klass()) {
+ callee->holder() == env()->Object_klass() &&
+ callee->name() != ciSymbol::finalize_method_name()) {
return callee;
}
--- a/hotspot/src/share/vm/opto/output.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/output.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1163,6 +1163,7 @@
// Have we run out of code space?
if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
C->record_failure("CodeCache is full");
+ CompileBroker::handle_full_code_cache();
return NULL;
}
// Configure the code buffer.
@@ -1487,6 +1488,7 @@
cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
C->record_failure("CodeCache is full");
+ CompileBroker::handle_full_code_cache();
return;
}
@@ -1643,6 +1645,7 @@
// One last check for failed CodeBuffer::expand:
if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
C->record_failure("CodeCache is full");
+ CompileBroker::handle_full_code_cache();
return;
}
--- a/hotspot/src/share/vm/opto/parse.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/parse.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -557,8 +557,9 @@
float dynamic_branch_prediction(float &cnt);
float branch_prediction(float &cnt, BoolTest::mask btest, int target_bci);
- bool seems_never_taken(float prob);
- bool seems_stable_comparison(BoolTest::mask btest, Node* c);
+ bool seems_never_taken(float prob) const;
+ bool path_is_suitable_for_uncommon_trap(float prob) const;
+ bool seems_stable_comparison() const;
void do_ifnull(BoolTest::mask btest, Node* c);
void do_if(BoolTest::mask btest, Node* c);
--- a/hotspot/src/share/vm/opto/parse2.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/opto/parse2.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -886,7 +886,7 @@
// some branches (e.g., _213_javac.Assembler.eliminate) validly produce
// very small but nonzero probabilities, which if confused with zero
// counts would keep the program recompiling indefinitely.
-bool Parse::seems_never_taken(float prob) {
+bool Parse::seems_never_taken(float prob) const {
return prob < PROB_MIN;
}
@@ -898,7 +898,7 @@
// already acting in a stable fashion. If the comparison
// seems stable, we will put an expensive uncommon trap
// on the untaken path.
-bool Parse::seems_stable_comparison(BoolTest::mask btest, Node* cmp) {
+bool Parse::seems_stable_comparison() const {
if (C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if)) {
return false;
}
@@ -1127,6 +1127,14 @@
}
}
+bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
+ // Don't want to speculate on uncommon traps when running with -Xcomp
+ if (!UseInterpreter) {
+ return false;
+ }
+ return (seems_never_taken(prob) && seems_stable_comparison());
+}
+
//----------------------------adjust_map_after_if------------------------------
// Adjust the JVM state to reflect the result of taking this path.
// Basically, it means inspecting the CmpNode controlling this
@@ -1140,7 +1148,7 @@
bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
- if (seems_never_taken(prob) && seems_stable_comparison(btest, c)) {
+ if (path_is_suitable_for_uncommon_trap(prob)) {
repush_if_args();
uncommon_trap(Deoptimization::Reason_unstable_if,
Deoptimization::Action_reinterpret,
--- a/hotspot/src/share/vm/prims/jni.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/jni.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -80,18 +80,6 @@
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/histogram.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
static jint CurrentVersion = JNI_VERSION_1_8;
@@ -3337,7 +3325,7 @@
directBufferSupportInitializeEnded = 1;
} else {
while (!directBufferSupportInitializeEnded && !directBufferSupportInitializeFailed) {
- os::yield();
+ os::naked_yield();
}
}
--- a/hotspot/src/share/vm/prims/jvm.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvm.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -53,7 +53,7 @@
#include "runtime/javaCalls.hpp"
#include "runtime/jfieldIDWorkaround.hpp"
#include "runtime/orderAccess.inline.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/perfData.hpp"
#include "runtime/reflection.hpp"
#include "runtime/thread.inline.hpp"
@@ -3042,7 +3042,7 @@
if (ConvertYieldToSleep) {
os::sleep(thread, MinSleepInterval, false);
} else {
- os::yield();
+ os::naked_yield();
}
JVM_END
@@ -3072,7 +3072,7 @@
// It appears that in certain GUI contexts, it may be beneficial to do a short sleep
// for SOLARIS
if (ConvertSleepToYield) {
- os::yield();
+ os::naked_yield();
} else {
ThreadState old_state = thread->osthread()->get_state();
thread->osthread()->set_state(SLEEPING);
--- a/hotspot/src/share/vm/prims/jvmtiExport.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -47,6 +47,7 @@
#include "runtime/interfaceSupport.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/objectMonitor.inline.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/vframe.hpp"
#include "services/attachListener.hpp"
--- a/hotspot/src/share/vm/prims/jvmtiTagMap.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiTagMap.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -3019,7 +3019,7 @@
// If there are any non-perm roots in the code cache, visit them.
blk.set_kind(JVMTI_HEAP_REFERENCE_OTHER);
- CodeBlobToOopClosure look_in_blobs(&blk, false);
+ CodeBlobToOopClosure look_in_blobs(&blk, !CodeBlobToOopClosure::FixRelocations);
CodeCache::scavenge_root_nmethods_do(&look_in_blobs);
return true;
--- a/hotspot/src/share/vm/prims/nativeLookup.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/nativeLookup.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -41,21 +41,6 @@
#include "runtime/sharedRuntime.hpp"
#include "runtime/signature.hpp"
#include "utilities/macros.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
static void mangle_name_on(outputStream* st, Symbol* name, int begin, int end) {
--- a/hotspot/src/share/vm/prims/whitebox.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/whitebox.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -24,6 +24,7 @@
#include "precompiled.hpp"
+#include "memory/metadataFactory.hpp"
#include "memory/universe.hpp"
#include "oops/oop.inline.hpp"
@@ -38,6 +39,7 @@
#include "runtime/interfaceSupport.hpp"
#include "runtime/os.hpp"
+#include "utilities/array.hpp"
#include "utilities/debug.hpp"
#include "utilities/macros.hpp"
#include "utilities/exceptions.hpp"
@@ -726,7 +728,6 @@
return result;
WB_END
-
WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
return (jlong) Thread::current()->stack_size();
WB_END
@@ -736,6 +737,35 @@
return (jlong) t->stack_available(os::current_stack_pointer()) - (jlong) StackShadowPages * os::vm_page_size();
WB_END
+int WhiteBox::array_bytes_to_length(size_t bytes) {
+ return Array<u1>::bytes_to_length(bytes);
+}
+
+WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
+ if (size < 0) {
+ THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
+ err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
+ }
+
+ oop class_loader_oop = JNIHandles::resolve(class_loader);
+ ClassLoaderData* cld = class_loader_oop != NULL
+ ? java_lang_ClassLoader::loader_data(class_loader_oop)
+ : ClassLoaderData::the_null_class_loader_data();
+
+ void* metadata = MetadataFactory::new_writeable_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
+
+ return (jlong)(uintptr_t)metadata;
+WB_END
+
+WB_ENTRY(void, WB_FreeMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong addr, jlong size))
+ oop class_loader_oop = JNIHandles::resolve(class_loader);
+ ClassLoaderData* cld = class_loader_oop != NULL
+ ? java_lang_ClassLoader::loader_data(class_loader_oop)
+ : ClassLoaderData::the_null_class_loader_data();
+
+ MetadataFactory::free_array(cld, (Array<u1>*)(uintptr_t)addr);
+WB_END
+
//Some convenience methods to deal with objects from java
int WhiteBox::offset_for_field(const char* field_name, oop object,
Symbol* signature_symbol) {
@@ -866,6 +896,10 @@
{CC"isInStringTable", CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable },
{CC"fullGC", CC"()V", (void*)&WB_FullGC },
{CC"readReservedMemory", CC"()V", (void*)&WB_ReadReservedMemory },
+ {CC"allocateMetaspace",
+ CC"(Ljava/lang/ClassLoader;J)J", (void*)&WB_AllocateMetaspace },
+ {CC"freeMetaspace",
+ CC"(Ljava/lang/ClassLoader;JJ)V", (void*)&WB_FreeMetaspace },
{CC"getCPUFeatures", CC"()Ljava/lang/String;", (void*)&WB_GetCPUFeatures },
{CC"getNMethod", CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
(void*)&WB_GetNMethod },
--- a/hotspot/src/share/vm/prims/whitebox.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/prims/whitebox.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -62,6 +62,8 @@
Symbol* signature_symbol);
static const char* lookup_jstring(const char* field_name, oop object);
static bool lookup_bool(const char* field_name, oop object);
+
+ static int array_bytes_to_length(size_t bytes);
};
--- a/hotspot/src/share/vm/runtime/arguments.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -37,26 +37,12 @@
#include "runtime/arguments.hpp"
#include "runtime/globals_extension.hpp"
#include "runtime/java.hpp"
+#include "runtime/os.hpp"
#include "services/management.hpp"
#include "services/memTracker.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/macros.hpp"
#include "utilities/taskqueue.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
#if INCLUDE_ALL_GCS
#include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
--- a/hotspot/src/share/vm/runtime/arguments.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,6 +26,7 @@
#define SHARE_VM_RUNTIME_ARGUMENTS_HPP
#include "runtime/java.hpp"
+#include "runtime/os.hpp"
#include "runtime/perfData.hpp"
#include "utilities/debug.hpp"
#include "utilities/top.hpp"
--- a/hotspot/src/share/vm/runtime/atomic.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/atomic.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,23 +23,6 @@
*/
#include "precompiled.hpp"
-#include "runtime/atomic.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
-
#include "runtime/atomic.inline.hpp"
jbyte Atomic::cmpxchg(jbyte exchange_value, volatile jbyte* dest, jbyte compare_value) {
--- a/hotspot/src/share/vm/runtime/frame.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/frame.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -40,6 +40,7 @@
#include "runtime/handles.inline.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/monitorChunk.hpp"
+#include "runtime/os.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/signature.hpp"
#include "runtime/stubCodeGenerator.hpp"
--- a/hotspot/src/share/vm/runtime/globals.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/globals.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1130,29 +1130,30 @@
"Use LWP-based instead of libthread-based synchronization " \
"(SPARC only)") \
\
- product(ccstr, SyncKnobs, NULL, \
- "(Unstable) Various monitor synchronization tunables") \
- \
- product(intx, EmitSync, 0, \
- "(Unsafe, Unstable) " \
- "Control emission of inline sync fast-path code") \
+ experimental(ccstr, SyncKnobs, NULL, \
+ "(Unstable) Various monitor synchronization tunables") \
+ \
+ experimental(intx, EmitSync, 0, \
+ "(Unsafe, Unstable) " \
+ "Control emission of inline sync fast-path code") \
\
product(intx, MonitorBound, 0, "Bound Monitor population") \
\
product(bool, MonitorInUseLists, false, "Track Monitors for Deflation") \
\
- product(intx, SyncFlags, 0, "(Unsafe, Unstable) Experimental Sync flags") \
- \
- product(intx, SyncVerbose, 0, "(Unstable)") \
- \
- product(intx, ClearFPUAtPark, 0, "(Unsafe, Unstable)") \
- \
- product(intx, hashCode, 5, \
- "(Unstable) select hashCode generation algorithm") \
- \
- product(intx, WorkAroundNPTLTimedWaitHang, 1, \
- "(Unstable, Linux-specific) " \
- "avoid NPTL-FUTEX hang pthread_cond_timedwait") \
+ experimental(intx, SyncFlags, 0, "(Unsafe, Unstable) " \
+ "Experimental Sync flags") \
+ \
+ experimental(intx, SyncVerbose, 0, "(Unstable)") \
+ \
+ experimental(intx, ClearFPUAtPark, 0, "(Unsafe, Unstable)") \
+ \
+ experimental(intx, hashCode, 5, \
+ "(Unstable) select hashCode generation algorithm") \
+ \
+ experimental(intx, WorkAroundNPTLTimedWaitHang, 1, \
+ "(Unstable, Linux-specific) " \
+ "avoid NPTL-FUTEX hang pthread_cond_timedwait") \
\
product(bool, FilterSpuriousWakeups, true, \
"When true prevents OS-level spurious, or premature, wakeups " \
--- a/hotspot/src/share/vm/runtime/handles.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/handles.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -29,18 +29,6 @@
#include "runtime/atomic.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/thread.inline.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
--- a/hotspot/src/share/vm/runtime/icache.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/icache.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -34,6 +34,9 @@
ResourceMark rm;
BufferBlob* b = BufferBlob::create("flush_icache_stub", ICache::stub_size);
+ if (b == NULL) {
+ vm_exit_out_of_memory(ICache::stub_size, OOM_MALLOC_ERROR, "CodeCache: no space for flush_icache_stub");
+ }
CodeBuffer c(b);
ICacheStubGenerator g(&c);
--- a/hotspot/src/share/vm/runtime/interfaceSupport.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/interfaceSupport.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -32,6 +32,7 @@
#include "runtime/init.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/orderAccess.inline.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/threadLocalStorage.hpp"
#include "runtime/vframe.hpp"
#include "utilities/preserveException.hpp"
--- a/hotspot/src/share/vm/runtime/javaCalls.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/javaCalls.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -37,6 +37,7 @@
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/signature.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/thread.inline.hpp"
--- a/hotspot/src/share/vm/runtime/mutex.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/mutex.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,4 +1,3 @@
-
/*
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -488,7 +487,6 @@
for (;;) {
assert(_OnDeck == ESelf, "invariant");
if (TrySpin(Self)) break;
- // CONSIDER: if ESelf->TryPark() && TryLock() break ...
// It's probably wise to spin only if we *actually* blocked
// CONSIDER: check the lockbyte, if it remains set then
// preemptively drain the cxq into the EntryList.
--- a/hotspot/src/share/vm/runtime/mutexLocker.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/mutexLocker.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -24,6 +24,7 @@
#include "precompiled.hpp"
#include "runtime/mutexLocker.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/safepoint.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadLocalStorage.hpp"
--- a/hotspot/src/share/vm/runtime/mutexLocker.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/mutexLocker.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -27,21 +27,6 @@
#include "memory/allocation.hpp"
#include "runtime/mutex.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
// Mutexes used in the VM.
--- a/hotspot/src/share/vm/runtime/objectMonitor.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/objectMonitor.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -43,24 +43,12 @@
#include "utilities/dtrace.hpp"
#include "utilities/macros.hpp"
#include "utilities/preserveException.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
#if defined(__GNUC__) && !defined(IA64) && !defined(PPC64)
// Need to inhibit inlining for older versions of GCC to avoid build-time failures
- #define ATTR __attribute__((noinline))
+ #define NOINLINE __attribute__((noinline))
#else
- #define ATTR
+ #define NOINLINE
#endif
@@ -115,38 +103,39 @@
// The knob* variables are effectively final. Once set they should
// never be modified hence. Consider using __read_mostly with GCC.
-int ObjectMonitor::Knob_Verbose = 0;
-int ObjectMonitor::Knob_SpinLimit = 5000; // derived by an external tool -
-static int Knob_LogSpins = 0; // enable jvmstat tally for spins
-static int Knob_HandOff = 0;
-static int Knob_ReportSettings = 0;
+int ObjectMonitor::Knob_Verbose = 0;
+int ObjectMonitor::Knob_VerifyInUse = 0;
+int ObjectMonitor::Knob_SpinLimit = 5000; // derived by an external tool -
+static int Knob_LogSpins = 0; // enable jvmstat tally for spins
+static int Knob_HandOff = 0;
+static int Knob_ReportSettings = 0;
-static int Knob_SpinBase = 0; // Floor AKA SpinMin
-static int Knob_SpinBackOff = 0; // spin-loop backoff
-static int Knob_CASPenalty = -1; // Penalty for failed CAS
-static int Knob_OXPenalty = -1; // Penalty for observed _owner change
-static int Knob_SpinSetSucc = 1; // spinners set the _succ field
-static int Knob_SpinEarly = 1;
-static int Knob_SuccEnabled = 1; // futile wake throttling
-static int Knob_SuccRestrict = 0; // Limit successors + spinners to at-most-one
-static int Knob_MaxSpinners = -1; // Should be a function of # CPUs
-static int Knob_Bonus = 100; // spin success bonus
-static int Knob_BonusB = 100; // spin success bonus
-static int Knob_Penalty = 200; // spin failure penalty
-static int Knob_Poverty = 1000;
-static int Knob_SpinAfterFutile = 1; // Spin after returning from park()
-static int Knob_FixedSpin = 0;
-static int Knob_OState = 3; // Spinner checks thread state of _owner
-static int Knob_UsePause = 1;
-static int Knob_ExitPolicy = 0;
-static int Knob_PreSpin = 10; // 20-100 likely better
-static int Knob_ResetEvent = 0;
-static int BackOffMask = 0;
+static int Knob_SpinBase = 0; // Floor AKA SpinMin
+static int Knob_SpinBackOff = 0; // spin-loop backoff
+static int Knob_CASPenalty = -1; // Penalty for failed CAS
+static int Knob_OXPenalty = -1; // Penalty for observed _owner change
+static int Knob_SpinSetSucc = 1; // spinners set the _succ field
+static int Knob_SpinEarly = 1;
+static int Knob_SuccEnabled = 1; // futile wake throttling
+static int Knob_SuccRestrict = 0; // Limit successors + spinners to at-most-one
+static int Knob_MaxSpinners = -1; // Should be a function of # CPUs
+static int Knob_Bonus = 100; // spin success bonus
+static int Knob_BonusB = 100; // spin success bonus
+static int Knob_Penalty = 200; // spin failure penalty
+static int Knob_Poverty = 1000;
+static int Knob_SpinAfterFutile = 1; // Spin after returning from park()
+static int Knob_FixedSpin = 0;
+static int Knob_OState = 3; // Spinner checks thread state of _owner
+static int Knob_UsePause = 1;
+static int Knob_ExitPolicy = 0;
+static int Knob_PreSpin = 10; // 20-100 likely better
+static int Knob_ResetEvent = 0;
+static int BackOffMask = 0;
-static int Knob_FastHSSEC = 0;
-static int Knob_MoveNotifyee = 2; // notify() - disposition of notifyee
-static int Knob_QMode = 0; // EntryList-cxq policy - queue discipline
-static volatile int InitDone = 0;
+static int Knob_FastHSSEC = 0;
+static int Knob_MoveNotifyee = 2; // notify() - disposition of notifyee
+static int Knob_QMode = 0; // EntryList-cxq policy - queue discipline
+static volatile int InitDone = 0;
#define TrySpin TrySpin_VaryDuration
@@ -211,7 +200,7 @@
// on EntryList|cxq. That is, spinning relieves contention on the "inner"
// locks and monitor metadata.
//
-// Cxq points to the the set of Recently Arrived Threads attempting entry.
+// Cxq points to the set of Recently Arrived Threads attempting entry.
// Because we push threads onto _cxq with CAS, the RATs must take the form of
// a singly-linked LIFO. We drain _cxq into EntryList at unlock-time when
// the unlocking thread notices that EntryList is null but _cxq is != null.
@@ -281,13 +270,12 @@
}
}
-void ATTR ObjectMonitor::enter(TRAPS) {
+void NOINLINE ObjectMonitor::enter(TRAPS) {
// The following code is ordered to check the most common cases first
// and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors.
Thread * const Self = THREAD;
- void * cur;
- cur = Atomic::cmpxchg_ptr(Self, &_owner, NULL);
+ void * cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL);
if (cur == NULL) {
// Either ASSERT _recursions == 0 or explicitly set _recursions = 0.
assert(_recursions == 0 , "invariant");
@@ -447,26 +435,24 @@
// Callers must compensate as needed.
int ObjectMonitor::TryLock (Thread * Self) {
- for (;;) {
- void * own = _owner;
- if (own != NULL) return 0;
- if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
- // Either guarantee _recursions == 0 or set _recursions = 0.
- assert(_recursions == 0, "invariant");
- assert(_owner == Self, "invariant");
- // CONSIDER: set or assert that OwnerIsThread == 1
- return 1;
- }
- // The lock had been free momentarily, but we lost the race to the lock.
- // Interference -- the CAS failed.
- // We can either return -1 or retry.
- // Retry doesn't make as much sense because the lock was just acquired.
- if (true) return -1;
- }
+ void * own = _owner;
+ if (own != NULL) return 0;
+ if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
+ // Either guarantee _recursions == 0 or set _recursions = 0.
+ assert(_recursions == 0, "invariant");
+ assert(_owner == Self, "invariant");
+ // CONSIDER: set or assert that OwnerIsThread == 1
+ return 1;
+ }
+ // The lock had been free momentarily, but we lost the race to the lock.
+ // Interference -- the CAS failed.
+ // We can either return -1 or retry.
+ // Retry doesn't make as much sense because the lock was just acquired.
+ return -1;
}
-void ATTR ObjectMonitor::EnterI (TRAPS) {
- Thread * Self = THREAD;
+void NOINLINE ObjectMonitor::EnterI (TRAPS) {
+ Thread * const Self = THREAD;
assert(Self->is_Java_thread(), "invariant");
assert(((JavaThread *) Self)->thread_state() == _thread_blocked , "invariant");
@@ -562,7 +548,7 @@
Atomic::cmpxchg_ptr(Self, &_Responsible, NULL);
}
- // The lock have been released while this thread was occupied queueing
+ // The lock might have been released while this thread was occupied queueing
// itself onto _cxq. To close the race and avoid "stranding" and
// progress-liveness failure we must resample-retry _owner before parking.
// Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner.
@@ -714,7 +700,7 @@
// Knob_Reset and Knob_SpinAfterFutile support and restructuring the
// loop accordingly.
-void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) {
+void NOINLINE ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) {
assert(Self != NULL , "invariant");
assert(SelfNode != NULL , "invariant");
assert(SelfNode->_thread == Self , "invariant");
@@ -802,6 +788,7 @@
OrderAccess::fence(); // see comments at the end of EnterI()
}
+// By convention we unlink a contending thread from EntryList|cxq immediately
// after the thread acquires the lock in ::enter(). Equally, we could defer
// unlinking the thread until ::exit()-time.
@@ -822,7 +809,7 @@
assert(prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant");
TEVENT(Unlink from EntryList);
} else {
- guarantee(SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant");
+ assert(SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant");
// Inopportune interleaving -- Self is still on the cxq.
// This usually means the enqueue of self raced an exiting thread.
// Normally we'll find Self near the front of the cxq, so
@@ -862,10 +849,12 @@
TEVENT(Unlink from cxq);
}
+#ifdef ASSERT
// Diagnostic hygiene ...
SelfNode->_prev = (ObjectWaiter *) 0xBAD;
SelfNode->_next = (ObjectWaiter *) 0xBAD;
SelfNode->TState = ObjectWaiter::TS_RUN;
+#endif
}
// -----------------------------------------------------------------------------
@@ -918,9 +907,15 @@
// the integral of the # of active timers at any instant over time).
// Both impinge on OS scalability. Given that, at most one thread parked on
// a monitor will use a timer.
+//
+// There is also the risk of a futile wake-up. If we drop the lock
+// another thread can reacquire the lock immediately, and we can
+// then wake a thread unnecessarily. This is benign, and we've
+// structured the code so the windows are short and the frequency
+// of such futile wakups is low.
-void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) {
- Thread * Self = THREAD;
+void NOINLINE ObjectMonitor::exit(bool not_suspended, TRAPS) {
+ Thread * const Self = THREAD;
if (THREAD != _owner) {
if (THREAD->is_lock_owned((address) _owner)) {
// Transmute _owner from a BasicLock pointer to a Thread address.
@@ -932,14 +927,17 @@
_recursions = 0;
OwnerIsThread = 1;
} else {
- // NOTE: we need to handle unbalanced monitor enter/exit
- // in native code by throwing an exception.
- // TODO: Throw an IllegalMonitorStateException ?
+ // Apparent unbalanced locking ...
+ // Naively we'd like to throw IllegalMonitorStateException.
+ // As a practical matter we can neither allocate nor throw an
+ // exception as ::exit() can be called from leaf routines.
+ // see x86_32.ad Fast_Unlock() and the I1 and I2 properties.
+ // Upon deeper reflection, however, in a properly run JVM the only
+ // way we should encounter this situation is in the presence of
+ // unbalanced JNI locking. TODO: CheckJNICalls.
+ // See also: CR4414101
TEVENT(Exit - Throw IMSX);
- assert(false, "Non-balanced monitor enter/exit!");
- if (false) {
- THROW(vmSymbols::java_lang_IllegalMonitorStateException());
- }
+ assert(false, "Non-balanced monitor enter/exit! Likely JNI locking");
return;
}
}
@@ -988,6 +986,7 @@
return;
}
TEVENT(Inflated exit - complex egress);
+ // Other threads are blocked trying to acquire the lock.
// Normally the exiting thread is responsible for ensuring succession,
// but if other successors are ready or other entering threads are spinning
@@ -1154,9 +1153,9 @@
if (w != NULL) {
// I'd like to write: guarantee (w->_thread != Self).
// But in practice an exiting thread may find itself on the EntryList.
- // Lets say thread T1 calls O.wait(). Wait() enqueues T1 on O's waitset and
+ // Let's say thread T1 calls O.wait(). Wait() enqueues T1 on O's waitset and
// then calls exit(). Exit release the lock by setting O._owner to NULL.
- // Lets say T1 then stalls. T2 acquires O and calls O.notify(). The
+ // Let's say T1 then stalls. T2 acquires O and calls O.notify(). The
// notify() operation moves T1 from O's waitset to O's EntryList. T2 then
// release the lock "O". T2 resumes immediately after the ST of null into
// _owner, above. T2 notices that the EntryList is populated, so it
@@ -1273,10 +1272,13 @@
// MEMBAR
// LD Self_>_suspend_flags
//
+// UPDATE 2007-10-6: since I've replaced the native Mutex/Monitor subsystem
+// with a more efficient implementation, the need to use "FastHSSEC" has
+// decreased. - Dave
bool ObjectMonitor::ExitSuspendEquivalent (JavaThread * jSelf) {
- int Mode = Knob_FastHSSEC;
+ const int Mode = Knob_FastHSSEC;
if (Mode && !jSelf->is_external_suspend()) {
assert(jSelf->is_suspend_equivalent(), "invariant");
jSelf->clear_suspend_equivalent();
@@ -1425,7 +1427,7 @@
// Wait/Notify/NotifyAll
//
// Note: a subset of changes to ObjectMonitor::wait()
-// will need to be replicated in complete_exit above
+// will need to be replicated in complete_exit
void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
Thread * const Self = THREAD;
assert(Self->is_Java_thread(), "Must be Java thread!");
@@ -2280,12 +2282,12 @@
assert(_event != NULL, "invariant");
}
-void ObjectWaiter::wait_reenter_begin(ObjectMonitor *mon) {
+void ObjectWaiter::wait_reenter_begin(ObjectMonitor * const mon) {
JavaThread *jt = (JavaThread *)this->_thread;
_active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(jt, mon);
}
-void ObjectWaiter::wait_reenter_end(ObjectMonitor *mon) {
+void ObjectWaiter::wait_reenter_end(ObjectMonitor * const mon) {
JavaThread *jt = (JavaThread *)this->_thread;
JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(jt, _active);
}
@@ -2467,6 +2469,7 @@
#define SETKNOB(x) { Knob_##x = kvGetInt (knobs, #x, Knob_##x); }
SETKNOB(ReportSettings);
SETKNOB(Verbose);
+ SETKNOB(VerifyInUse);
SETKNOB(FixedSpin);
SETKNOB(SpinLimit);
SETKNOB(SpinBase);
--- a/hotspot/src/share/vm/runtime/objectMonitor.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/objectMonitor.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -311,6 +311,7 @@
public:
static int Knob_Verbose;
+ static int Knob_VerifyInUse;
static int Knob_SpinLimit;
void* operator new (size_t size) throw() {
return AllocateHeap(size, mtInternal);
--- a/hotspot/src/share/vm/runtime/os.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/os.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -46,7 +46,7 @@
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
-#include "runtime/os.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/thread.inline.hpp"
#include "services/attachListener.hpp"
@@ -54,18 +54,6 @@
#include "services/threadService.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
# include <signal.h>
--- a/hotspot/src/share/vm/runtime/os.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/os.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -442,16 +442,7 @@
// ms = 0, will sleep for the least amount of time allowed by the OS.
static void naked_short_sleep(jlong ms);
static void infinite_sleep(); // never returns, use with CAUTION
- static void yield(); // Yields to all threads with same priority
- enum YieldResult {
- YIELD_SWITCHED = 1, // caller descheduled, other ready threads exist & ran
- YIELD_NONEREADY = 0, // No other runnable/ready threads.
- // platform-specific yield return immediately
- YIELD_UNKNOWN = -1 // Unknown: platform doesn't support _SWITCHED or _NONEREADY
- // YIELD_SWITCHED and YIELD_NONREADY imply the platform supports a "strong"
- // yield that can be used in lieu of blocking.
- } ;
- static YieldResult NakedYield () ;
+ static void naked_yield () ;
static OSReturn set_priority(Thread* thread, ThreadPriority priority);
static OSReturn get_priority(const Thread* const thread, ThreadPriority& priority);
@@ -478,9 +469,6 @@
// run cmd in a separate process and return its exit code; or -1 on failures
static int fork_and_exec(char *cmd);
- // Set file to send error reports.
- static void set_error_file(const char *logfile);
-
// os::exit() is merged with vm_exit()
// static void exit(int num);
@@ -629,11 +617,6 @@
static void print_jni_name_prefix_on(outputStream* st, int args_size);
static void print_jni_name_suffix_on(outputStream* st, int args_size);
- // File conventions
- static const char* file_separator();
- static const char* line_separator();
- static const char* path_separator();
-
// Init os specific system properties values
static void init_system_properties_values();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/vm/runtime/os.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_RUNTIME_OS_INLINE_HPP
+#define SHARE_VM_RUNTIME_OS_INLINE_HPP
+
+#include "runtime/os.hpp"
+
+#ifdef TARGET_OS_FAMILY_linux
+# include "os_linux.inline.hpp"
+#endif
+#ifdef TARGET_OS_FAMILY_solaris
+# include "os_solaris.inline.hpp"
+#endif
+#ifdef TARGET_OS_FAMILY_windows
+# include "os_windows.inline.hpp"
+#endif
+#ifdef TARGET_OS_FAMILY_aix
+# include "os_aix.inline.hpp"
+#endif
+#ifdef TARGET_OS_FAMILY_bsd
+# include "os_bsd.inline.hpp"
+#endif
+
+#endif // SHARE_VM_RUNTIME_OS_INLINE_HPP
--- a/hotspot/src/share/vm/runtime/safepoint.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/safepoint.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -322,7 +322,7 @@
SpinPause() ; // MP-Polite spin
} else
if (steps < DeferThrSuspendLoopCount) {
- os::NakedYield() ;
+ os::naked_yield() ;
} else {
os::naked_short_sleep(1);
}
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1810,14 +1810,8 @@
// Handles the uncommon case in locking, i.e., contention or an inflated lock.
-#ifndef PRODUCT
-int SharedRuntime::_monitor_enter_ctr=0;
-#endif
JRT_ENTRY_NO_ASYNC(void, SharedRuntime::complete_monitor_locking_C(oopDesc* _obj, BasicLock* lock, JavaThread* thread))
oop obj(_obj);
-#ifndef PRODUCT
- _monitor_enter_ctr++; // monitor enter slow
-#endif
if (PrintBiasedLockingStatistics) {
Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
}
@@ -1831,15 +1825,9 @@
assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
JRT_END
-#ifndef PRODUCT
-int SharedRuntime::_monitor_exit_ctr=0;
-#endif
// Handles the uncommon cases of monitor unlocking in compiled code
JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* _obj, BasicLock* lock))
oop obj(_obj);
-#ifndef PRODUCT
- _monitor_exit_ctr++; // monitor exit slow
-#endif
Thread* THREAD = JavaThread::current();
// I'm not convinced we need the code contained by MIGHT_HAVE_PENDING anymore
// testing was unable to ever fire the assert that guarded it so I have removed it.
@@ -1879,8 +1867,6 @@
ttyLocker ttyl;
if (xtty != NULL) xtty->head("statistics type='SharedRuntime'");
- if (_monitor_enter_ctr) tty->print_cr("%5d monitor enter slow", _monitor_enter_ctr);
- if (_monitor_exit_ctr) tty->print_cr("%5d monitor exit slow", _monitor_exit_ctr);
if (_throw_null_ctr) tty->print_cr("%5d implicit null throw", _throw_null_ctr);
SharedRuntime::print_ic_miss_histogram();
@@ -2464,9 +2450,9 @@
if (PrintAdapterHandlers || PrintStubCode) {
ttyLocker ttyl;
entry->print_adapter_on(tty);
- tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)",
+ tty->print_cr("i2c argument handler #%d for: %s %s %s (%d bytes generated)",
_adapters->number_of_entries(), (method->is_static() ? "static" : "receiver"),
- method->signature()->as_C_string(), insts_size);
+ method->signature()->as_C_string(), fingerprint->as_string(), insts_size);
tty->print_cr("c2i argument handler starts at %p", entry->get_c2i_entry());
if (Verbose || PrintStubCode) {
address first_pc = entry->base_address();
--- a/hotspot/src/share/vm/runtime/sharedRuntime.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -516,8 +516,6 @@
static void trace_ic_miss(address at);
public:
- static int _monitor_enter_ctr; // monitor enter slow
- static int _monitor_exit_ctr; // monitor exit slow
static int _throw_null_ctr; // throwing a null-pointer exception
static int _ic_miss_ctr; // total # of IC misses
static int _wrong_method_ctr;
--- a/hotspot/src/share/vm/runtime/synchronizer.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/synchronizer.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -41,24 +41,12 @@
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/preserveException.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
#if defined(__GNUC__) && !defined(PPC64)
// Need to inhibit inlining for older versions of GCC to avoid build-time failures
- #define ATTR __attribute__((noinline))
+ #define NOINLINE __attribute__((noinline))
#else
- #define ATTR
+ #define NOINLINE
#endif
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
@@ -218,14 +206,6 @@
return;
}
-#if 0
- // The following optimization isn't particularly useful.
- if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) {
- lock->set_displaced_header(NULL);
- return;
- }
-#endif
-
// The object header will never be displaced to this lock,
// so it does not matter what the value is, except that it
// must be non-zero to avoid looking like a re-entrant lock,
@@ -469,7 +449,7 @@
++its;
if (its > 10000 || !os::is_MP()) {
if (its & 1) {
- os::NakedYield();
+ os::naked_yield();
TEVENT(Inflate: INFLATING - yield);
} else {
// Note that the following code attenuates the livelock problem but is not
@@ -499,7 +479,7 @@
if ((YieldThenBlock++) >= 16) {
Thread::current()->_ParkEvent->park(1);
} else {
- os::NakedYield();
+ os::naked_yield();
}
}
Thread::muxRelease(InflationLocks + ix);
@@ -585,7 +565,7 @@
// added check of the bias pattern is to avoid useless calls to
// thread-local storage.
if (obj->mark()->has_bias_pattern()) {
- // Box and unbox the raw reference just in case we cause a STW safepoint.
+ // Handle for oop obj in case of STW safepoint
Handle hobj(Self, obj);
// Relaxing assertion for bug 6320749.
assert(Universe::verify_in_progress() ||
@@ -902,23 +882,23 @@
}
}
}
-/* Too slow for general assert or debug
+
void ObjectSynchronizer::verifyInUse (Thread *Self) {
ObjectMonitor* mid;
int inusetally = 0;
for (mid = Self->omInUseList; mid != NULL; mid = mid->FreeNext) {
- inusetally ++;
+ inusetally++;
}
assert(inusetally == Self->omInUseCount, "inuse count off");
int freetally = 0;
for (mid = Self->omFreeList; mid != NULL; mid = mid->FreeNext) {
- freetally ++;
+ freetally++;
}
assert(freetally == Self->omFreeCount, "free count off");
}
-*/
-ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) {
+
+ObjectMonitor * NOINLINE ObjectSynchronizer::omAlloc (Thread * Self) {
// A large MAXPRIVATE value reduces both list lock contention
// and list coherency traffic, but also tends to increase the
// number of objectMonitors in circulation as well as the STW
@@ -944,7 +924,9 @@
m->FreeNext = Self->omInUseList;
Self->omInUseList = m;
Self->omInUseCount++;
- // verifyInUse(Self);
+ if (ObjectMonitor::Knob_VerifyInUse) {
+ verifyInUse(Self);
+ }
} else {
m->FreeNext = NULL;
}
@@ -1064,7 +1046,9 @@
curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
}
Self->omInUseCount--;
- // verifyInUse(Self);
+ if (ObjectMonitor::Knob_VerifyInUse) {
+ verifyInUse(Self);
+ }
break;
} else {
curmidinuse = mid;
@@ -1073,7 +1057,7 @@
}
}
- // FreeNext is used for both onInUseList and omFreeList, so clear old before setting new
+ // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new
m->FreeNext = Self->omFreeList;
Self->omFreeList = m;
Self->omFreeCount++;
@@ -1086,7 +1070,7 @@
// consecutive STW safepoints. Relatedly, we might decay
// omFreeProvision at STW safepoints.
//
-// Also return the monitors of a moribund thread"s omInUseList to
+// Also return the monitors of a moribund thread's omInUseList to
// a global gOmInUseList under the global list lock so these
// will continue to be scanned.
//
@@ -1127,7 +1111,6 @@
InUseTail = curom;
InUseTally++;
}
-// TODO debug
assert(Self->omInUseCount == InUseTally, "inuse count off");
Self->omInUseCount = 0;
guarantee(InUseTail != NULL && InUseList != NULL, "invariant");
@@ -1166,7 +1149,7 @@
// multiple locks occupy the same $ line. Padding might be appropriate.
-ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
+ObjectMonitor * NOINLINE ObjectSynchronizer::inflate (Thread * Self, oop object) {
// Inflate mutates the heap ...
// Relaxing assertion for bug 6320749.
assert(Universe::verify_in_progress() ||
@@ -1397,7 +1380,7 @@
// Deflate a single monitor if not in use
// Return true if deflated, false if in use
bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
- ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
+ ObjectMonitor** freeHeadp, ObjectMonitor** freeTailp) {
bool deflated;
// Normal case ... The monitor is associated with obj.
guarantee(obj->mark() == markOopDesc::encode(mid), "invariant");
@@ -1427,13 +1410,13 @@
assert(mid->object() == NULL, "invariant");
// Move the object to the working free list defined by FreeHead,FreeTail.
- if (*FreeHeadp == NULL) *FreeHeadp = mid;
- if (*FreeTailp != NULL) {
- ObjectMonitor * prevtail = *FreeTailp;
+ if (*freeHeadp == NULL) *freeHeadp = mid;
+ if (*freeTailp != NULL) {
+ ObjectMonitor * prevtail = *freeTailp;
assert(prevtail->FreeNext == NULL, "cleaned up deflated?"); // TODO KK
prevtail->FreeNext = mid;
}
- *FreeTailp = mid;
+ *freeTailp = mid;
deflated = true;
}
return deflated;
@@ -1441,7 +1424,7 @@
// Caller acquires ListLock
int ObjectSynchronizer::walk_monitor_list(ObjectMonitor** listheadp,
- ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
+ ObjectMonitor** freeHeadp, ObjectMonitor** freeTailp) {
ObjectMonitor* mid;
ObjectMonitor* next;
ObjectMonitor* curmidinuse = NULL;
@@ -1451,7 +1434,7 @@
oop obj = (oop) mid->object();
bool deflated = false;
if (obj != NULL) {
- deflated = deflate_monitor(mid, obj, FreeHeadp, FreeTailp);
+ deflated = deflate_monitor(mid, obj, freeHeadp, freeTailp);
}
if (deflated) {
// extract from per-thread in-use-list
@@ -1494,7 +1477,9 @@
nInCirculation+= cur->omInUseCount;
int deflatedcount = walk_monitor_list(cur->omInUseList_addr(), &FreeHead, &FreeTail);
cur->omInUseCount-= deflatedcount;
- // verifyInUse(cur);
+ if (ObjectMonitor::Knob_VerifyInUse) {
+ verifyInUse(cur);
+ }
nScavenged += deflatedcount;
nInuse += cur->omInUseCount;
}
--- a/hotspot/src/share/vm/runtime/synchronizer.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/synchronizer.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -84,7 +84,7 @@
static void reenter (Handle obj, intptr_t recursion, TRAPS);
// thread-specific and global objectMonitor free list accessors
-// static void verifyInUse (Thread * Self) ; too slow for general assert/debug
+ static void verifyInUse(Thread * Self);
static ObjectMonitor * omAlloc(Thread * Self);
static void omRelease(Thread * Self, ObjectMonitor * m, bool FromPerThreadAlloc);
static void omFlush(Thread * Self);
@@ -114,10 +114,10 @@
// An adaptive profile-based deflation policy could be used if needed
static void deflate_idle_monitors();
static int walk_monitor_list(ObjectMonitor** listheadp,
- ObjectMonitor** FreeHeadp,
- ObjectMonitor** FreeTailp);
- static bool deflate_monitor(ObjectMonitor* mid, oop obj, ObjectMonitor** FreeHeadp,
- ObjectMonitor** FreeTailp);
+ ObjectMonitor** freeHeadp,
+ ObjectMonitor** freeTailp);
+ static bool deflate_monitor(ObjectMonitor* mid, oop obj, ObjectMonitor** freeHeadp,
+ ObjectMonitor** freeTailp);
static void oops_do(OopClosure* f);
// debugging
@@ -130,7 +130,10 @@
enum { _BLOCKSIZE = 128 };
static ObjectMonitor* gBlockList;
static ObjectMonitor * volatile gFreeList;
- static ObjectMonitor * volatile gOmInUseList; // for moribund thread, so monitors they inflated still get scanned
+ // global monitor in use list, for moribund threads,
+ // monitors they inflated need to be scanned for deflation
+ static ObjectMonitor * volatile gOmInUseList;
+ // count of entries in gOmInUseList
static int gOmInUseCount;
};
--- a/hotspot/src/share/vm/runtime/task.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/task.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,18 +28,6 @@
#include "runtime/task.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/timer.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
int PeriodicTask::_num_tasks = 0;
PeriodicTask* PeriodicTask::_tasks[PeriodicTask::max_tasks];
--- a/hotspot/src/share/vm/runtime/thread.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/thread.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -85,18 +85,6 @@
#include "utilities/events.hpp"
#include "utilities/preserveException.hpp"
#include "utilities/macros.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
#if INCLUDE_ALL_GCS
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
@@ -4111,8 +4099,8 @@
SharedHeap* sh = SharedHeap::heap();
// Cannot yet substitute active_workers for n_par_threads
// because of G1CollectedHeap::verify() use of
- // SharedHeap::process_strong_roots(). n_par_threads == 0 will
- // turn off parallelism in process_strong_roots while active_workers
+ // SharedHeap::process_roots(). n_par_threads == 0 will
+ // turn off parallelism in process_roots while active_workers
// is being used for parallelism elsewhere.
bool is_par = sh->n_par_threads() > 0;
assert(!is_par ||
@@ -4386,7 +4374,7 @@
if (Yields > 5) {
os::naked_short_sleep(1);
} else {
- os::NakedYield();
+ os::naked_yield();
++Yields;
}
} else {
@@ -4404,6 +4392,12 @@
// It's safe if subsequent LDs and STs float "up" into the critical section,
// but prior LDs and STs within the critical section can't be allowed
// to reorder or float past the ST that releases the lock.
+ // Loads and stores in the critical section - which appear in program
+ // order before the store that releases the lock - must also appear
+ // before the store that releases the lock in memory visibility order.
+ // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
+ // the ST of 0 into the lock-word which releases the lock, so fence
+ // more than covers this on all platforms.
*adr = 0;
}
@@ -4585,18 +4579,25 @@
// This implementation pops from the head of the list. This is unfair,
// but tends to provide excellent throughput as hot threads remain hot.
// (We wake recently run threads first).
-
+//
+// All paths through muxRelease() will execute a CAS.
+// Release consistency -- We depend on the CAS in muxRelease() to provide full
+// bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
+// executed within the critical section are complete and globally visible before the
+// store (CAS) to the lock-word that releases the lock becomes globally visible.
void Thread::muxRelease (volatile intptr_t * Lock) {
for (;;) {
const intptr_t w = Atomic::cmpxchg_ptr(0, Lock, LOCKBIT);
assert(w & LOCKBIT, "invariant");
if (w == LOCKBIT) return;
- ParkEvent * List = (ParkEvent *)(w & ~LOCKBIT);
+ ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
assert(List != NULL, "invariant");
assert(List->OnList == intptr_t(Lock), "invariant");
- ParkEvent * nxt = List->ListNext;
+ ParkEvent * const nxt = List->ListNext;
+ guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant");
// The following CAS() releases the lock and pops the head element.
+ // The CAS() also ratifies the previously fetched lock-word value.
if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
continue;
}
--- a/hotspot/src/share/vm/runtime/thread.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/thread.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -452,7 +452,7 @@
private:
bool claim_oops_do_par_case(int collection_parity);
public:
- // Requires that "collection_parity" is that of the current strong roots
+ // Requires that "collection_parity" is that of the current roots
// iteration. If "is_par" is false, sets the parity of "this" to
// "collection_parity", and returns "true". If "is_par" is true,
// uses an atomic instruction to set the current threads parity to
@@ -1761,34 +1761,6 @@
return (CompilerThread*)this;
}
-inline bool JavaThread::stack_guard_zone_unused() {
- return _stack_guard_state == stack_guard_unused;
-}
-
-inline bool JavaThread::stack_yellow_zone_disabled() {
- return _stack_guard_state == stack_guard_yellow_disabled;
-}
-
-inline bool JavaThread::stack_yellow_zone_enabled() {
-#ifdef ASSERT
- if (os::uses_stack_guard_pages()) {
- assert(_stack_guard_state != stack_guard_unused, "guard pages must be in use");
- }
-#endif
- return _stack_guard_state == stack_guard_enabled;
-}
-
-inline size_t JavaThread::stack_available(address cur_sp) {
- // This code assumes java stacks grow down
- address low_addr; // Limit on the address for deepest stack depth
- if (_stack_guard_state == stack_guard_unused) {
- low_addr = stack_base() - stack_size();
- } else {
- low_addr = stack_yellow_zone_base();
- }
- return cur_sp > low_addr ? cur_sp - low_addr : 0;
-}
-
// A thread used for Compilation.
class CompilerThread : public JavaThread {
friend class VMStructs;
@@ -1863,7 +1835,6 @@
return JavaThread::current()->as_CompilerThread();
}
-
// The active thread queue. It also keeps track of the current used
// thread priorities.
class Threads: AllStatic {
--- a/hotspot/src/share/vm/runtime/thread.inline.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/thread.inline.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
#define SHARE_VM_RUNTIME_THREAD_INLINE_HPP_SCOPE
#include "runtime/atomic.inline.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/thread.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "thread_linux.inline.hpp"
@@ -136,4 +137,32 @@
OrderAccess::fence();
}
+inline bool JavaThread::stack_guard_zone_unused() {
+ return _stack_guard_state == stack_guard_unused;
+}
+
+inline bool JavaThread::stack_yellow_zone_disabled() {
+ return _stack_guard_state == stack_guard_yellow_disabled;
+}
+
+inline size_t JavaThread::stack_available(address cur_sp) {
+ // This code assumes java stacks grow down
+ address low_addr; // Limit on the address for deepest stack depth
+ if (_stack_guard_state == stack_guard_unused) {
+ low_addr = stack_base() - stack_size();
+ } else {
+ low_addr = stack_yellow_zone_base();
+ }
+ return cur_sp > low_addr ? cur_sp - low_addr : 0;
+}
+
+inline bool JavaThread::stack_yellow_zone_enabled() {
+#ifdef ASSERT
+ if (os::uses_stack_guard_pages()) {
+ assert(_stack_guard_state != stack_guard_unused, "guard pages must be in use");
+ }
+#endif
+ return _stack_guard_state == stack_guard_enabled;
+}
+
#endif // SHARE_VM_RUNTIME_THREAD_INLINE_HPP
--- a/hotspot/src/share/vm/runtime/threadLocalStorage.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/threadLocalStorage.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,20 +23,9 @@
*/
#include "precompiled.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadLocalStorage.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
// static member initialization
int ThreadLocalStorage::_thread_index = -1;
--- a/hotspot/src/share/vm/runtime/timer.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/timer.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -26,21 +26,6 @@
#include "oops/oop.inline.hpp"
#include "runtime/timer.hpp"
#include "utilities/ostream.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
double TimeHelper::counter_to_seconds(jlong counter) {
double count = (double) counter;
--- a/hotspot/src/share/vm/runtime/vframe.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vframe.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -260,66 +260,156 @@
return fr().interpreter_frame_method();
}
-StackValueCollection* interpretedVFrame::locals() const {
- int length = method()->max_locals();
+static StackValue* create_stack_value_from_oop_map(const InterpreterOopMap& oop_mask,
+ int index,
+ const intptr_t* const addr) {
+
+ assert(index >= 0 &&
+ index < oop_mask.number_of_entries(), "invariant");
- if (method()->is_native()) {
- // If the method is native, max_locals is not telling the truth.
- // maxlocals then equals the size of parameters
- length = method()->size_of_parameters();
+ // categorize using oop_mask
+ if (oop_mask.is_oop(index)) {
+ // reference (oop) "r"
+ Handle h(addr != NULL ? (*(oop*)addr) : (oop)NULL);
+ return new StackValue(h);
+ }
+ // value (integer) "v"
+ return new StackValue(addr != NULL ? *addr : 0);
+}
+
+static bool is_in_expression_stack(const frame& fr, const intptr_t* const addr) {
+ assert(addr != NULL, "invariant");
+
+ // Ensure to be 'inside' the expresion stack (i.e., addr >= sp for Intel).
+ // In case of exceptions, the expression stack is invalid and the sp
+ // will be reset to express this condition.
+ if (frame::interpreter_frame_expression_stack_direction() > 0) {
+ return addr <= fr.interpreter_frame_tos_address();
}
- StackValueCollection* result = new StackValueCollection(length);
+ return addr >= fr.interpreter_frame_tos_address();
+}
+
+static void stack_locals(StackValueCollection* result,
+ int length,
+ const InterpreterOopMap& oop_mask,
+ const frame& fr) {
+
+ assert(result != NULL, "invariant");
+
+ for (int i = 0; i < length; ++i) {
+ const intptr_t* const addr = fr.interpreter_frame_local_at(i);
+ assert(addr != NULL, "invariant");
+ assert(addr >= fr.sp(), "must be inside the frame");
+
+ StackValue* const sv = create_stack_value_from_oop_map(oop_mask, i, addr);
+ assert(sv != NULL, "sanity check");
+
+ result->add(sv);
+ }
+}
+
+static void stack_expressions(StackValueCollection* result,
+ int length,
+ int max_locals,
+ const InterpreterOopMap& oop_mask,
+ const frame& fr) {
+
+ assert(result != NULL, "invariant");
- // Get oopmap describing oops and int for current bci
+ for (int i = 0; i < length; ++i) {
+ const intptr_t* addr = fr.interpreter_frame_expression_stack_at(i);
+ assert(addr != NULL, "invariant");
+ if (!is_in_expression_stack(fr, addr)) {
+ // Need to ensure no bogus escapes.
+ addr = NULL;
+ }
+
+ StackValue* const sv = create_stack_value_from_oop_map(oop_mask,
+ i + max_locals,
+ addr);
+ assert(sv != NULL, "sanity check");
+
+ result->add(sv);
+ }
+}
+
+StackValueCollection* interpretedVFrame::locals() const {
+ return stack_data(false);
+}
+
+StackValueCollection* interpretedVFrame::expressions() const {
+ return stack_data(true);
+}
+
+/*
+ * Worker routine for fetching references and/or values
+ * for a particular bci in the interpretedVFrame.
+ *
+ * Returns data for either "locals" or "expressions",
+ * using bci relative oop_map (oop_mask) information.
+ *
+ * @param expressions bool switch controlling what data to return
+ (false == locals / true == expression)
+ *
+ */
+StackValueCollection* interpretedVFrame::stack_data(bool expressions) const {
+
InterpreterOopMap oop_mask;
+ // oopmap for current bci
if (TraceDeoptimization && Verbose) {
- // need the current JavaThread and not thread()
methodHandle m_h(Thread::current(), method());
OopMapCache::compute_one_oop_map(m_h, bci(), &oop_mask);
} else {
method()->mask_for(bci(), &oop_mask);
}
- // handle locals
- for(int i=0; i < length; i++) {
- // Find stack location
- intptr_t *addr = locals_addr_at(i);
+
+ const int mask_len = oop_mask.number_of_entries();
+
+ // If the method is native, method()->max_locals() is not telling the truth.
+ // For our purposes, max locals instead equals the size of parameters.
+ const int max_locals = method()->is_native() ?
+ method()->size_of_parameters() : method()->max_locals();
+
+ assert(mask_len >= max_locals, "invariant");
+
+ const int length = expressions ? mask_len - max_locals : max_locals;
+ assert(length >= 0, "invariant");
- // Depending on oop/int put it in the right package
- StackValue *sv;
- if (oop_mask.is_oop(i)) {
- // oop value
- Handle h(*(oop *)addr);
- sv = new StackValue(h);
- } else {
- // integer
- sv = new StackValue(*addr);
- }
- assert(sv != NULL, "sanity check");
- result->add(sv);
+ StackValueCollection* const result = new StackValueCollection(length);
+
+ if (0 == length) {
+ return result;
}
+
+ if (expressions) {
+ stack_expressions(result, length, max_locals, oop_mask, fr());
+ } else {
+ stack_locals(result, length, oop_mask, fr());
+ }
+
+ assert(length == result->size(), "invariant");
+
return result;
}
void interpretedVFrame::set_locals(StackValueCollection* values) const {
if (values == NULL || values->size() == 0) return;
- int length = method()->max_locals();
- if (method()->is_native()) {
- // If the method is native, max_locals is not telling the truth.
- // maxlocals then equals the size of parameters
- length = method()->size_of_parameters();
- }
+ // If the method is native, max_locals is not telling the truth.
+ // maxlocals then equals the size of parameters
+ const int max_locals = method()->is_native() ?
+ method()->size_of_parameters() : method()->max_locals();
- assert(length == values->size(), "Mismatch between actual stack format and supplied data");
+ assert(max_locals == values->size(), "Mismatch between actual stack format and supplied data");
// handle locals
- for (int i = 0; i < length; i++) {
+ for (int i = 0; i < max_locals; i++) {
// Find stack location
intptr_t *addr = locals_addr_at(i);
// Depending on oop/int put it in the right package
- StackValue *sv = values->at(i);
+ const StackValue* const sv = values->at(i);
assert(sv != NULL, "sanity check");
if (sv->type() == T_OBJECT) {
*(oop *) addr = (sv->get_obj())();
@@ -329,61 +419,6 @@
}
}
-StackValueCollection* interpretedVFrame::expressions() const {
-
- InterpreterOopMap oop_mask;
-
- if (!method()->is_native()) {
- // Get oopmap describing oops and int for current bci
- if (TraceDeoptimization && Verbose) {
- // need the current JavaThread and not thread()
- methodHandle m_h(Thread::current(), method());
- OopMapCache::compute_one_oop_map(m_h, bci(), &oop_mask);
- } else {
- method()->mask_for(bci(), &oop_mask);
- }
- }
-
- // If the bci is a call instruction, i.e. any of the invoke* instructions,
- // the InterpreterOopMap does not include expression/operand stack liveness
- // info in the oop_mask/bit_mask. This can lead to a discrepancy of what
- // is actually on the expression stack compared to what is given by the
- // oop_map. We need to use the length reported in the oop_map.
- int length = oop_mask.expression_stack_size();
-
- assert(fr().interpreter_frame_expression_stack_size() >= length,
- "error in expression stack!");
-
- StackValueCollection* result = new StackValueCollection(length);
-
- if (0 == length) {
- return result;
- }
-
- int nof_locals = method()->max_locals();
-
- // handle expressions
- for(int i=0; i < length; i++) {
- // Find stack location
- intptr_t *addr = fr().interpreter_frame_expression_stack_at(i);
-
- // Depending on oop/int put it in the right package
- StackValue *sv;
- if (oop_mask.is_oop(i + nof_locals)) {
- // oop value
- Handle h(*(oop *)addr);
- sv = new StackValue(h);
- } else {
- // integer
- sv = new StackValue(*addr);
- }
- assert(sv != NULL, "sanity check");
- result->add(sv);
- }
- return result;
-}
-
-
// ------------- cChunk --------------
entryVFrame::entryVFrame(const frame* fr, const RegisterMap* reg_map, JavaThread* thread)
--- a/hotspot/src/share/vm/runtime/vframe.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vframe.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -186,7 +186,7 @@
private:
static const int bcp_offset;
intptr_t* locals_addr_at(int offset) const;
-
+ StackValueCollection* stack_data(bool expressions) const;
// returns where the parameters starts relative to the frame pointer
int start_of_parameters() const;
--- a/hotspot/src/share/vm/runtime/virtualspace.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/runtime/virtualspace.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -27,21 +27,6 @@
#include "oops/oop.inline.hpp"
#include "runtime/virtualspace.hpp"
#include "services/memTracker.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
--- a/hotspot/src/share/vm/services/heapDumper.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/services/heapDumper.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -33,6 +33,7 @@
#include "oops/objArrayKlass.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jniHandles.hpp"
+#include "runtime/os.hpp"
#include "runtime/reflectionUtils.hpp"
#include "runtime/vframe.hpp"
#include "runtime/vmThread.hpp"
--- a/hotspot/src/share/vm/services/memTracker.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/services/memTracker.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -484,7 +484,7 @@
// as short sleep.
os::naked_short_sleep(1);
#else
- os::NakedYield();
+ os::naked_yield();
#endif
}
}
--- a/hotspot/src/share/vm/services/memoryService.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/services/memoryService.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -136,7 +136,6 @@
break;
#if INCLUDE_ALL_GCS
case Generation::ParNew:
- case Generation::ASParNew:
_minor_gc_manager = MemoryManager::get_parnew_memory_manager();
break;
#endif // INCLUDE_ALL_GCS
@@ -268,7 +267,6 @@
#if INCLUDE_ALL_GCS
case Generation::ParNew:
- case Generation::ASParNew:
{
assert(major_mgr != NULL && minor_mgr != NULL, "Should have two managers");
// Add a memory pool for each space and young gen doesn't
@@ -300,7 +298,6 @@
#if INCLUDE_ALL_GCS
case Generation::ConcurrentMarkSweep:
- case Generation::ASConcurrentMarkSweep:
{
assert(major_mgr != NULL && minor_mgr == NULL, "Should have only one manager");
ConcurrentMarkSweepGeneration* cms = (ConcurrentMarkSweepGeneration*) gen;
@@ -548,23 +545,20 @@
// GC manager type depends on the type of Generation. Depending on the space
// availablity and vm options the gc uses major gc manager or minor gc
// manager or both. The type of gc manager depends on the generation kind.
-// For DefNew, ParNew and ASParNew generation doing scavenge gc uses minor
-// gc manager (so _fullGC is set to false ) and for other generation kinds
-// doing mark-sweep-compact uses major gc manager (so _fullGC is set
-// to true).
+// For DefNew and ParNew generation doing scavenge gc uses minor gc manager (so
+// _fullGC is set to false ) and for other generation kinds doing
+// mark-sweep-compact uses major gc manager (so _fullGC is set to true).
TraceMemoryManagerStats::TraceMemoryManagerStats(Generation::Name kind, GCCause::Cause cause) {
switch (kind) {
case Generation::DefNew:
#if INCLUDE_ALL_GCS
case Generation::ParNew:
- case Generation::ASParNew:
#endif // INCLUDE_ALL_GCS
_fullGC=false;
break;
case Generation::MarkSweepCompact:
#if INCLUDE_ALL_GCS
case Generation::ConcurrentMarkSweep:
- case Generation::ASConcurrentMarkSweep:
#endif // INCLUDE_ALL_GCS
_fullGC=true;
break;
--- a/hotspot/src/share/vm/utilities/accessFlags.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/accessFlags.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,22 +26,6 @@
#include "oops/oop.inline.hpp"
#include "runtime/atomic.inline.hpp"
#include "utilities/accessFlags.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
-
void AccessFlags::atomic_set_bits(jint bits) {
// Atomically update the flags with the bits given
--- a/hotspot/src/share/vm/utilities/array.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/array.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -305,6 +305,7 @@
friend class MetadataFactory;
friend class VMStructs;
friend class MethodHandleCompiler; // special case
+ friend class WhiteBox;
protected:
int _length; // the number of array elements
T _data[1]; // the array memory
@@ -326,6 +327,31 @@
static size_t byte_sizeof(int length) { return sizeof(Array<T>) + MAX2(length - 1, 0) * sizeof(T); }
+ // WhiteBox API helper.
+ // Can't distinguish between array of length 0 and length 1,
+ // will always return 0 in those cases.
+ static int bytes_to_length(size_t bytes) {
+ assert(is_size_aligned(bytes, BytesPerWord), "Must be, for now");
+
+ if (sizeof(Array<T>) >= bytes) {
+ return 0;
+ }
+
+ size_t left = bytes - sizeof(Array<T>);
+ assert(is_size_aligned(left, sizeof(T)), "Must be");
+
+ size_t elements = left / sizeof(T);
+ assert(elements <= (size_t)INT_MAX, err_msg("number of elements " SIZE_FORMAT "doesn't fit into an int.", elements));
+
+ int length = (int)elements;
+
+ assert((size_t)size(length) * BytesPerWord == bytes,
+ err_msg("Expected: " SIZE_FORMAT " got: " SIZE_FORMAT,
+ bytes, (size_t)size(length) * BytesPerWord));
+
+ return length;
+ }
+
explicit Array(int length) : _length(length) {
assert(length >= 0, "illegal length");
}
--- a/hotspot/src/share/vm/utilities/bitMap.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/bitMap.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -28,22 +28,6 @@
#include "runtime/atomic.inline.hpp"
#include "utilities/bitMap.inline.hpp"
#include "utilities/copy.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
-
BitMap::BitMap(bm_word_t* map, idx_t size_in_bits) :
_map(map), _size(size_in_bits), _map_allocator(false)
--- a/hotspot/src/share/vm/utilities/debug.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/debug.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -42,6 +42,7 @@
#include "runtime/atomic.inline.hpp"
#include "runtime/frame.hpp"
#include "runtime/java.hpp"
+#include "runtime/os.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "runtime/stubRoutines.hpp"
@@ -52,18 +53,6 @@
#include "utilities/events.hpp"
#include "utilities/top.hpp"
#include "utilities/vmError.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
#ifndef ASSERT
# ifdef _DEBUG
--- a/hotspot/src/share/vm/utilities/events.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/events.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -25,6 +25,7 @@
#include "precompiled.hpp"
#include "memory/allocation.inline.hpp"
#include "runtime/mutexLocker.hpp"
+#include "runtime/os.inline.hpp"
#include "runtime/osThread.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadCritical.hpp"
--- a/hotspot/src/share/vm/utilities/histogram.hpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/histogram.hpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,21 +28,6 @@
#include "memory/allocation.hpp"
#include "runtime/os.hpp"
#include "utilities/growableArray.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
// This class provides a framework for collecting various statistics.
// The current implementation is oriented towards counting invocations
--- a/hotspot/src/share/vm/utilities/ostream.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/ostream.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -27,25 +27,11 @@
#include "gc_implementation/shared/gcId.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/arguments.hpp"
+#include "runtime/os.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/ostream.hpp"
#include "utilities/top.hpp"
#include "utilities/xmlstream.hpp"
-#ifdef TARGET_OS_FAMILY_linux
-# include "os_linux.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_solaris
-# include "os_solaris.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_windows
-# include "os_windows.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_aix
-# include "os_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_bsd
-# include "os_bsd.inline.hpp"
-#endif
extern "C" void jio_print(const char* s); // Declarationtion of jvm method
--- a/hotspot/src/share/vm/utilities/taskqueue.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/taskqueue.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -142,7 +142,7 @@
void ParallelTaskTerminator::yield() {
assert(_offered_termination <= _n_threads, "Invariant");
- os::yield();
+ os::naked_yield();
}
void ParallelTaskTerminator::sleep(uint millis) {
--- a/hotspot/src/share/vm/utilities/vmError.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/src/share/vm/utilities/vmError.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -989,7 +989,6 @@
if (fd != -1) {
out.print_raw("# An error report file with more information is saved as:\n# ");
out.print_raw_cr(buffer);
- os::set_error_file(buffer);
log.set_fd(fd);
} else {
--- a/hotspot/test/compiler/6775880/Test.java Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/test/compiler/6775880/Test.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,6 @@
* @test
* @bug 6775880
* @summary EA +DeoptimizeALot: assert(mon_info->owner()->is_locked(),"object must be locked now")
- * @compile -source 1.4 -target 1.4 Test.java
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -Xbatch -XX:+DoEscapeAnalysis -XX:+DeoptimizeALot -XX:CompileCommand=exclude,java.lang.AbstractStringBuilder::append Test
*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/gc/g1/TestDeferredRSUpdate.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test TestDeferredRSUpdate
+ * @bug 8040977
+ * @summary Ensure that running with -XX:-G1DeferredRSUpdate does not crash the VM
+ * @key gc
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.ProcessTools;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+public class TestDeferredRSUpdate {
+ public static void main(String[] args) throws Exception {
+ GCTest.main(args);
+
+ ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC",
+ "-Xmx10M",
+ // G1DeferredRSUpdate is a develop option, but we cannot limit execution of this test to only debug VMs.
+ "-XX:+IgnoreUnrecognizedVMOptions",
+ "-XX:-G1DeferredRSUpdate",
+ GCTest.class.getName());
+
+ OutputAnalyzer output = new OutputAnalyzer(pb.start());
+ output.shouldHaveExitValue(0);
+ }
+
+ static class GCTest {
+ private static Object[] garbage = new Object[32];
+
+ public static void main(String [] args) {
+ System.out.println("Creating garbage");
+ // Create 128MB of garbage. This should result in at least one minor GC, with
+ // some objects copied to old gen. As references from old to young are installed,
+ // the crash due to the use before initialize occurs.
+ Object prev = null;
+ Object prevPrev = null;
+ for (int i = 0; i < 1024; i++) {
+ Object[] next = new Object[32 * 1024];
+ next[0] = prev;
+ next[1] = prevPrev;
+
+ Object[] cur = (Object[]) garbage[i % garbage.length];
+ if (cur != null) {
+ cur[0] = null;
+ cur[1] = null;
+ }
+ garbage[i % garbage.length] = next;
+
+ prevPrev = prev;
+ prev = next;
+ }
+ System.out.println("Done");
+ }
+ }
+}
--- a/hotspot/test/runtime/6626217/Test6626217.sh Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/test/runtime/6626217/Test6626217.sh Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -54,7 +54,7 @@
# Compile all the usual suspects, including the default 'many_loader'
${CP} many_loader1.java.foo many_loader.java
-${JAVAC} ${TESTJAVACOPTS} -source 1.4 -target 1.4 -Xlint *.java
+${JAVAC} ${TESTJAVACOPTS} -Xlint *.java
# Rename the class files, so the custom loader (and not the system loader) will find it
${MV} from_loader2.class from_loader2.impl2
@@ -62,7 +62,7 @@
# Compile the next version of 'many_loader'
${MV} many_loader.class many_loader.impl1
${CP} many_loader2.java.foo many_loader.java
-${JAVAC} ${TESTJAVACOPTS} -source 1.4 -target 1.4 -Xlint many_loader.java
+${JAVAC} ${TESTJAVACOPTS} -Xlint many_loader.java
# Rename the class file, so the custom loader (and not the system loader) will find it
${MV} many_loader.class many_loader.impl2
--- a/hotspot/test/runtime/8003720/Test8003720.java Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/test/runtime/8003720/Test8003720.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
* @test
* @bug 8003720
* @summary Method in interpreter stack frame can be deallocated
- * @compile -XDignore.symbol.file -source 1.7 -target 1.7 Victim.java
+ * @compile -XDignore.symbol.file Victim.java
* @run main/othervm -Xverify:all -Xint Test8003720
*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/verifier/OverriderMsg.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.File;
+import java.io.FileOutputStream;
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.MethodVisitor;
+import static jdk.internal.org.objectweb.asm.Opcodes.*;
+import com.oracle.java.testlibrary.*;
+
+/*
+ * @test OverriderMsg
+ * @bug 8026894
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file OverriderMsg.java
+ * @run main/othervm OverriderMsg
+ */
+
+// This test checks that the super class name is included in the message when
+// a method is detected overriding a final method in its super class. The
+// asm part of the test creates these two classes:
+//
+// public class HasFinal {
+// public final void m(String s) { }
+// }
+//
+// public class Overrider extends HasFinal {
+// public void m(String s) { }
+// public static void main(String[] args) { }
+// }
+//
+public class OverriderMsg {
+
+ public static void dump_HasFinal () throws Exception {
+
+ ClassWriter cw = new ClassWriter(0);
+ MethodVisitor mv;
+
+ cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "HasFinal", null, "java/lang/Object", null);
+
+ {
+ mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(1, 1);
+ mv.visitEnd();
+ }
+ {
+ mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "m", "(Ljava/lang/String;)V", null, null);
+ mv.visitCode();
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(0, 2);
+ mv.visitEnd();
+ }
+ cw.visitEnd();
+ try (FileOutputStream fos = new FileOutputStream(new File("HasFinal.class"))) {
+ fos.write(cw.toByteArray());
+ }
+ }
+
+
+ public static void dump_Overrider () throws Exception {
+
+ ClassWriter cw = new ClassWriter(0);
+ MethodVisitor mv;
+ cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "Overrider", null, "HasFinal", null);
+
+ {
+ mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitMethodInsn(INVOKESPECIAL, "HasFinal", "<init>", "()V");
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(1, 1);
+ mv.visitEnd();
+ }
+ {
+ mv = cw.visitMethod(ACC_PUBLIC, "m", "(Ljava/lang/String;)V", null, null);
+ mv.visitCode();
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(0, 2);
+ mv.visitEnd();
+ }
+ {
+ mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
+ mv.visitCode();
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(0, 1);
+ mv.visitEnd();
+ }
+ cw.visitEnd();
+
+ try (FileOutputStream fos = new FileOutputStream(new File("Overrider.class"))) {
+ fos.write(cw.toByteArray());
+ }
+ }
+
+
+ public static void main(String... args) throws Exception {
+ dump_HasFinal();
+ dump_Overrider();
+ ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, "-cp", ".", "Overrider");
+ OutputAnalyzer output = new OutputAnalyzer(pb.start());
+ output.shouldContain(
+ "java.lang.VerifyError: class Overrider overrides final method HasFinal.m(Ljava/lang/String;)V");
+ output.shouldHaveExitValue(1);
+ }
+
+}
--- a/hotspot/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java Thu Jul 17 09:50:06 2014 -0700
+++ b/hotspot/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java Wed Jul 05 19:50:57 2017 +0200
@@ -142,6 +142,8 @@
// Memory
public native void readReservedMemory();
+ public native long allocateMetaspace(ClassLoader classLoader, long size);
+ public native void freeMetaspace(ClassLoader classLoader, long addr, long size);
// force Full GC
public native void fullGC();
--- a/jdk/.hgtags Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/.hgtags Wed Jul 05 19:50:57 2017 +0200
@@ -265,3 +265,4 @@
f87c5be90e01a7ffb47947108eb3e0b0b1920880 jdk9-b20
2df45ac1bf491278f38c12e0dfbeebadb6c54c8c jdk9-b21
85bcf0f99edc08873614afbe5a5563e13ce13c83 jdk9-b22
+9febf9dbc0a4b15323f2dbd29931cfbf086332b4 jdk9-b23
--- a/jdk/make/lib/Awt2dLibraries.gmk Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/make/lib/Awt2dLibraries.gmk Wed Jul 05 19:50:57 2017 +0200
@@ -1358,7 +1358,7 @@
ifeq ($(OPENJDK_TARGET_OS), macosx)
LIBAWT_LWAWT_FILES := \
- awt.m \
+ AWT_debug.m \
ApplicationDelegate.m \
CFRetainedResource.m \
CGLGraphicsConfig.m \
--- a/jdk/make/mapfiles/libsplashscreen/mapfile-vers Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/make/mapfiles/libsplashscreen/mapfile-vers Wed Jul 05 19:50:57 2017 +0200
@@ -35,6 +35,7 @@
Java_java_awt_SplashScreen__1getImageFileName;
Java_java_awt_SplashScreen__1getImageJarName;
Java_java_awt_SplashScreen__1setImageData;
+ Java_java_awt_SplashScreen__1getScaleFactor;
SplashLoadMemory;
SplashLoadFile;
--- a/jdk/make/mapfiles/libsunec/mapfile-vers Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/make/mapfiles/libsunec/mapfile-vers Wed Jul 05 19:50:57 2017 +0200
@@ -28,10 +28,9 @@
SUNWprivate_1.1 {
global:
Java_sun_security_ec_ECKeyPairGenerator_generateECKeyPair;
- Java_sun_security_ec_ECKeyPairGenerator_getEncodedBytes;
- Java_sun_security_ec_ECDSASignature_signDigest;
- Java_sun_security_ec_ECDSASignature_verifySignedDigest;
- Java_sun_security_ec_ECDHKeyAgreement_deriveKey;
+ Java_sun_security_ec_ECDSASignature_signDigest;
+ Java_sun_security_ec_ECDSASignature_verifySignedDigest;
+ Java_sun_security_ec_ECDHKeyAgreement_deriveKey;
local:
*;
};
--- a/jdk/make/profile-includes.txt Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/make/profile-includes.txt Wed Jul 05 19:50:57 2017 +0200
@@ -71,6 +71,7 @@
rt.jar \
security/US_export_policy.jar \
security/blacklist \
+ security/blacklisted.certs \
security/cacerts \
security/java.policy \
security/java.security \
--- a/jdk/src/macosx/bin/java_md_macosx.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/bin/java_md_macosx.c Wed Jul 05 19:50:57 2017 +0200
@@ -994,7 +994,7 @@
sameThread = JNI_TRUE;
// Set a variable that tells us we started on the main thread.
- // This is used by the AWT during startup. (See awt.m)
+ // This is used by the AWT during startup. (See LWCToolkit.m)
char envVar[80];
snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
setenv(envVar, "1", 1);
--- a/jdk/src/macosx/classes/com/apple/eawt/Application.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/eawt/Application.java Wed Jul 05 19:50:57 2017 +0200
@@ -58,15 +58,8 @@
static Application sApplication = null;
static {
- java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction<Void>() {
- public Void run() {
- System.loadLibrary("awt");
- return null;
- }
- });
-
checkSecurity();
+ Toolkit.getDefaultToolkit(); // Start AppKit
if (!Beans.isDesignTime()) {
nativeInitializeApplicationDelegate();
}
--- a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java Wed Jul 05 19:50:57 2017 +0200
@@ -121,10 +121,6 @@
public void show() {
final int startItemCount = comboBox.getItemCount();
- if (startItemCount == 0) {
- return;
- }
-
final Rectangle popupBounds = adjustPopupAndGetBounds();
if (popupBounds == null) return; // null means don't show
--- a/jdk/src/macosx/classes/com/apple/laf/AquaMenuBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaMenuBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -26,11 +26,14 @@
package com.apple.laf;
import java.awt.*;
+import java.security.AccessController;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicMenuBarUI;
+import sun.lwawt.macosx.LWCToolkit;
+import sun.security.action.GetBooleanAction;
import sun.security.action.GetPropertyAction;
// MenuBar implementation for Mac L&F
@@ -131,28 +134,20 @@
ScreenMenuBar fScreenMenuBar;
boolean useScreenMenuBar = getScreenMenuBarProperty();
- private static String getPrivSysProp(final String propName) {
- return java.security.AccessController.doPrivileged(new GetPropertyAction(propName));
- }
-
static boolean getScreenMenuBarProperty() {
- final String props[] = new String[]{""};
-
- boolean useScreenMenuBar = false;
- try {
- props[0] = getPrivSysProp(AquaLookAndFeel.sPropertyPrefix + "useScreenMenuBar");
-
- if (props[0] != null && props[0].equals("true")) useScreenMenuBar = true;
- else {
- props[0] = getPrivSysProp(AquaLookAndFeel.sOldPropertyPrefix + "useScreenMenuBar");
-
- if (props[0] != null && props[0].equals("true")) {
- System.err.println(AquaLookAndFeel.sOldPropertyPrefix + "useScreenMenuBar has been deprecated. Please switch to " + AquaLookAndFeel.sPropertyPrefix + "useScreenMenuBar");
- useScreenMenuBar = true;
- }
- }
- } catch(final Throwable t) { };
-
- return useScreenMenuBar;
+ // Do not allow AWT to set the screen menu bar if it's embedded in another UI toolkit
+ if (LWCToolkit.isEmbedded()) return false;
+ if (AccessController.doPrivileged(
+ new GetBooleanAction(AquaLookAndFeel.sPropertyPrefix + "useScreenMenuBar"))) {
+ return true;
+ }
+ if (AccessController.doPrivileged(
+ new GetBooleanAction(AquaLookAndFeel.sOldPropertyPrefix + "useScreenMenuBar"))) {
+ System.err.println(AquaLookAndFeel.sOldPropertyPrefix +
+ "useScreenMenuBar has been deprecated. Please switch to " +
+ AquaLookAndFeel.sPropertyPrefix + "useScreenMenuBar");
+ return true;
+ }
+ return false;
}
}
--- a/jdk/src/macosx/classes/sun/awt/CGraphicsEnvironment.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/classes/sun/awt/CGraphicsEnvironment.java Wed Jul 05 19:50:57 2017 +0200
@@ -40,9 +40,6 @@
*/
public final class CGraphicsEnvironment extends SunGraphicsEnvironment {
- // Global initialization of the Cocoa runtime.
- private static native void initCocoa();
-
/**
* Fetch an array of all valid CoreGraphics display identifiers.
*/
@@ -60,21 +57,8 @@
public static void init() { }
static {
- java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
- public Void run() {
- System.loadLibrary("awt");
- return null;
- }
- });
-
- java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
- public Void run() {
- if (isHeadless()) return null;
- initCocoa();
- return null;
- }
- });
-
+ // Load libraries and initialize the Toolkit.
+ Toolkit.getDefaultToolkit();
// Install the correct surface manager factory.
SurfaceManagerFactory.setInstance(new MacosxSurfaceManagerFactory());
}
--- a/jdk/src/macosx/classes/sun/font/CFontConfiguration.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/classes/sun/font/CFontConfiguration.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -106,6 +106,6 @@
@Override
protected void initReorderMap() {
- reorderMap = new HashMap();
+ reorderMap = new HashMap<>();
}
}
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java Wed Jul 05 19:50:57 2017 +0200
@@ -44,6 +44,7 @@
import sun.awt.*;
import sun.awt.datatransfer.DataTransferer;
+import sun.awt.util.ThreadGroupUtils;
import sun.java2d.opengl.OGLRenderQueue;
import sun.lwawt.*;
import sun.lwawt.LWWindowPeer.PeerType;
@@ -70,7 +71,7 @@
private static final int BUTTONS = 5;
private static native void initIDs();
-
+ private static native void initAppkit(ThreadGroup appKitThreadGroup, boolean headless);
private static CInputMethodDescriptor sInputMethodDescriptor;
static {
@@ -119,6 +120,7 @@
areExtraMouseButtonsEnabled = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons", "true"));
//set system property if not yet assigned
System.setProperty("sun.awt.enableExtraMouseButtons", ""+areExtraMouseButtonsEnabled);
+ initAppkit(ThreadGroupUtils.getRootThreadGroup(), GraphicsEnvironment.isHeadless());
}
/*
@@ -166,7 +168,7 @@
// This is only called from native code.
static void systemColorsChanged() {
EventQueue.invokeLater(() -> {
- AccessController.doPrivileged ((PrivilegedAction<Object>) () -> {
+ AccessController.doPrivileged( (PrivilegedAction<Object>) () -> {
AWTAccessor.getSystemColorAccessor().updateSystemColors();
return null;
});
@@ -790,6 +792,13 @@
*/
native boolean isApplicationActive();
+ /**
+ * Returns true if AWT toolkit is embedded, false otherwise.
+ *
+ * @return true if AWT toolkit is embedded, false otherwise
+ */
+ public static native boolean isEmbedded();
+
/************************
* Native methods section
************************/
--- a/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m Wed Jul 05 19:50:57 2017 +0200
@@ -30,24 +30,6 @@
#import "AWT_debug.h"
-/*
- * Class: sun_awt_CGraphicsEnvironment
- * Method: initCocoa
- * Signature: ()V
- */
-JNIEXPORT void JNICALL
-Java_sun_awt_CGraphicsEnvironment_initCocoa
-(JNIEnv *env, jclass self)
-{
-JNF_COCOA_ENTER(env);
-
- // Inform Cocoa that we're multi-threaded.
- // Creating a short-lived NSThread is the recommended way of doing so.
- [NSThread detachNewThreadSelector:@selector(self) toTarget:[NSObject class] withObject:nil];
-
-JNF_COCOA_EXIT(env);
-}
-
#define MAX_DISPLAYS 64
/*
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m Wed Jul 05 19:50:57 2017 +0200
@@ -24,7 +24,12 @@
*/
#import <dlfcn.h>
+#import <pthread.h>
+#import <objc/runtime.h>
+#import <Cocoa/Cocoa.h>
+#import <Security/AuthSession.h>
#import <JavaNativeFoundation/JavaNativeFoundation.h>
+#import <JavaRuntimeSupport/JavaRuntimeSupport.h>
#include "jni_util.h"
#import "CMenuBar.h"
@@ -34,6 +39,8 @@
#import "AWT_debug.h"
#import "CSystemColors.h"
#import "NSApplicationAWT.h"
+#import "PropertiesUtilities.h"
+#import "ApplicationDelegate.h"
#import "sun_lwawt_macosx_LWCToolkit.h"
@@ -42,6 +49,20 @@
int gNumberOfButtons;
jint* gButtonDownMasks;
+// Indicates that the app has been started with -XstartOnFirstThread
+// (directly or via WebStart settings), and AWT should not run its
+// own event loop in this mode. Even if a loop isn't running yet,
+// we expect an embedder (e.g. SWT) to start it some time later.
+static BOOL forceEmbeddedMode = NO;
+
+// Indicates if awt toolkit is embedded into another UI toolkit
+static BOOL isEmbedded = NO;
+
+// This is the data necessary to have JNI_OnLoad wait for AppKit to start.
+static BOOL sAppKitStarted = NO;
+static pthread_mutex_t sAppKitStarted_mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t sAppKitStarted_cv = PTHREAD_COND_INITIALIZER;
+
@implementation AWTToolkit
static long eventCount;
@@ -115,6 +136,232 @@
}
@end
+void setBusy(BOOL busy) {
+ AWT_ASSERT_APPKIT_THREAD;
+
+ JNIEnv *env = [ThreadUtilities getJNIEnv];
+ static JNF_CLASS_CACHE(jc_AWTAutoShutdown, "sun/awt/AWTAutoShutdown");
+
+ if (busy) {
+ static JNF_STATIC_MEMBER_CACHE(jm_notifyBusyMethod, jc_AWTAutoShutdown, "notifyToolkitThreadBusy", "()V");
+ JNFCallStaticVoidMethod(env, jm_notifyBusyMethod);
+ } else {
+ static JNF_STATIC_MEMBER_CACHE(jm_notifyFreeMethod, jc_AWTAutoShutdown, "notifyToolkitThreadFree", "()V");
+ JNFCallStaticVoidMethod(env, jm_notifyFreeMethod);
+ }
+}
+
+static void setUpAWTAppKit(BOOL installObservers)
+{
+ if (installObservers) {
+ AWT_STARTUP_LOG(@"Setting up busy observers");
+
+ // Add CFRunLoopObservers to call into AWT so that AWT knows that the
+ // AWT thread (which is the AppKit main thread) is alive. This way AWT
+ // will not automatically shutdown.
+ CFRunLoopObserverRef busyObserver = CFRunLoopObserverCreateWithHandler(
+ NULL, // CFAllocator
+ kCFRunLoopAfterWaiting, // CFOptionFlags
+ true, // repeats
+ NSIntegerMax, // order
+ ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
+ setBusy(YES);
+ });
+
+ CFRunLoopObserverRef notBusyObserver = CFRunLoopObserverCreateWithHandler(
+ NULL, // CFAllocator
+ kCFRunLoopBeforeWaiting, // CFOptionFlags
+ true, // repeats
+ NSIntegerMin, // order
+ ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
+ setBusy(NO);
+ });
+
+ CFRunLoopRef runLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
+ CFRunLoopAddObserver(runLoop, busyObserver, kCFRunLoopDefaultMode);
+ CFRunLoopAddObserver(runLoop, notBusyObserver, kCFRunLoopDefaultMode);
+
+ CFRelease(busyObserver);
+ CFRelease(notBusyObserver);
+
+ setBusy(YES);
+ }
+
+ JNIEnv* env = [ThreadUtilities getJNIEnv];
+ static JNF_CLASS_CACHE(jc_LWCToolkit, "sun/lwawt/macosx/LWCToolkit");
+ static JNF_STATIC_MEMBER_CACHE(jsm_installToolkitThreadInJava, jc_LWCToolkit, "installToolkitThreadInJava", "()V");
+ JNFCallStaticVoidMethod(env, jsm_installToolkitThreadInJava);
+}
+
+BOOL isSWTInWebStart(JNIEnv* env) {
+ NSString *swtWebStart = [PropertiesUtilities javaSystemPropertyForKey:@"com.apple.javaws.usingSWT" withEnv:env];
+ return [@"true" isCaseInsensitiveLike:swtWebStart];
+}
+
+static void AWT_NSUncaughtExceptionHandler(NSException *exception) {
+ NSLog(@"Apple AWT Internal Exception: %@", [exception description]);
+}
+
+@interface AWTStarter : NSObject
++ (void)start:(BOOL)headless;
++ (void)starter:(BOOL)onMainThread headless:(BOOL)headless;
++ (void)appKitIsRunning:(id)arg;
+@end
+
+@implementation AWTStarter
+
++ (BOOL) isConnectedToWindowServer {
+ SecuritySessionId session_id;
+ SessionAttributeBits session_info;
+ OSStatus status = SessionGetInfo(callerSecuritySession, &session_id, &session_info);
+ if (status != noErr) return NO;
+ if (!(session_info & sessionHasGraphicAccess)) return NO;
+ return YES;
+}
+
++ (BOOL) markAppAsDaemon {
+ id jrsAppKitAWTClass = objc_getClass("JRSAppKitAWT");
+ SEL markAppSel = @selector(markAppIsDaemon);
+ if (![jrsAppKitAWTClass respondsToSelector:markAppSel]) return NO;
+ return [jrsAppKitAWTClass performSelector:markAppSel] ? YES : NO;
+}
+
++ (void)appKitIsRunning:(id)arg {
+ AWT_ASSERT_APPKIT_THREAD;
+ AWT_STARTUP_LOG(@"About to message AppKit started");
+
+ // Signal that AppKit has started (or is already running).
+ pthread_mutex_lock(&sAppKitStarted_mutex);
+ sAppKitStarted = YES;
+ pthread_cond_signal(&sAppKitStarted_cv);
+ pthread_mutex_unlock(&sAppKitStarted_mutex);
+
+ AWT_STARTUP_LOG(@"Finished messaging AppKit started");
+}
+
++ (void)start:(BOOL)headless
+{
+ // onMainThread is NOT the same at SWT mode!
+ // If the JVM was started on the first thread for SWT, but the SWT loads the AWT on a secondary thread,
+ // onMainThread here will be false but SWT mode will be true. If we are currently on the main thread, we don't
+ // need to throw AWT startup over to another thread.
+ BOOL onMainThread = [NSThread isMainThread];
+
+ NSString* msg = [NSString stringWithFormat:@"+[AWTStarter start headless:%d] { onMainThread:%d }", headless, onMainThread];
+ AWT_STARTUP_LOG(msg);
+
+ if (!headless)
+ {
+ // Listen for the NSApp to start. This indicates that JNI_OnLoad can proceed.
+ // It must wait because there is a chance that another java thread will grab
+ // the AppKit lock before the +[NSApplication sharedApplication] returns.
+ // See <rdar://problem/3492666> for an example.
+ [[NSNotificationCenter defaultCenter] addObserver:[AWTStarter class]
+ selector:@selector(appKitIsRunning:)
+ name:NSApplicationDidFinishLaunchingNotification
+ object:nil];
+
+ AWT_STARTUP_LOG(@"+[AWTStarter start:::]: registered NSApplicationDidFinishLaunchingNotification");
+ }
+
+ [ThreadUtilities performOnMainThreadWaiting:NO block:^() {
+ [AWTStarter starter:onMainThread headless:headless];
+ }];
+
+
+ if (!headless && !onMainThread) {
+
+ AWT_STARTUP_LOG(@"about to wait on AppKit startup mutex");
+
+ // Wait here for AppKit to have started (or for AWT to have been loaded into
+ // an already running NSApplication).
+ pthread_mutex_lock(&sAppKitStarted_mutex);
+ while (sAppKitStarted == NO) {
+ pthread_cond_wait(&sAppKitStarted_cv, &sAppKitStarted_mutex);
+ }
+ pthread_mutex_unlock(&sAppKitStarted_mutex);
+
+ // AWT gets here AFTER +[AWTStarter appKitIsRunning:] is called.
+ AWT_STARTUP_LOG(@"got out of the AppKit startup mutex");
+ }
+
+ if (!headless) {
+ // Don't set the delegate until the NSApplication has been created and
+ // its finishLaunching has initialized it.
+ // ApplicationDelegate is the support code for com.apple.eawt.
+ [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
+ id<NSApplicationDelegate> delegate = [ApplicationDelegate sharedDelegate];
+ if (delegate != nil) {
+ OSXAPP_SetApplicationDelegate(delegate);
+ }
+ }];
+ }
+}
+
++ (void)starter:(BOOL)wasOnMainThread headless:(BOOL)headless {
+ NSAutoreleasePool *pool = [NSAutoreleasePool new];
+ // Add the exception handler of last resort
+ NSSetUncaughtExceptionHandler(AWT_NSUncaughtExceptionHandler);
+
+ // Headless mode trumps either ordinary AWT or SWT-in-AWT mode. Declare us a daemon and return.
+ if (headless) {
+ // Note that we don't install run loop observers in headless mode
+ // because we don't need them (see 7174704)
+ if (!forceEmbeddedMode) {
+ setUpAWTAppKit(false);
+ }
+ [AWTStarter markAppAsDaemon];
+ return;
+ }
+
+ if (forceEmbeddedMode) {
+ AWT_STARTUP_LOG(@"in SWT or SWT/WebStart mode");
+
+ // Init a default NSApplication instance instead of the NSApplicationAWT.
+ // Note that [NSApp isRunning] will return YES after that, though
+ // this behavior isn't specified anywhere. We rely on that.
+ NSApplicationLoad();
+ }
+
+ // This will create a NSApplicationAWT for standalone AWT programs, unless there is
+ // already a NSApplication instance. If there is already a NSApplication instance,
+ // and -[NSApplication isRunning] returns YES, AWT is embedded inside another
+ // AppKit Application.
+ NSApplication *app = [NSApplicationAWT sharedApplication];
+ isEmbedded = ![NSApp isKindOfClass:[NSApplicationAWT class]];
+
+ if (!isEmbedded) {
+ // Install run loop observers and set the AppKit Java thread name
+ setUpAWTAppKit(true);
+ }
+
+ // AWT gets to this point BEFORE NSApplicationDidFinishLaunchingNotification is sent.
+ if (![app isRunning]) {
+ AWT_STARTUP_LOG(@"+[AWTStarter startAWT]: ![app isRunning]");
+ // This is where the AWT AppKit thread parks itself to process events.
+ [NSApplicationAWT runAWTLoopWithApp: app];
+ } else {
+ // We're either embedded, or showing a splash screen
+ if (isEmbedded) {
+ AWT_STARTUP_LOG(@"running embedded");
+
+ // We don't track if the runloop is busy, so set it free to let AWT finish when it needs
+ setBusy(NO);
+ } else {
+ AWT_STARTUP_LOG(@"running after showing a splash screen");
+ }
+
+ // Signal so that JNI_OnLoad can proceed.
+ if (!wasOnMainThread) [AWTStarter appKitIsRunning:nil];
+
+ // Proceed to exit this call as there is no reason to run the NSApplication event loop.
+ }
+
+ [pool drain];
+}
+
+@end
+
/*
* Class: sun_lwawt_macosx_LWCToolkit
* Method: nativeSyncQueue
@@ -169,52 +416,6 @@
NSBeep(); // produces both sound and visual flash, if configured in System Preferences
}
-/*
- * Class: sun_lwawt_macosx_LWCToolkit
- * Method: initIDs
- * Signature: ()V
- */
-JNIEXPORT void JNICALL
-Java_sun_lwawt_macosx_LWCToolkit_initIDs
-(JNIEnv *env, jclass klass) {
- // set thread names
- if (![ThreadUtilities isAWTEmbedded]) {
- dispatch_async(dispatch_get_main_queue(), ^(void){
- [[NSThread currentThread] setName:@"AppKit Thread"];
- JNIEnv *env = [ThreadUtilities getJNIEnv];
- static JNF_CLASS_CACHE(jc_LWCToolkit, "sun/lwawt/macosx/LWCToolkit");
- static JNF_STATIC_MEMBER_CACHE(jsm_installToolkitThreadInJava, jc_LWCToolkit, "installToolkitThreadInJava", "()V");
- JNFCallStaticVoidMethod(env, jsm_installToolkitThreadInJava);
- });
- }
-
- gNumberOfButtons = sun_lwawt_macosx_LWCToolkit_BUTTONS;
-
- jclass inputEventClazz = (*env)->FindClass(env, "java/awt/event/InputEvent");
- CHECK_NULL(inputEventClazz);
- jmethodID getButtonDownMasksID = (*env)->GetStaticMethodID(env, inputEventClazz, "getButtonDownMasks", "()[I");
- CHECK_NULL(getButtonDownMasksID);
- jintArray obj = (jintArray)(*env)->CallStaticObjectMethod(env, inputEventClazz, getButtonDownMasksID);
- jint * tmp = (*env)->GetIntArrayElements(env, obj, JNI_FALSE);
- CHECK_NULL(tmp);
-
- gButtonDownMasks = (jint*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), gNumberOfButtons);
- if (gButtonDownMasks == NULL) {
- gNumberOfButtons = 0;
- (*env)->ReleaseIntArrayElements(env, obj, tmp, JNI_ABORT);
- JNU_ThrowOutOfMemoryError(env, NULL);
- return;
- }
-
- int i;
- for (i = 0; i < gNumberOfButtons; i++) {
- gButtonDownMasks[i] = tmp[i];
- }
-
- (*env)->ReleaseIntArrayElements(env, obj, tmp, 0);
- (*env)->DeleteLocalRef(env, obj);
-}
-
static UInt32 RGB(NSColor *c) {
c = [c colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
if (c == nil)
@@ -443,3 +644,95 @@
{
}
+
+/*
+ * Class: sun_lwawt_macosx_LWCToolkit
+ * Method: initIDs
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_sun_lwawt_macosx_LWCToolkit_initIDs
+(JNIEnv *env, jclass klass) {
+
+ JNF_COCOA_ENTER(env)
+
+ gNumberOfButtons = sun_lwawt_macosx_LWCToolkit_BUTTONS;
+
+ jclass inputEventClazz = (*env)->FindClass(env, "java/awt/event/InputEvent");
+ CHECK_NULL(inputEventClazz);
+ jmethodID getButtonDownMasksID = (*env)->GetStaticMethodID(env, inputEventClazz, "getButtonDownMasks", "()[I");
+ CHECK_NULL(getButtonDownMasksID);
+ jintArray obj = (jintArray)(*env)->CallStaticObjectMethod(env, inputEventClazz, getButtonDownMasksID);
+ jint * tmp = (*env)->GetIntArrayElements(env, obj, JNI_FALSE);
+ CHECK_NULL(tmp);
+
+ gButtonDownMasks = (jint*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), gNumberOfButtons);
+ if (gButtonDownMasks == NULL) {
+ gNumberOfButtons = 0;
+ (*env)->ReleaseIntArrayElements(env, obj, tmp, JNI_ABORT);
+ JNU_ThrowOutOfMemoryError(env, NULL);
+ return;
+ }
+
+ int i;
+ for (i = 0; i < gNumberOfButtons; i++) {
+ gButtonDownMasks[i] = tmp[i];
+ }
+
+ (*env)->ReleaseIntArrayElements(env, obj, tmp, 0);
+ (*env)->DeleteLocalRef(env, obj);
+
+ JNF_COCOA_EXIT(env)
+}
+
+/*
+ * Class: sun_lwawt_macosx_LWCToolkit
+ * Method: initAppkit
+ * Signature: (Ljava/lang/ThreadGroup;)V
+ */
+JNIEXPORT void JNICALL
+Java_sun_lwawt_macosx_LWCToolkit_initAppkit
+(JNIEnv *env, jclass klass, jobject appkitThreadGroup, jboolean headless) {
+ JNF_COCOA_ENTER(env)
+
+ [ThreadUtilities setAppkitThreadGroup:(*env)->NewGlobalRef(env, appkitThreadGroup)];
+
+ // Launcher sets this env variable if -XstartOnFirstThread is specified
+ char envVar[80];
+ snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
+ if (getenv(envVar) != NULL) {
+ forceEmbeddedMode = YES;
+ unsetenv(envVar);
+ }
+
+ if (isSWTInWebStart(env)) {
+ forceEmbeddedMode = YES;
+ }
+
+ [AWTStarter start:headless ? YES : NO];
+
+ JNF_COCOA_EXIT(env)
+}
+
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
+ OSXAPP_SetJavaVM(vm);
+
+ // We need to let Foundation know that this is a multithreaded application, if it isn't already.
+ if (![NSThread isMultiThreaded]) {
+ [NSThread detachNewThreadSelector:nil toTarget:nil withObject:nil];
+ }
+
+ return JNI_VERSION_1_4;
+}
+
+/*
+ * Class: sun_lwawt_macosx_LWCToolkit
+ * Method: isEmbedded
+ * Signature: ()Z
+ */
+JNIEXPORT jboolean JNICALL
+Java_sun_lwawt_macosx_LWCToolkit_isEmbedded
+(JNIEnv *env, jclass klass) {
+ return isEmbedded ? JNI_TRUE : JNI_FALSE;
+}
+
--- a/jdk/src/macosx/native/sun/awt/awt.m Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,460 +0,0 @@
-/*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-#import <pthread.h>
-#import <objc/runtime.h>
-#import <Cocoa/Cocoa.h>
-#import <Security/AuthSession.h>
-#import <JavaNativeFoundation/JavaNativeFoundation.h>
-#import <JavaRuntimeSupport/JavaRuntimeSupport.h>
-
-#import "NSApplicationAWT.h"
-#import "PropertiesUtilities.h"
-#import "ThreadUtilities.h"
-#import "AWT_debug.h"
-#import "ApplicationDelegate.h"
-
-#define DEBUG 0
-
-
-// The symbol is defined in libosxapp.dylib (ThreadUtilities.m)
-extern JavaVM *jvm;
-
-// Indicates if AWT is running embedded (in SWT, FX, elsewhere)
-static BOOL isEmbedded = NO;
-
-// Indicates that the app has been started with -XstartOnFirstThread
-// (directly or via WebStart settings), and AWT should not run its
-// own event loop in this mode. Even if a loop isn't running yet,
-// we expect an embedder (e.g. SWT) to start it some time later.
-static BOOL forceEmbeddedMode = NO;
-
-static bool ShouldPrintVerboseDebugging() {
- static int debug = -1;
- if (debug == -1) {
- debug = (int)(getenv("JAVA_AWT_VERBOSE") != NULL) || (DEBUG != 0);
- }
- return (bool)debug;
-}
-
-// This is the data necessary to have JNI_OnLoad wait for AppKit to start.
-static BOOL sAppKitStarted = NO;
-static pthread_mutex_t sAppKitStarted_mutex = PTHREAD_MUTEX_INITIALIZER;
-static pthread_cond_t sAppKitStarted_cv = PTHREAD_COND_INITIALIZER;
-
-void setBusy(BOOL isBusy);
-static void BusyObserver(CFRunLoopObserverRef ref, CFRunLoopActivity what, void* arg);
-static void NotBusyObserver(CFRunLoopObserverRef ref, CFRunLoopActivity what, void* arg);
-static void AWT_NSUncaughtExceptionHandler(NSException *exception);
-
-static CFRunLoopObserverRef busyObserver = NULL;
-static CFRunLoopObserverRef notBusyObserver = NULL;
-
-static void setUpAWTAppKit()
-{
- BOOL verbose = ShouldPrintVerboseDebugging();
- if (verbose) AWT_DEBUG_LOG(@"setting up busy observers");
-
- // Add CFRunLoopObservers to call into AWT so that AWT knows that the
- // AWT thread (which is the AppKit main thread) is alive. This way AWT
- // will not automatically shutdown.
- busyObserver = CFRunLoopObserverCreate(
- NULL, // CFAllocator
- kCFRunLoopAfterWaiting, // CFOptionFlags
- true, // repeats
- NSIntegerMax, // order
- &BusyObserver, // CFRunLoopObserverCallBack
- NULL); // CFRunLoopObserverContext
-
- notBusyObserver = CFRunLoopObserverCreate(
- NULL, // CFAllocator
- kCFRunLoopBeforeWaiting, // CFOptionFlags
- true, // repeats
- NSIntegerMin, // order
- &NotBusyObserver, // CFRunLoopObserverCallBack
- NULL); // CFRunLoopObserverContext
-
- CFRunLoopRef runLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
- CFRunLoopAddObserver(runLoop, busyObserver, kCFRunLoopDefaultMode);
- CFRunLoopAddObserver(runLoop, notBusyObserver, kCFRunLoopDefaultMode);
-
- CFRelease(busyObserver);
- CFRelease(notBusyObserver);
-
- setBusy(YES);
-}
-
-static void setUpAppKitThreadName()
-{
- BOOL verbose = ShouldPrintVerboseDebugging();
- JNIEnv *env = [ThreadUtilities getJNIEnv];
-
- // Set the java name of the AppKit main thread appropriately.
- jclass threadClass = NULL;
- jstring name = NULL;
- jobject curThread = NULL;
-
- threadClass = (*env)->FindClass(env, "java/lang/Thread");
- if (threadClass == NULL || (*env)->ExceptionCheck(env)) goto cleanup;
- jmethodID currentThreadID = (*env)->GetStaticMethodID(env, threadClass, "currentThread", "()Ljava/lang/Thread;");
- if (currentThreadID == NULL || (*env)->ExceptionCheck(env)) goto cleanup;
- jmethodID setName = (*env)->GetMethodID(env, threadClass, "setName", "(Ljava/lang/String;)V");
- if (setName == NULL || (*env)->ExceptionCheck(env)) goto cleanup;
-
- curThread = (*env)->CallStaticObjectMethod(env, threadClass, currentThreadID); // AWT_THREADING Safe (known object)
- if (curThread == NULL || (*env)->ExceptionCheck(env)) goto cleanup;
- name = (*env)->NewStringUTF(env, "AWT-AppKit");
- if (name == NULL || (*env)->ExceptionCheck(env)) goto cleanup;
- (*env)->CallVoidMethod(env, curThread, setName, name); // AWT_THREADING Safe (known object)
- if ((*env)->ExceptionCheck(env)) goto cleanup;
-
-cleanup:
- if (threadClass != NULL) {
- (*env)->DeleteLocalRef(env, threadClass);
- }
- if (name != NULL) {
- (*env)->DeleteLocalRef(env, name);
- }
- if (curThread != NULL) {
- (*env)->DeleteLocalRef(env, curThread);
- }
- if ((*env)->ExceptionCheck(env)) {
- (*env)->ExceptionDescribe(env);
- (*env)->ExceptionClear(env);
- }
-
- if (verbose) AWT_DEBUG_LOG(@"finished setting thread name");
-}
-
-
-// Returns true if java believes it is running headless
-BOOL isHeadless(JNIEnv *env) {
- // Just access the property directly, instead of using GraphicsEnvironment.isHeadless.
- // This is because this may be called while AWT is being loaded, and calling AWT
- // while it is being loaded will deadlock.
- static JNF_CLASS_CACHE(jc_Toolkit, "java/awt/GraphicsEnvironment");
- static JNF_STATIC_MEMBER_CACHE(jm_isHeadless, jc_Toolkit, "isHeadless", "()Z");
- return JNFCallStaticBooleanMethod(env, jm_isHeadless);
-}
-
-BOOL isSWTInWebStart(JNIEnv* env) {
- NSString *swtWebStart = [PropertiesUtilities javaSystemPropertyForKey:@"com.apple.javaws.usingSWT" withEnv:env];
- return [@"true" isCaseInsensitiveLike:swtWebStart];
-}
-
-void setBusy(BOOL busy) {
-AWT_ASSERT_APPKIT_THREAD;
-
- JNIEnv *env = [ThreadUtilities getJNIEnv];
- static JNF_CLASS_CACHE(jc_AWTAutoShutdown, "sun/awt/AWTAutoShutdown");
-
- if (busy) {
- static JNF_STATIC_MEMBER_CACHE(jm_notifyBusyMethod, jc_AWTAutoShutdown, "notifyToolkitThreadBusy", "()V");
- JNFCallStaticVoidMethod(env, jm_notifyBusyMethod);
- } else {
- static JNF_STATIC_MEMBER_CACHE(jm_notifyFreeMethod, jc_AWTAutoShutdown, "notifyToolkitThreadFree", "()V");
- JNFCallStaticVoidMethod(env, jm_notifyFreeMethod);
- }
-}
-
-static void BusyObserver(CFRunLoopObserverRef ref, CFRunLoopActivity what, void* arg) {
-AWT_ASSERT_APPKIT_THREAD;
-
- // This is only called with the selector kCFRunLoopAfterWaiting.
-#ifndef PRODUCT_BUILD
- assert(what == kCFRunLoopAfterWaiting);
-#endif /* PRODUCT_BUILD */
-
- setBusy(YES);
-}
-
-static void NotBusyObserver(CFRunLoopObserverRef ref, CFRunLoopActivity what, void* arg) {
-AWT_ASSERT_APPKIT_THREAD;
-
- // This is only called with the selector kCFRunLoopBeforeWaiting.
-#ifndef PRODUCT_BUILD
- assert(what == kCFRunLoopBeforeWaiting);
-#endif /* PRODUCT_BUILD */
-
- setBusy(NO);
-}
-
-static void AWT_NSUncaughtExceptionHandler(NSException *exception) {
- NSLog(@"Apple AWT Internal Exception: %@", [exception description]);
-}
-
-// This is an empty Obj-C object just so that -peformSelectorOnMainThread can be used.
-@interface AWTStarter : NSObject { }
-+ (void)start:(BOOL)headless;
-- (void)starter:(NSArray*)args;
-+ (void)appKitIsRunning:(id)arg;
-@end
-
-@implementation AWTStarter
-
-+ (BOOL) isConnectedToWindowServer {
- SecuritySessionId session_id;
- SessionAttributeBits session_info;
- OSStatus status = SessionGetInfo(callerSecuritySession, &session_id, &session_info);
- if (status != noErr) return NO;
- if (!(session_info & sessionHasGraphicAccess)) return NO;
- return YES;
-}
-
-+ (BOOL) markAppAsDaemon {
- id jrsAppKitAWTClass = objc_getClass("JRSAppKitAWT");
- SEL markAppSel = @selector(markAppIsDaemon);
- if (![jrsAppKitAWTClass respondsToSelector:markAppSel]) return NO;
- return [jrsAppKitAWTClass performSelector:markAppSel] ? YES : NO;
-}
-
-+ (void)appKitIsRunning:(id)arg {
- // Headless: NO
- // Embedded: BOTH
- // Multiple Calls: NO
- // Callers: AppKit's NSApplicationDidFinishLaunchingNotification or +[AWTStarter startAWT:]
-AWT_ASSERT_APPKIT_THREAD;
-
- BOOL verbose = ShouldPrintVerboseDebugging();
- if (verbose) AWT_DEBUG_LOG(@"about to message AppKit started");
-
- // Signal that AppKit has started (or is already running).
- pthread_mutex_lock(&sAppKitStarted_mutex);
- sAppKitStarted = YES;
- pthread_cond_signal(&sAppKitStarted_cv);
- pthread_mutex_unlock(&sAppKitStarted_mutex);
-
- if (verbose) AWT_DEBUG_LOG(@"finished messaging AppKit started");
-}
-
-+ (void)start:(BOOL)headless
-{
- BOOL verbose = ShouldPrintVerboseDebugging();
-
- // Headless: BOTH
- // Embedded: BOTH
- // Multiple Calls: NO
- // Caller: JNI_OnLoad
-
- // onMainThread is NOT the same at SWT mode!
- // If the JVM was started on the first thread for SWT, but the SWT loads the AWT on a secondary thread,
- // onMainThread here will be false but SWT mode will be true. If we are currently on the main thread, we don't
- // need to throw AWT startup over to another thread.
- BOOL onMainThread = (pthread_main_np() != 0);
-
- if (verbose) {
- NSString *msg = [NSString stringWithFormat:@"+[AWTStarter start headless:%d] { onMainThread:%d }", headless, onMainThread];
- AWT_DEBUG_LOG(msg);
- }
-
- if (!headless)
- {
- // Listen for the NSApp to start. This indicates that JNI_OnLoad can proceed.
- // It must wait because there is a chance that another java thread will grab
- // the AppKit lock before the +[NSApplication sharedApplication] returns.
- // See <rdar://problem/3492666> for an example.
- [[NSNotificationCenter defaultCenter] addObserver:[AWTStarter class]
- selector:@selector(appKitIsRunning:)
- name:NSApplicationDidFinishLaunchingNotification
- object:nil];
-
- if (verbose) NSLog(@"+[AWTStarter start:::]: registered NSApplicationDidFinishLaunchingNotification");
- }
-
- id st = [[AWTStarter alloc] init];
-
- NSArray * args = [NSArray arrayWithObjects:
- [NSNumber numberWithBool: onMainThread],
- [NSNumber numberWithBool: headless],
- [NSNumber numberWithBool: verbose],
- nil];
-
- if (onMainThread) {
- [st starter:args];
- } else {
- [st performSelectorOnMainThread: @selector(starter:) withObject:args waitUntilDone:NO];
- }
-
- if (!headless && !onMainThread) {
- if (verbose) AWT_DEBUG_LOG(@"about to wait on AppKit startup mutex");
-
- // Wait here for AppKit to have started (or for AWT to have been loaded into
- // an already running NSApplication).
- pthread_mutex_lock(&sAppKitStarted_mutex);
- while (sAppKitStarted == NO) {
- pthread_cond_wait(&sAppKitStarted_cv, &sAppKitStarted_mutex);
- }
- pthread_mutex_unlock(&sAppKitStarted_mutex);
-
- // AWT gets here AFTER +[AWTStarter appKitIsRunning:] is called.
- if (verbose) AWT_DEBUG_LOG(@"got out of the AppKit startup mutex");
- }
-
- if (!headless) {
- // Don't set the delegate until the NSApplication has been created and
- // its finishLaunching has initialized it.
- // ApplicationDelegate is the support code for com.apple.eawt.
- [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
- id<NSApplicationDelegate> delegate = [ApplicationDelegate sharedDelegate];
- if (delegate != nil) {
- OSXAPP_SetApplicationDelegate(delegate);
- }
- }];
- }
-}
-
-- (void)starter:(NSArray*)args {
- NSAutoreleasePool *pool = [NSAutoreleasePool new];
-
- BOOL onMainThread = [[args objectAtIndex:0] boolValue];
- BOOL headless = [[args objectAtIndex:1] boolValue];
- BOOL verbose = [[args objectAtIndex:2] boolValue];
-
- BOOL wasOnMainThread = onMainThread;
-
- // Add the exception handler of last resort
- NSSetUncaughtExceptionHandler(AWT_NSUncaughtExceptionHandler);
-
- // Headless mode trumps either ordinary AWT or SWT-in-AWT mode. Declare us a daemon and return.
- if (headless) {
- // Note that we don't install run loop observers in headless mode
- // because we don't need them (see 7174704)
- if (!forceEmbeddedMode) {
- setUpAppKitThreadName();
- }
- [AWTStarter markAppAsDaemon];
- return;
- }
-
- if (forceEmbeddedMode) {
- if (verbose) NSLog(@"in SWT or SWT/WebStart mode");
-
- // Init a default NSApplication instance instead of the NSApplicationAWT.
- // Note that [NSApp isRunning] will return YES after that, though
- // this behavior isn't specified anywhere. We rely on that.
- NSApplicationLoad();
- }
-
- // This will create a NSApplicationAWT for standalone AWT programs, unless there is
- // already a NSApplication instance. If there is already a NSApplication instance,
- // and -[NSApplication isRunning] returns YES, AWT is embedded inside another
- // AppKit Application.
- NSApplication *app = [NSApplicationAWT sharedApplication];
- isEmbedded = ![NSApp isKindOfClass:[NSApplicationAWT class]];
- [ThreadUtilities setAWTEmbedded:isEmbedded];
-
- if (!isEmbedded) {
- // Install run loop observers and set the AppKit Java thread name
- setUpAWTAppKit();
- setUpAppKitThreadName();
- }
-
- // AWT gets to this point BEFORE NSApplicationDidFinishLaunchingNotification is sent.
- if (![app isRunning]) {
- if (verbose) AWT_DEBUG_LOG(@"+[AWTStarter startAWT]: ![app isRunning]");
-
- // This is where the AWT AppKit thread parks itself to process events.
- [NSApplicationAWT runAWTLoopWithApp: app];
- } else {
- // We're either embedded, or showing a splash screen
- if (isEmbedded) {
- if (verbose) AWT_DEBUG_LOG(@"running embedded");
-
- // We don't track if the runloop is busy, so set it free to let AWT finish when it needs
- setBusy(NO);
- } else {
- if (verbose) AWT_DEBUG_LOG(@"running after showing a splash screen");
- }
-
- // Signal so that JNI_OnLoad can proceed.
- if (!wasOnMainThread) [AWTStarter appKitIsRunning:nil];
-
- // Proceed to exit this call as there is no reason to run the NSApplication event loop.
- }
-
- [pool drain];
-}
-
-@end
-
-
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
- BOOL verbose = ShouldPrintVerboseDebugging();
- if (verbose) AWT_DEBUG_LOG(@"entered JNI_OnLoad");
-
- // Headless: BOTH
- // Embedded: BOTH
- // Multiple Calls: NO
- // Caller: JavaVM classloader
-
- // Keep a static reference for other archives.
- OSXAPP_SetJavaVM(vm);
-
- JNIEnv *env = NULL;
-
- // Need JNIEnv for JNF_COCOA_ENTER(env); macro below
- jint status = (*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_4);
- if (status != JNI_OK || env == NULL) {
- AWT_DEBUG_LOG(@"Can't get JNIEnv");
- return JNI_VERSION_1_4;
- }
-
-JNF_COCOA_ENTER(env);
-
- // Launcher sets this env variable if -XstartOnFirstThread is specified
- char envVar[80];
- snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
- if (getenv(envVar) != NULL) {
- forceEmbeddedMode = YES;
- unsetenv(envVar);
- }
-
- if (isSWTInWebStart(env)) {
- forceEmbeddedMode = YES;
- }
- JNIEnv* env = [ThreadUtilities getJNIEnvUncached];
- jclass jc_ThreadGroupUtils = (*env)->FindClass(env, "sun/awt/util/ThreadGroupUtils");
- jmethodID sjm_getRootThreadGroup = (*env)->GetStaticMethodID(env, jc_ThreadGroupUtils, "getRootThreadGroup", "()Ljava/lang/ThreadGroup;");
- jobject rootThreadGroup = (*env)->CallStaticObjectMethod(env, jc_ThreadGroupUtils, sjm_getRootThreadGroup);
- [ThreadUtilities setAppkitThreadGroup:(*env)->NewGlobalRef(env, rootThreadGroup)];
- // The current thread was attached in getJNIEnvUnchached.
- // Detach it back. It will be reattached later if needed with a proper TG
- [ThreadUtilities detachCurrentThread];
-
- BOOL headless = isHeadless(env);
-
- // We need to let Foundation know that this is a multithreaded application, if it isn't already.
- if (![NSThread isMultiThreaded]) {
- [NSThread detachNewThreadSelector:nil toTarget:nil withObject:nil];
- }
-
- [AWTStarter start:headless];
-
-JNF_COCOA_EXIT(env);
-
- if (verbose) AWT_DEBUG_LOG(@"exiting JNI_OnLoad");
-
- return JNI_VERSION_1_4;
-}
--- a/jdk/src/macosx/native/sun/awt/splashscreen/splashscreen_sys.m Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/splashscreen/splashscreen_sys.m Wed Jul 05 19:50:57 2017 +0200
@@ -125,6 +125,39 @@
return buf;
}
+char* SplashGetScaledImageName(const char* jar, const char* file,
+ float *scaleFactor) {
+ NSAutoreleasePool *pool = [NSAutoreleasePool new];
+ *scaleFactor = 1;
+ char* scaledFile = nil;
+ float screenScaleFactor = [SplashNSScreen() backingScaleFactor];
+
+ if (screenScaleFactor > 1) {
+ NSString *fileName = [NSString stringWithUTF8String: file];
+ NSUInteger length = [fileName length];
+ NSRange range = [fileName rangeOfString: @"."
+ options:NSBackwardsSearch];
+ NSUInteger dotIndex = range.location;
+ NSString *fileName2x = nil;
+
+ if (dotIndex == NSNotFound) {
+ fileName2x = [fileName stringByAppendingString: @"@2x"];
+ } else {
+ fileName2x = [fileName substringToIndex: dotIndex];
+ fileName2x = [fileName2x stringByAppendingString: @"@2x"];
+ fileName2x = [fileName2x stringByAppendingString:
+ [fileName substringFromIndex: dotIndex]];
+ }
+
+ if ((fileName2x != nil) && (jar || [[NSFileManager defaultManager]
+ fileExistsAtPath: fileName2x])){
+ *scaleFactor = 2;
+ scaledFile = strdup([fileName2x UTF8String]);
+ }
+ }
+ [pool drain];
+ return scaledFile;
+}
void
SplashInitPlatform(Splash * splash) {
@@ -132,7 +165,7 @@
splash->maskRequired = 0;
-
+
//TODO: the following is too much of a hack but should work in 90% cases.
// besides we don't use device-dependant drawing, so probably
// that's very fine indeed
@@ -225,7 +258,15 @@
[image setBackgroundColor: [NSColor clearColor]];
[image addRepresentation: rep];
-
+ float scaleFactor = splash->scaleFactor;
+ if (scaleFactor > 0 && scaleFactor != 1) {
+ [image setScalesWhenResized:YES];
+ NSSize size = [image size];
+ size.width /= scaleFactor;
+ size.height /= scaleFactor;
+ [image setSize: size];
+ }
+
NSImageView * view = [[NSImageView alloc] init];
[view setImage: image];
--- a/jdk/src/macosx/native/sun/osxapp/AWT_debug.h Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/native/sun/osxapp/AWT_debug.h Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,12 +28,16 @@
#import <Cocoa/Cocoa.h>
+bool ShouldPrintVerboseDebugging();
#define kInternalError "java/lang/InternalError"
#define AWT_DEBUG_LOG(str) \
NSLog(@"\tCocoa AWT: %@ %@", str, [NSThread callStackSymbols])
+#define AWT_STARTUP_LOG(str) \
+ if (ShouldPrintVerboseDebugging()) AWT_DEBUG_LOG((str))
+
#define AWT_DEBUG_BUG_REPORT_MESSAGE \
NSLog(@"\tPlease file a bug report at http://bugreport.java.com/bugreport \
with this message and a reproducible test case.")
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/native/sun/osxapp/AWT_debug.m Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#import "AWT_debug.h"
+
+bool ShouldPrintVerboseDebugging() {
+ static int debug = -1;
+ if (debug == -1) {
+ debug = (int)(getenv("JAVA_AWT_VERBOSE") != NULL);
+ }
+ return (bool)debug;
+}
--- a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.h Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.h Wed Jul 05 19:50:57 2017 +0200
@@ -129,8 +129,6 @@
+ (JNIEnv*)getJNIEnvUncached;
+ (void)detachCurrentThread;
+ (void)setAppkitThreadGroup:(jobject)group;
-+ (void)setAWTEmbedded:(BOOL)embedded;
-+ (BOOL)isAWTEmbedded;
//Wrappers for the corresponding JNFRunLoop methods with a check for main thread
+ (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block;
--- a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m Wed Jul 05 19:50:57 2017 +0200
@@ -34,7 +34,6 @@
JavaVM *jvm = NULL;
static JNIEnv *appKitEnv = NULL;
static jobject appkitThreadGroup = NULL;
-static BOOL awtEmbedded = NO;
static inline void attachCurrentThread(void** env) {
if ([NSThread isMainThread]) {
@@ -88,14 +87,6 @@
}
}
-+ (void)setAWTEmbedded:(BOOL)embedded {
- awtEmbedded = embedded;
-}
-
-+ (BOOL)isAWTEmbedded {
- return awtEmbedded;
-}
-
@end
--- a/jdk/src/share/bin/java.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/bin/java.c Wed Jul 05 19:50:57 2017 +0200
@@ -1816,20 +1816,48 @@
const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
int data_size;
- void *image_data;
+ void *image_data = NULL;
+ float scale_factor = 1;
+ char *scaled_splash_name = NULL;
+
+ if (file_name == NULL){
+ return;
+ }
+
+ scaled_splash_name = DoSplashGetScaledImageName(
+ jar_name, file_name, &scale_factor);
if (jar_name) {
- image_data = JLI_JarUnpackFile(jar_name, file_name, &data_size);
+
+ if (scaled_splash_name) {
+ image_data = JLI_JarUnpackFile(
+ jar_name, scaled_splash_name, &data_size);
+ }
+
+ if (!image_data) {
+ scale_factor = 1;
+ image_data = JLI_JarUnpackFile(
+ jar_name, file_name, &data_size);
+ }
if (image_data) {
DoSplashInit();
+ DoSplashSetScaleFactor(scale_factor);
DoSplashLoadMemory(image_data, data_size);
JLI_MemFree(image_data);
}
- } else if (file_name) {
+ } else {
DoSplashInit();
- DoSplashLoadFile(file_name);
- } else {
- return;
+ if (scaled_splash_name) {
+ DoSplashSetScaleFactor(scale_factor);
+ DoSplashLoadFile(scaled_splash_name);
+ } else {
+ DoSplashLoadFile(file_name);
+ }
}
+
+ if (scaled_splash_name) {
+ JLI_MemFree(scaled_splash_name);
+ }
+
DoSplashSetFileJarName(file_name, jar_name);
/*
--- a/jdk/src/share/bin/splashscreen.h Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/bin/splashscreen.h Wed Jul 05 19:50:57 2017 +0200
@@ -29,3 +29,6 @@
void DoSplashInit(void);
void DoSplashClose(void);
void DoSplashSetFileJarName(const char* fileName, const char* jarName);
+void DoSplashSetScaleFactor(float scaleFactor);
+char* DoSplashGetScaledImageName(const char* jarName, const char* fileName,
+ float* scaleFactor);
--- a/jdk/src/share/bin/splashscreen_stubs.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/bin/splashscreen_stubs.c Wed Jul 05 19:50:57 2017 +0200
@@ -37,6 +37,9 @@
typedef void (*SplashClose_t)(void);
typedef void (*SplashSetFileJarName_t)(const char* fileName,
const char* jarName);
+typedef void (*SplashSetScaleFactor_t)(float scaleFactor);
+typedef char* (*SplashGetScaledImageName_t)(const char* fileName,
+ const char* jarName, float* scaleFactor);
/*
* This macro invokes a function from the shared lib.
@@ -58,11 +61,11 @@
#define INVOKEV(name) _INVOKE(name, ,;)
int DoSplashLoadMemory(void* pdata, int size) {
- INVOKE(SplashLoadMemory,0)(pdata, size);
+ INVOKE(SplashLoadMemory, NULL)(pdata, size);
}
int DoSplashLoadFile(const char* filename) {
- INVOKE(SplashLoadFile,0)(filename);
+ INVOKE(SplashLoadFile, NULL)(filename);
}
void DoSplashInit(void) {
@@ -76,3 +79,12 @@
void DoSplashSetFileJarName(const char* fileName, const char* jarName) {
INVOKEV(SplashSetFileJarName)(fileName, jarName);
}
+
+void DoSplashSetScaleFactor(float scaleFactor) {
+ INVOKEV(SplashSetScaleFactor)(scaleFactor);
+}
+
+char* DoSplashGetScaledImageName(const char* fileName, const char* jarName,
+ float* scaleFactor) {
+ INVOKE(SplashGetScaledImageName, NULL)(fileName, jarName, scaleFactor);
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/beans/introspect/ClassInfo.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.beans.introspect;
+
+import com.sun.beans.util.Cache;
+
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Map;
+
+import static sun.reflect.misc.ReflectUtil.checkPackageAccess;
+
+public final class ClassInfo {
+ private static final ClassInfo DEFAULT = new ClassInfo(null);
+ private static final Cache<Class<?>,ClassInfo> CACHE
+ = new Cache<Class<?>,ClassInfo>(Cache.Kind.SOFT, Cache.Kind.SOFT) {
+ @Override
+ public ClassInfo create(Class<?> type) {
+ return new ClassInfo(type);
+ }
+ };
+
+ public static ClassInfo get(Class<?> type) {
+ if (type == null) {
+ return DEFAULT;
+ }
+ try {
+ checkPackageAccess(type);
+ return CACHE.get(type);
+ } catch (SecurityException exception) {
+ return DEFAULT;
+ }
+ }
+
+ private final Object mutex = new Object();
+ private final Class<?> type;
+ private List<Method> methods;
+ private Map<String,PropertyInfo> properties;
+ private Map<String,EventSetInfo> eventSets;
+
+ private ClassInfo(Class<?> type) {
+ this.type = type;
+ }
+
+ public List<Method> getMethods() {
+ if (this.methods == null) {
+ synchronized (this.mutex) {
+ if (this.methods == null) {
+ this.methods = MethodInfo.get(this.type);
+ }
+ }
+ }
+ return this.methods;
+ }
+
+ public Map<String,PropertyInfo> getProperties() {
+ if (this.properties == null) {
+ synchronized (this.mutex) {
+ if (this.properties == null) {
+ this.properties = PropertyInfo.get(this.type);
+ }
+ }
+ }
+ return this.properties;
+ }
+
+ public Map<String,EventSetInfo> getEventSets() {
+ if (this.eventSets == null) {
+ synchronized (this.mutex) {
+ if (this.eventSets == null) {
+ this.eventSets = EventSetInfo.get(this.type);
+ }
+ }
+ }
+ return this.eventSets;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/beans/introspect/EventSetInfo.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.beans.introspect;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
+import java.util.EventListener;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TooManyListenersException;
+import java.util.TreeMap;
+
+public final class EventSetInfo {
+ private MethodInfo add;
+ private MethodInfo remove;
+ private MethodInfo get;
+
+ private EventSetInfo() {
+ }
+
+ private boolean initialize() {
+ if ((this.add == null) || (this.remove == null) || (this.remove.type != this.add.type)) {
+ return false;
+ }
+ if ((this.get != null) && (this.get.type != this.add.type)) {
+ this.get = null;
+ }
+ return true;
+ }
+
+ public Class<?> getListenerType() {
+ return this.add.type;
+ }
+
+ public Method getAddMethod() {
+ return this.add.method;
+ }
+
+ public Method getRemoveMethod() {
+ return this.remove.method;
+ }
+
+ public Method getGetMethod() {
+ return (this.get == null) ? null : this.get.method;
+ }
+
+ public boolean isUnicast() {
+ // if the adder method throws the TooManyListenersException
+ // then it is an Unicast event source
+ return this.add.isThrow(TooManyListenersException.class);
+ }
+
+ private static MethodInfo getInfo(MethodInfo info, Method method, int prefix, int postfix) {
+ Class<?> type = (postfix > 0)
+ ? MethodInfo.resolve(method, method.getGenericReturnType()).getComponentType()
+ : MethodInfo.resolve(method, method.getGenericParameterTypes()[0]);
+
+ if ((type != null) && EventListener.class.isAssignableFrom(type)) {
+ String name = method.getName();
+ if (prefix + postfix < name.length()) {
+ if (type.getName().endsWith(name.substring(prefix, name.length() - postfix))) {
+ if ((info == null) || info.type.isAssignableFrom(type)) {
+ return new MethodInfo(method, type);
+ }
+ }
+ }
+ }
+ return info;
+ }
+
+ private static EventSetInfo getInfo(Map<String,EventSetInfo> map, String key) {
+ EventSetInfo info = map.get(key);
+ if (info == null) {
+ info = new EventSetInfo();
+ map.put(key, info);
+ }
+ return info;
+ }
+
+ public static Map<String,EventSetInfo> get(Class<?> type) {
+ List<Method> methods = ClassInfo.get(type).getMethods();
+ if (methods.isEmpty()) {
+ return Collections.emptyMap();
+ }
+ Map<String,EventSetInfo> map = new TreeMap<>();
+ for (Method method : ClassInfo.get(type).getMethods()) {
+ if (!Modifier.isStatic(method.getModifiers())) {
+ Class<?> returnType = method.getReturnType();
+ String name = method.getName();
+ switch (method.getParameterCount()) {
+ case 1:
+ if ((returnType == void.class) && name.endsWith("Listener")) {
+ if (name.startsWith("add")) {
+ EventSetInfo info = getInfo(map, name.substring(3, name.length() - 8));
+ info.add = getInfo(info.add, method, 3, 0);
+ } else if (name.startsWith("remove")) {
+ EventSetInfo info = getInfo(map, name.substring(6, name.length() - 8));
+ info.remove = getInfo(info.remove, method, 6, 0);
+ }
+ }
+ break;
+ case 0:
+ if (returnType.isArray() && name.startsWith("get") && name.endsWith("Listeners")) {
+ EventSetInfo info = getInfo(map, name.substring(3, name.length() - 9));
+ info.get = getInfo(info.get, method, 3, 1);
+ }
+ break;
+ }
+ }
+ }
+ Iterator<EventSetInfo> iterator = map.values().iterator();
+ while (iterator.hasNext()) {
+ if (!iterator.next().initialize()) {
+ iterator.remove();
+ }
+ }
+ return !map.isEmpty()
+ ? Collections.unmodifiableMap(map)
+ : Collections.emptyMap();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/beans/introspect/MethodInfo.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.beans.introspect;
+
+import com.sun.beans.TypeResolver;
+import com.sun.beans.finder.MethodFinder;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+final class MethodInfo {
+ final Method method;
+ final Class<?> type;
+
+ MethodInfo(Method method, Class<?> type) {
+ this.method = method;
+ this.type = type;
+ }
+
+ MethodInfo(Method method, Type type) {
+ this.method = method;
+ this.type = resolve(method, type);
+ }
+
+ boolean isThrow(Class<?> exception) {
+ for (Class<?> type : this.method.getExceptionTypes()) {
+ if (type == exception) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static Class<?> resolve(Method method, Type type) {
+ return TypeResolver.erase(TypeResolver.resolveInClass(method.getDeclaringClass(), type));
+ }
+
+ static List<Method> get(Class<?> type) {
+ List<Method> list = null;
+ if (type != null) {
+ boolean inaccessible = !Modifier.isPublic(type.getModifiers());
+ for (Method method : type.getMethods()) {
+ if (method.getDeclaringClass().equals(type)) {
+ if (inaccessible) {
+ try {
+ method = MethodFinder.findAccessibleMethod(method);
+ if (!method.getDeclaringClass().isInterface()) {
+ method = null; // ignore methods from superclasses
+ }
+ } catch (NoSuchMethodException exception) {
+ // commented out because of 6976577
+ // method = null; // ignore inaccessible methods
+ }
+ }
+ if (method != null) {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+ list.add(method);
+ }
+ }
+ }
+ }
+ return (list != null)
+ ? Collections.unmodifiableList(list)
+ : Collections.emptyList();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/beans/introspect/PropertyInfo.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.beans.introspect;
+
+import java.beans.BeanProperty;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import static com.sun.beans.finder.ClassFinder.findClass;
+
+public final class PropertyInfo {
+ public enum Name {bound, expert, hidden, preferred, visualUpdate, description, enumerationValues}
+
+ private static final String VETO_EXCEPTION_NAME = "java.beans.PropertyVetoException";
+ private static final Class<?> VETO_EXCEPTION;
+
+ static {
+ Class<?> type;
+ try {
+ type = Class.forName(VETO_EXCEPTION_NAME);
+ } catch (Exception exception) {
+ type = null;
+ }
+ VETO_EXCEPTION = type;
+ }
+
+ private Class<?> type;
+ private MethodInfo read;
+ private MethodInfo write;
+ private PropertyInfo indexed;
+ private List<MethodInfo> readList;
+ private List<MethodInfo> writeList;
+ private Map<Name,Object> map;
+
+ private PropertyInfo() {
+ }
+
+ private boolean initialize() {
+ if (this.read != null) {
+ this.type = this.read.type;
+ }
+ if (this.readList != null) {
+ for (MethodInfo info : this.readList) {
+ if ((this.read == null) || this.read.type.isAssignableFrom(info.type)) {
+ this.read = info;
+ this.type = info.type;
+ }
+ }
+ this.readList = null;
+ }
+ if (this.writeList != null) {
+ for (MethodInfo info : this.writeList) {
+ if (this.type == null) {
+ this.write = info;
+ this.type = info.type;
+ } else if (this.type.isAssignableFrom(info.type)) {
+ if ((this.write == null) || this.write.type.isAssignableFrom(info.type)) {
+ this.write = info;
+ }
+ }
+ }
+ this.writeList = null;
+ }
+ if (this.indexed != null) {
+ if ((this.type != null) && !this.type.isArray()) {
+ this.indexed = null; // property type is not an array
+ } else if (!this.indexed.initialize()) {
+ this.indexed = null; // cannot initialize indexed methods
+ } else if ((this.type != null) && (this.indexed.type != this.type.getComponentType())) {
+ this.indexed = null; // different property types
+ } else {
+ this.map = this.indexed.map;
+ this.indexed.map = null;
+ }
+ }
+ if ((this.type == null) && (this.indexed == null)) {
+ return false;
+ }
+ initialize(this.write);
+ initialize(this.read);
+ return true;
+ }
+
+ private void initialize(MethodInfo info) {
+ if (info != null) {
+ BeanProperty annotation = info.method.getAnnotation(BeanProperty.class);
+ if (annotation != null) {
+ if (!annotation.bound()) {
+ put(Name.bound, Boolean.FALSE);
+ }
+ put(Name.expert, annotation.expert());
+ put(Name.hidden, annotation.hidden());
+ put(Name.preferred, annotation.preferred());
+ put(Name.visualUpdate, annotation.visualUpdate());
+ put(Name.description, annotation.description());
+ String[] values = annotation.enumerationValues();
+ if (0 < values.length) {
+ try {
+ Object[] array = new Object[3 * values.length];
+ int index = 0;
+ for (String value : values) {
+ Class<?> type = info.method.getDeclaringClass();
+ String name = value;
+ int pos = value.lastIndexOf('.');
+ if (pos > 0) {
+ name = value.substring(0, pos);
+ if (name.indexOf('.') < 0) {
+ String pkg = type.getName();
+ name = pkg.substring(0, 1 + Math.max(
+ pkg.lastIndexOf('.'),
+ pkg.lastIndexOf('$'))) + name;
+ }
+ type = findClass(name);
+ name = value.substring(pos + 1);
+ }
+ Field field = type.getField(name);
+ if (Modifier.isStatic(field.getModifiers()) && info.type.isAssignableFrom(field.getType())) {
+ array[index++] = name;
+ array[index++] = field.get(null);
+ array[index++] = value;
+ }
+ }
+ if (index == array.length) {
+ put(Name.enumerationValues, array);
+ }
+ } catch (Exception ignored) {
+ ignored.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+
+ public Class<?> getPropertyType() {
+ return this.type;
+ }
+
+ public Method getReadMethod() {
+ return (this.read == null) ? null : this.read.method;
+ }
+
+ public Method getWriteMethod() {
+ return (this.write == null) ? null : this.write.method;
+ }
+
+ public PropertyInfo getIndexed() {
+ return this.indexed;
+ }
+
+ public boolean isConstrained() {
+ if (this.write != null) {
+ if (VETO_EXCEPTION == null) {
+ for (Class<?> type : this.write.method.getExceptionTypes()) {
+ if (type.getName().equals(VETO_EXCEPTION_NAME)) {
+ return true;
+ }
+ }
+ } else if (this.write.isThrow(VETO_EXCEPTION)) {
+ return true;
+ }
+ }
+ return (this.indexed != null) && this.indexed.isConstrained();
+ }
+
+ public boolean is(Name name) {
+ Object value = get(name);
+ return (value instanceof Boolean)
+ ? (Boolean) value
+ : Name.bound.equals(name);
+ }
+
+ public Object get(Name name) {
+ return this.map == null ? null : this.map.get(name);
+ }
+
+ private void put(Name name, boolean value) {
+ if (value) {
+ put(name, Boolean.TRUE);
+ }
+ }
+
+ private void put(Name name, String value) {
+ if (0 < value.length()) {
+ put(name, (Object) value);
+ }
+ }
+
+ private void put(Name name, Object value) {
+ if (this.map == null) {
+ this.map = new EnumMap<>(Name.class);
+ }
+ this.map.put(name, value);
+ }
+
+ private static List<MethodInfo> add(List<MethodInfo> list, Method method, Type type) {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+ list.add(new MethodInfo(method, type));
+ return list;
+ }
+
+ private static boolean isPrefix(String name, String prefix) {
+ return name.length() > prefix.length() && name.startsWith(prefix);
+ }
+
+ private static PropertyInfo getInfo(Map<String,PropertyInfo> map, String key, boolean indexed) {
+ PropertyInfo info = map.get(key);
+ if (info == null) {
+ info = new PropertyInfo();
+ map.put(key, info);
+ }
+ if (!indexed) {
+ return info;
+ }
+ if (info.indexed == null) {
+ info.indexed = new PropertyInfo();
+ }
+ return info.indexed;
+ }
+
+ public static Map<String,PropertyInfo> get(Class<?> type) {
+ List<Method> methods = ClassInfo.get(type).getMethods();
+ if (methods.isEmpty()) {
+ return Collections.emptyMap();
+ }
+ Map<String,PropertyInfo> map = new TreeMap<>();
+ for (Method method : methods) {
+ if (!Modifier.isStatic(method.getModifiers())) {
+ Class<?> returnType = method.getReturnType();
+ String name = method.getName();
+ switch (method.getParameterCount()) {
+ case 0:
+ if (returnType.equals(boolean.class) && isPrefix(name, "is")) {
+ PropertyInfo info = getInfo(map, name.substring(2), false);
+ info.read = new MethodInfo(method, boolean.class);
+ } else if (!returnType.equals(void.class) && isPrefix(name, "get")) {
+ PropertyInfo info = getInfo(map, name.substring(3), false);
+ info.readList = add(info.readList, method, method.getGenericReturnType());
+ }
+ break;
+ case 1:
+ if (returnType.equals(void.class) && isPrefix(name, "set")) {
+ PropertyInfo info = getInfo(map, name.substring(3), false);
+ info.writeList = add(info.writeList, method, method.getGenericParameterTypes()[0]);
+ } else if (!returnType.equals(void.class) && method.getParameterTypes()[0].equals(int.class) && isPrefix(name, "get")) {
+ PropertyInfo info = getInfo(map, name.substring(3), true);
+ info.readList = add(info.readList, method, method.getGenericReturnType());
+ }
+ break;
+ case 2:
+ if (returnType.equals(void.class) && method.getParameterTypes()[0].equals(int.class) && isPrefix(name, "set")) {
+ PropertyInfo info = getInfo(map, name.substring(3), true);
+ info.writeList = add(info.writeList, method, method.getGenericParameterTypes()[1]);
+ }
+ break;
+ }
+ }
+ }
+ Iterator<PropertyInfo> iterator = map.values().iterator();
+ while (iterator.hasNext()) {
+ if (!iterator.next().initialize()) {
+ iterator.remove();
+ }
+ }
+ return !map.isEmpty()
+ ? Collections.unmodifiableMap(map)
+ : Collections.emptyMap();
+ }
+}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKFileChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKFileChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -82,14 +82,14 @@
private String renameFileErrorTitle = null;
private String renameFileErrorText = null;
- private JComboBox filterComboBox;
+ private JComboBox<FileFilter> filterComboBox;
private FilterComboBoxModel filterComboBoxModel;
// From Motif
private JPanel rightPanel;
- private JList directoryList;
- private JList fileList;
+ private JList<File> directoryList;
+ private JList<File> fileList;
private JLabel pathField;
private JTextField fileNameTextField;
@@ -116,7 +116,7 @@
private int pathLabelMnemonic = 0;
private int filterLabelMnemonic = 0;
- private JComboBox directoryComboBox;
+ private JComboBox<File> directoryComboBox;
private DirectoryComboBoxModel directoryComboBoxModel;
private Action directoryComboBoxAction = new DirectoryComboBoxAction();
private JPanel bottomButtonPanel;
@@ -153,7 +153,7 @@
}
int mode = fc.getFileSelectionMode();
- JList list = mode == JFileChooser.DIRECTORIES_ONLY ?
+ JList<File> list = mode == JFileChooser.DIRECTORIES_ONLY ?
directoryList : fileList;
Object[] files = list.getSelectedValues();
int len = files.length;
@@ -369,8 +369,8 @@
}
class DoubleClickListener extends MouseAdapter {
- JList list;
- public DoubleClickListener(JList list) {
+ JList<?> list;
+ public DoubleClickListener(JList<?> list) {
this.list = list;
}
@@ -413,7 +413,7 @@
}
}
- protected MouseListener createDoubleClickListener(JFileChooser fc, JList list) {
+ protected MouseListener createDoubleClickListener(JFileChooser fc, JList<?> list) {
return new DoubleClickListener(list);
}
@@ -423,7 +423,7 @@
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JFileChooser chooser = getFileChooser();
- JList list = (JList) e.getSource();
+ JList<?> list = (JList) e.getSource();
if (chooser.isMultiSelectionEnabled()) {
File[] files = null;
@@ -554,7 +554,7 @@
0, 0) {
public void layoutContainer(Container target) {
super.layoutContainer(target);
- JComboBox comboBox = directoryComboBox;
+ JComboBox<?> comboBox = directoryComboBox;
if (comboBox.getWidth() > target.getWidth()) {
comboBox.setBounds(0, comboBox.getY(), target.getWidth(),
comboBox.getHeight());
@@ -565,7 +565,7 @@
comboBoxPanel.setName("GTKFileChooser.directoryComboBoxPanel");
// CurrentDir ComboBox
directoryComboBoxModel = createDirectoryComboBoxModel(fc);
- directoryComboBox = new JComboBox(directoryComboBoxModel);
+ directoryComboBox = new JComboBox<>(directoryComboBoxModel);
directoryComboBox.setName("GTKFileChooser.directoryComboBox");
directoryComboBox.putClientProperty( "JComboBox.lightweightKeyboardNavigation", "Lightweight" );
directoryComboBox.addActionListener(directoryComboBoxAction);
@@ -710,7 +710,7 @@
filterComboBoxModel = createFilterComboBoxModel();
fc.addPropertyChangeListener(filterComboBoxModel);
- filterComboBox = new JComboBox(filterComboBoxModel);
+ filterComboBox = new JComboBox<>(filterComboBoxModel);
filterComboBox.setRenderer(createFilterComboBoxRenderer());
filterLabel.setLabelFor(filterComboBox);
@@ -851,7 +851,7 @@
}
protected JScrollPane createFilesList() {
- fileList = new JList();
+ fileList = new JList<>();
fileList.setName("GTKFileChooser.fileList");
fileList.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, filesLabelText);
@@ -877,7 +877,7 @@
}
protected JScrollPane createDirectoryList() {
- directoryList = new JList();
+ directoryList = new JList<>();
directoryList.setName("GTKFileChooser.directoryList");
directoryList.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, foldersLabelText);
align(directoryList);
@@ -930,7 +930,7 @@
}
@SuppressWarnings("serial") // Superclass is not serializable across versions
- protected class GTKDirectoryListModel extends AbstractListModel implements ListDataListener {
+ protected class GTKDirectoryListModel extends AbstractListModel<File> implements ListDataListener {
File curDir;
public GTKDirectoryListModel() {
getModel().addListDataListener(this);
@@ -941,7 +941,8 @@
return getModel().getDirectories().size() + 1;
}
- public Object getElementAt(int index) {
+ @Override
+ public File getElementAt(int index) {
return index > 0 ? getModel().getDirectories().elementAt(index - 1):
curDir;
}
@@ -974,7 +975,7 @@
}
@SuppressWarnings("serial") // Superclass is not serializable across versions
- protected class GTKFileListModel extends AbstractListModel implements ListDataListener {
+ protected class GTKFileListModel extends AbstractListModel<File> implements ListDataListener {
public GTKFileListModel() {
getModel().addListDataListener(this);
}
@@ -991,7 +992,8 @@
return getModel().getFiles().indexOf(o);
}
- public Object getElementAt(int index) {
+ @Override
+ public File getElementAt(int index) {
return getModel().getFiles().elementAt(index);
}
@@ -1019,7 +1021,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
protected class FileCellRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list, Object value, int index,
+ public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
@@ -1033,7 +1035,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
protected class DirectoryCellRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list, Object value, int index,
+ public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
@@ -1095,7 +1097,7 @@
* Data model for a type-face selection combo-box.
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
- protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel {
+ protected class DirectoryComboBoxModel extends AbstractListModel<File> implements ComboBoxModel<File> {
Vector<File> directories = new Vector<File>();
File selectedDirectory = null;
JFileChooser chooser = getFileChooser();
@@ -1163,7 +1165,8 @@
return directories.size();
}
- public Object getElementAt(int index) {
+ @Override
+ public File getElementAt(int index) {
return directories.elementAt(index);
}
}
@@ -1314,7 +1317,7 @@
return name;
}
- public Component getListCellRendererComponent(JList list, Object value,
+ public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected,
boolean cellHasFocus) {
@@ -1345,8 +1348,8 @@
* Data model for filter combo-box.
*/
@SuppressWarnings("serial") // JDK implementation class
- protected class FilterComboBoxModel extends AbstractListModel
- implements ComboBoxModel, PropertyChangeListener {
+ protected class FilterComboBoxModel extends AbstractListModel<FileFilter>
+ implements ComboBoxModel<FileFilter>, PropertyChangeListener {
protected FileFilter[] filters;
protected FilterComboBoxModel() {
@@ -1400,7 +1403,8 @@
}
}
- public Object getElementAt(int index) {
+ @Override
+ public FileFilter getElementAt(int index) {
if (index > getSize() - 1) {
// This shouldn't happen. Try to recover gracefully.
return getFileChooser().getFileFilter();
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKIconFactory.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKIconFactory.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -151,7 +151,7 @@
private static class DelegatingIcon extends SynthIcon implements
UIResource {
- private static final Class[] PARAM_TYPES = new Class[] {
+ private static final Class<?>[] PARAM_TYPES = new Class<?>[] {
SynthContext.class, Graphics.class, int.class,
int.class, int.class, int.class, int.class
};
@@ -190,7 +190,7 @@
return (Method)method;
}
- protected Class[] getMethodParamTypes() {
+ protected Class<?>[] getMethodParamTypes() {
return PARAM_TYPES;
}
@@ -262,7 +262,7 @@
// we create a unique icon per ToolBar and lookup the style for the
// HandleBox.
private static class ToolBarHandleIcon extends DelegatingIcon {
- private static final Class[] PARAM_TYPES = new Class[] {
+ private static final Class<?>[] PARAM_TYPES = new Class<?>[] {
SynthContext.class, Graphics.class, int.class,
int.class, int.class, int.class, int.class, Orientation.class,
};
@@ -273,7 +273,7 @@
super(TOOL_BAR_HANDLE_ICON);
}
- protected Class[] getMethodParamTypes() {
+ protected Class<?>[] getMethodParamTypes() {
return PARAM_TYPES;
}
@@ -323,7 +323,7 @@
}
private static class MenuArrowIcon extends DelegatingIcon {
- private static final Class[] PARAM_TYPES = new Class[] {
+ private static final Class<?>[] PARAM_TYPES = new Class<?>[] {
SynthContext.class, Graphics.class, int.class,
int.class, int.class, int.class, int.class, ArrowType.class,
};
@@ -332,7 +332,7 @@
super(MENU_ARROW_ICON);
}
- protected Class[] getMethodParamTypes() {
+ protected Class<?>[] getMethodParamTypes() {
return PARAM_TYPES;
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -1086,13 +1086,13 @@
public Object createValue(UIDefaults table) {
try {
- Class c = Class.forName(className, true,Thread.currentThread().
- getContextClassLoader());
+ Class<?> c = Class.forName(className, true,Thread.currentThread().
+ getContextClassLoader());
if (methodName == null) {
return c.newInstance();
}
- Method m = c.getMethod(methodName, (Class[])null);
+ Method m = c.getMethod(methodName, (Class<?>[])null);
return m.invoke(c, (Object[])null);
} catch (ClassNotFoundException cnfe) {
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -764,7 +764,7 @@
} else {
return;
}
- Map gm = getFrameGeometry();
+ Map<String, Object> gm = getFrameGeometry();
int w = titlePane.getWidth();
int h = titlePane.getHeight();
@@ -828,11 +828,11 @@
}
} // end TitlePaneLayout
- protected Map getFrameGeometry() {
+ protected Map<String, Object> getFrameGeometry() {
return frameGeometry;
}
- protected void setFrameGeometry(JComponent titlePane, Map gm) {
+ protected void setFrameGeometry(JComponent titlePane, Map<String, Object> gm) {
this.frameGeometry = gm;
if (getInt("top_height") == 0 && titlePane != null) {
gm.put("top_height", Integer.valueOf(titlePane.getHeight()));
@@ -1501,7 +1501,7 @@
"name", getStringAttr(frame, "style")
});
if (frame_style != null) {
- Map gm = frameGeometries.get(getStringAttr(frame_style, "geometry"));
+ Map<String, Object> gm = frameGeometries.get(getStringAttr(frame_style, "geometry"));
setFrameGeometry(titlePane, gm);
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/XColors.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/XColors.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -34,7 +34,7 @@
*/
class XColors {
- private static class XColor implements Comparable {
+ private static class XColor implements Comparable<XColor> {
String name;
int red;
@@ -52,10 +52,8 @@
return new ColorUIResource(red, green, blue);
}
- public int compareTo(Object o) {
- XColor other = (XColor)o;
-
- return name.compareTo(other.name);
+ public int compareTo(XColor o) {
+ return name.compareTo(o.name);
}
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -97,7 +97,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
protected class MotifComboPopup extends BasicComboPopup {
- public MotifComboPopup( JComboBox comboBox ) {
+ public MotifComboPopup( JComboBox<Object> comboBox ) {
super( comboBox );
}
@@ -177,7 +177,7 @@
}
public void paintCurrentValue(Graphics g,Rectangle bounds,boolean hasFocus) {
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
Component c;
Dimension d;
c = renderer.getListCellRendererComponent(listBox, comboBox.getSelectedItem(), -1, false, false);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -342,7 +342,7 @@
leftPanel.add(l);
@SuppressWarnings("serial") // anonymous class
- JComboBox tmp2 = new JComboBox<FileFilter>() {
+ JComboBox<FileFilter> tmp2 = new JComboBox<FileFilter>() {
public Dimension getMaximumSize() {
Dimension d = super.getMaximumSize();
d.height = getPreferredSize().height;
@@ -655,7 +655,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
protected class FileCellRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list, Object value, int index,
+ public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
@@ -667,7 +667,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
protected class DirectoryCellRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list, Object value, int index,
+ public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
@@ -778,7 +778,7 @@
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
public class FilterComboBoxRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list,
+ public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -130,11 +130,14 @@
//one second seems plausible value
duration = 1000;
} else {
- duration = XPStyle.getXP().getThemeTransitionDuration(
- c, part,
- normalizeState(oldState),
- normalizeState(newState),
- Prop.TRANSITIONDURATIONS);
+ XPStyle xp = XPStyle.getXP();
+ duration = (xp != null)
+ ? xp.getThemeTransitionDuration(
+ c, part,
+ normalizeState(oldState),
+ normalizeState(newState),
+ Prop.TRANSITIONDURATIONS)
+ : 1000;
}
controller.startAnimation(c, part, oldState, newState, duration);
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -102,7 +102,7 @@
private static void updateAllUIs() {
// Check if the current UI is WindowsLookAndfeel and flush the XP style map.
// Note: Change the package test if this class is moved to a different package.
- Class uiClass = UIManager.getLookAndFeel().getClass();
+ Class<?> uiClass = UIManager.getLookAndFeel().getClass();
if (uiClass.getPackage().equals(DesktopProperty.class.getPackage())) {
XPStyle.invalidateStyle();
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/TMSchema.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/TMSchema.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -446,7 +446,7 @@
initStates();
}
- Enum[] states = stateMap.get(part);
+ Enum<?>[] states = stateMap.get(part);
if (states != null) {
for (int i = 0; i < states.length; i++) {
if (state == states[i]) {
@@ -504,10 +504,10 @@
TRANSITIONDURATIONS(Integer.class, 6000);
- private final Class type;
+ private final Class<?> type;
private final int value;
- private Prop(Class type, int value) {
+ private Prop(Class<?> type, int value) {
this.type = type;
this.value = value;
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -37,6 +37,7 @@
import static com.sun.java.swing.plaf.windows.TMSchema.Part;
import static com.sun.java.swing.plaf.windows.TMSchema.State;
import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
+
import sun.swing.DefaultLookup;
import sun.swing.StringUIClientPropertyKey;
@@ -60,7 +61,7 @@
private static final MouseListener rolloverListener =
new MouseAdapter() {
private void handleRollover(MouseEvent e, boolean isRollover) {
- JComboBox comboBox = getComboBox(e);
+ JComboBox<?> comboBox = getComboBox(e);
WindowsComboBoxUI comboBoxUI = getWindowsComboBoxUI(e);
if (comboBox == null || comboBoxUI == null) {
return;
@@ -88,9 +89,9 @@
handleRollover(e, false);
}
- private JComboBox getComboBox(MouseEvent event) {
+ private JComboBox<?> getComboBox(MouseEvent event) {
Object source = event.getSource();
- JComboBox rv = null;
+ JComboBox<?> rv = null;
if (source instanceof JComboBox) {
rv = (JComboBox) source;
} else if (source instanceof XPComboBoxButton) {
@@ -101,7 +102,7 @@
}
private WindowsComboBoxUI getWindowsComboBoxUI(MouseEvent event) {
- JComboBox comboBox = getComboBox(event);
+ JComboBox<?> comboBox = getComboBox(event);
WindowsComboBoxUI rv = null;
if (comboBox != null
&& comboBox.getUI() instanceof WindowsComboBoxUI) {
@@ -122,7 +123,7 @@
&& (source = e.getSource()) instanceof JComboBox
&& ((JComboBox) source).getUI() instanceof
WindowsComboBoxUI) {
- JComboBox comboBox = (JComboBox) source;
+ JComboBox<?> comboBox = (JComboBox) source;
WindowsComboBoxUI comboBoxUI = (WindowsComboBoxUI) comboBox.getUI();
if (comboBoxUI.arrowButton instanceof XPComboBoxButton) {
((XPComboBoxButton) comboBoxUI.arrowButton).setPart(
@@ -231,6 +232,9 @@
private void paintXPComboBoxBackground(Graphics g, JComponent c) {
XPStyle xp = XPStyle.getXP();
+ if (xp == null) {
+ return;
+ }
State state = getXPComboBoxState(c);
Skin skin = null;
if (! comboBox.isEditable()
@@ -273,7 +277,7 @@
// color for currentValue is the same as for any other item
// mostly copied from javax.swing.plaf.basic.BasicComboBoxUI.paintCurrentValue
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
Component c;
if ( hasFocus && !isPopupVisible(comboBox) ) {
c = renderer.getListCellRendererComponent(
@@ -384,7 +388,7 @@
* @since 1.6
*/
@Override
- protected ListCellRenderer createRenderer() {
+ protected ListCellRenderer<Object> createRenderer() {
XPStyle xp = XPStyle.getXP();
if (xp != null && xp.isSkinDefined(comboBox, Part.CP_READONLY)) {
return new WindowsComboBoxRenderer();
@@ -400,8 +404,9 @@
* @return a button which represents the popup control
*/
protected JButton createArrowButton() {
- if (XPStyle.getXP() != null) {
- return new XPComboBoxButton();
+ XPStyle xp = XPStyle.getXP();
+ if (xp != null) {
+ return new XPComboBoxButton(xp);
} else {
return super.createArrowButton();
}
@@ -409,9 +414,9 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
private class XPComboBoxButton extends XPStyle.GlyphButton {
- public XPComboBoxButton() {
+ public XPComboBoxButton(XPStyle xp) {
super(null,
- (! XPStyle.getXP().isSkinDefined(comboBox, Part.CP_DROPDOWNBUTTONRIGHT))
+ (! xp.isSkinDefined(comboBox, Part.CP_DROPDOWNBUTTONRIGHT))
? Part.CP_DROPDOWNBUTTON
: (comboBox.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT)
? Part.CP_DROPDOWNBUTTONLEFT
@@ -424,10 +429,11 @@
protected State getState() {
State rv;
rv = super.getState();
+ XPStyle xp = XPStyle.getXP();
if (rv != State.DISABLED
&& comboBox != null && ! comboBox.isEditable()
- && XPStyle.getXP().isSkinDefined(comboBox,
- Part.CP_DROPDOWNBUTTONRIGHT)) {
+ && xp != null && xp.isSkinDefined(comboBox,
+ Part.CP_DROPDOWNBUTTONRIGHT)) {
/*
* for non editable ComboBoxes Vista seems to have the
* same glyph for all non DISABLED states
@@ -463,7 +469,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
protected class WindowsComboPopup extends BasicComboPopup {
- public WindowsComboPopup( JComboBox cBox ) {
+ public WindowsComboPopup( JComboBox<Object> cBox ) {
super( cBox );
}
@@ -523,7 +529,7 @@
*/
@Override
public Component getListCellRendererComponent(
- JList list,
+ JList<?> list,
Object value,
int index,
boolean isSelected,
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -191,7 +191,7 @@
return WindowsFileChooserUI.this.getNewFolderAction();
}
- public MouseListener createDoubleClickListener(JList list) {
+ public MouseListener createDoubleClickListener(JList<?> list) {
return WindowsFileChooserUI.this.createDoubleClickListener(getFileChooser(),
list);
}
@@ -994,7 +994,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
class DirectoryComboBoxRenderer extends DefaultListCellRenderer {
IndentIcon ii = new IndentIcon();
- public Component getListCellRendererComponent(JList list, Object value,
+ public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected,
boolean cellHasFocus) {
@@ -1184,7 +1184,7 @@
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
public class FilterComboBoxRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list,
+ public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -125,6 +125,9 @@
static void paintXPText(AbstractButton b, Part part, State state,
Graphics g, int x, int y, String text, int mnemIndex) {
XPStyle xp = XPStyle.getXP();
+ if (xp == null) {
+ return;
+ }
Color textColor = b.getForeground();
if (textColor instanceof UIResource) {
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java Wed Jul 05 19:50:57 2017 +0200
@@ -623,8 +623,8 @@
@SuppressWarnings("serial") // Same-version serialization only
private static class MenuArrowIcon implements Icon, UIResource, Serializable {
public void paintIcon(Component c, Graphics g, int x, int y) {
- if (WindowsMenuItemUI.isVistaPainting()) {
- XPStyle xp = XPStyle.getXP();
+ XPStyle xp = XPStyle.getXP();
+ if (WindowsMenuItemUI.isVistaPainting(xp)) {
State state = State.NORMAL;
if (c instanceof JMenuItem) {
state = ((JMenuItem) c).getModel().isEnabled()
@@ -657,16 +657,18 @@
}
}
public int getIconWidth() {
- if (WindowsMenuItemUI.isVistaPainting()) {
- Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU);
+ XPStyle xp = XPStyle.getXP();
+ if (WindowsMenuItemUI.isVistaPainting(xp)) {
+ Skin skin = xp.getSkin(null, Part.MP_POPUPSUBMENU);
return skin.getWidth();
} else {
return 4;
}
}
public int getIconHeight() {
- if (WindowsMenuItemUI.isVistaPainting()) {
- Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU);
+ XPStyle xp = XPStyle.getXP();
+ if (WindowsMenuItemUI.isVistaPainting(xp)) {
+ Skin skin = xp.getSkin(null, Part.MP_POPUPSUBMENU);
return skin.getHeight();
} else {
return 8;
@@ -692,7 +694,8 @@
}
static int getIconWidth() {
- return XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK).getWidth()
+ XPStyle xp = XPStyle.getXP();
+ return ((xp != null) ? xp.getSkin(null, Part.MP_POPUPCHECK).getWidth() : 16)
+ 2 * OFFSET;
}
@@ -756,12 +759,17 @@
Icon icon = getIcon();
int height = 0;
if (icon != null) {
- height = icon.getIconHeight() + 2 * OFFSET;
+ height = icon.getIconHeight();
} else {
- Skin skin =
- XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK);
- height = skin.getHeight() + 2 * OFFSET;
+ XPStyle xp = XPStyle.getXP();
+ if (xp != null) {
+ Skin skin = xp.getSkin(null, Part.MP_POPUPCHECK);
+ height = skin.getHeight();
+ } else {
+ height = 16;
+ }
}
+ height += 2 * OFFSET;
return height;
}
@@ -809,14 +817,16 @@
? State.BULLETDISABLED
: State.CHECKMARKDISABLED;
}
- Skin skin;
XPStyle xp = XPStyle.getXP();
- skin = xp.getSkin(c, backgroundPart);
- skin.paintSkin(g, x, y,
- getIconWidth(), getIconHeight(), backgroundState);
- if (icon == null) {
- skin = xp.getSkin(c, part);
- skin.paintSkin(g, x + OFFSET, y + OFFSET, state);
+ if (xp != null) {
+ Skin skin;
+ skin = xp.getSkin(c, backgroundPart);
+ skin.paintSkin(g, x, y,
+ getIconWidth(), getIconHeight(), backgroundState);
+ if (icon == null) {
+ skin = xp.getSkin(c, part);
+ skin.paintSkin(g, x + OFFSET, y + OFFSET, state);
+ }
}
}
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -86,14 +86,15 @@
}
} else {
buttonWidth += 2;
- selectedTitleGradientColor =
- UIManager.getColor("InternalFrame.activeTitleGradient");
- notSelectedTitleGradientColor =
- UIManager.getColor("InternalFrame.inactiveTitleGradient");
Color activeBorderColor =
UIManager.getColor("InternalFrame.activeBorderColor");
setBorder(BorderFactory.createLineBorder(activeBorderColor, 1));
}
+ // JDK-8039383: initialize these colors because getXP() may return null when theme is changed
+ selectedTitleGradientColor =
+ UIManager.getColor("InternalFrame.activeTitleGradient");
+ notSelectedTitleGradientColor =
+ UIManager.getColor("InternalFrame.inactiveTitleGradient");
}
protected void uninstallListeners() {
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java Wed Jul 05 19:50:57 2017 +0200
@@ -2326,8 +2326,9 @@
}
public Object getXPValue(UIDefaults table) {
- Border xpBorder = XPStyle.getXP().getBorder(null, (Part)xpValue);
- if (extraMargin != null) {
+ XPStyle xp = XPStyle.getXP();
+ Border xpBorder = xp != null ? xp.getBorder(null, (Part)xpValue) : null;
+ if (xpBorder != null && extraMargin != null) {
return new BorderUIResource.
CompoundBorderUIResource(xpBorder, extraMargin);
} else {
@@ -2343,7 +2344,8 @@
public Object getXPValue(UIDefaults table) {
XPColorValueKey key = (XPColorValueKey)xpValue;
- return XPStyle.getXP().getColor(key.skin, key.prop, null);
+ XPStyle xp = XPStyle.getXP();
+ return xp != null ? xp.getColor(key.skin, key.prop, null) : null;
}
private static class XPColorValueKey {
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -156,8 +156,8 @@
@Override
public void paint(Graphics g, JComponent c) {
- if (WindowsMenuItemUI.isVistaPainting()) {
- XPStyle xp = XPStyle.getXP();
+ XPStyle xp = XPStyle.getXP();
+ if (WindowsMenuItemUI.isVistaPainting(xp)) {
Skin skin;
skin = xp.getSkin(c, Part.MP_BARBACKGROUND);
int width = c.getWidth();
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -108,8 +108,9 @@
static void paintBackground(WindowsMenuItemUIAccessor menuItemUI,
Graphics g, JMenuItem menuItem, Color bgColor) {
- assert isVistaPainting();
- if (isVistaPainting()) {
+ XPStyle xp = XPStyle.getXP();
+ assert isVistaPainting(xp);
+ if (isVistaPainting(xp)) {
int menuWidth = menuItem.getWidth();
int menuHeight = menuItem.getHeight();
if (menuItem.isOpaque()) {
@@ -118,7 +119,6 @@
g.fillRect(0,0, menuWidth, menuHeight);
g.setColor(oldColor);
}
- XPStyle xp = XPStyle.getXP();
Part part = menuItemUI.getPart(menuItem);
Skin skin = xp.getSkin(menuItem, part);
skin.paintSkin(g, 0 , 0,
@@ -170,8 +170,11 @@
* is it possible that in some theme some Vista parts are not defined while
* others are?
*/
- static boolean isVistaPainting() {
- XPStyle xp = XPStyle.getXP();
+ static boolean isVistaPainting(final XPStyle xp) {
return xp != null && xp.isSkinDefined(null, Part.MP_POPUPITEM);
}
+
+ static boolean isVistaPainting() {
+ return isVistaPainting(XPStyle.getXP());
+ }
}
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,8 @@
public void paint(Graphics g, JComponent c) {
Dimension s = c.getSize();
- if (WindowsMenuItemUI.isVistaPainting()) {
+ XPStyle xp = XPStyle.getXP();
+ if (WindowsMenuItemUI.isVistaPainting(xp)) {
int x = 1;
Component parent = c.getParent();
if (parent instanceof JComponent) {
@@ -67,7 +68,7 @@
x += WindowsPopupMenuUI.getGutterWidth();
}
}
- Skin skin = XPStyle.getXP().getSkin(c, Part.MP_POPUPSEPARATOR);
+ Skin skin = xp.getSkin(c, Part.MP_POPUPSEPARATOR);
int skinHeight = skin.getHeight();
int y = (s.height - skinHeight) / 2;
skin.paintSkin(g, x, y, s.width - x - 1, skinHeight, State.NORMAL);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -194,8 +194,8 @@
@Override
public void paint(Graphics g, JComponent c) {
- if (WindowsMenuItemUI.isVistaPainting()) {
- XPStyle xp = XPStyle.getXP();
+ XPStyle xp = XPStyle.getXP();
+ if (WindowsMenuItemUI.isVistaPainting(xp)) {
Skin skin = xp.getSkin(c, Part.MP_POPUPBACKGROUND);
skin.paintSkin(g, 0, 0, c.getWidth(),c.getHeight(), State.NORMAL);
int textOffset = getTextOffset(c);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -322,8 +322,9 @@
private Rectangle getFullChunkBounds(Rectangle box) {
boolean vertical = (progressBar.getOrientation() == JProgressBar.VERTICAL);
XPStyle xp = XPStyle.getXP();
- int gap = xp.getInt(progressBar, Part.PP_PROGRESS, null,
- Prop.PROGRESSSPACESIZE, 0);
+ int gap = (xp != null) ? xp.getInt(progressBar, Part.PP_PROGRESS,
+ null, Prop.PROGRESSSPACESIZE, 0)
+ : 0;
if (!vertical) {
int chunksize = box.width+gap;
@@ -338,6 +339,9 @@
boolean vertical,
int bgwidth, int bgheight) {
XPStyle xp = XPStyle.getXP();
+ if (xp == null) {
+ return;
+ }
// create a new graphics to keep drawing surface state
Graphics2D gfx = (Graphics2D)g.create();
@@ -396,6 +400,9 @@
private void paintXPBackground(Graphics g, boolean vertical,
int barRectWidth, int barRectHeight) {
XPStyle xp = XPStyle.getXP();
+ if (xp == null) {
+ return;
+ }
Part part = vertical ? Part.PP_BARVERT : Part.PP_BAR;
Skin skin = xp.getSkin(progressBar, part);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -215,7 +215,6 @@
}
private Part getXPThumbPart() {
- XPStyle xp = XPStyle.getXP();
Part part;
boolean vertical = (slider.getOrientation() == JSlider.VERTICAL);
boolean leftToRight = slider.getComponentOrientation().isLeftToRight();
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,9 @@
private void paintXPBackground(Graphics g, JComponent c) {
XPStyle xp = XPStyle.getXP();
+ if (xp == null) {
+ return;
+ }
Skin skin = xp.getSkin(c, Part.EP_EDIT);
State state = getXPState(c);
skin.paintSkin(g, 0, 0, c.getWidth(), c.getHeight(), state);
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -91,9 +91,10 @@
this.column = column;
this.hasRollover = (column == getRolloverColumn());
if (skin == null) {
- skin = XPStyle.getXP().getSkin(header, Part.HP_HEADERITEM);
+ XPStyle xp = XPStyle.getXP();
+ skin = (xp != null) ? xp.getSkin(header, Part.HP_HEADERITEM) : null;
}
- Insets margins = skin.getContentMargin();
+ Insets margins = (skin != null) ? skin.getContentMargin() : null;
Border border = null;
int contentTop = 0;
int contentLeft = 0;
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java Wed Jul 05 19:50:57 2017 +0200
@@ -115,7 +115,7 @@
}
}
}
- return xp;
+ return ThemeReader.isXPStyleEnabled() ? xp : null;
}
static boolean isVista() {
@@ -180,9 +180,10 @@
* should probably be cached there instead of here.
*/
Dimension getDimension(Component c, Part part, State state, Prop prop) {
- return ThemeReader.getPosition(part.getControlName(c), part.getValue(),
- State.getValue(part, state),
- prop.getValue());
+ Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(),
+ State.getValue(part, state),
+ prop.getValue());
+ return (d != null) ? d : new Dimension();
}
/** Get a named <code>Point</code> (e.g. a location or an offset) value
@@ -199,11 +200,7 @@
Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(),
State.getValue(part, state),
prop.getValue());
- if (d != null) {
- return new Point(d.width, d.height);
- } else {
- return null;
- }
+ return (d != null) ? new Point(d.width, d.height) : new Point();
}
/** Get a named <code>Insets</code> value from the current style
@@ -217,9 +214,10 @@
* The return value is already cached in those places.
*/
Insets getMargin(Component c, Part part, State state, Prop prop) {
- return ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(),
- State.getValue(part, state),
- prop.getValue());
+ Insets insets = ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(),
+ State.getValue(part, state),
+ prop.getValue());
+ return (insets != null) ? insets : new Insets(0, 0, 0, 0);
}
@@ -349,7 +347,7 @@
// special casing for comboboxes.
// there may be more special cases in the future
if(c instanceof JComboBox) {
- JComboBox cb = (JComboBox)c;
+ JComboBox<?> cb = (JComboBox)c;
// note. in the future this should be replaced with a call
// to BasicLookAndFeel.getUIOfType()
if(cb.getUI() instanceof WindowsComboBoxUI) {
@@ -509,16 +507,17 @@
int boundingWidth = 100;
int boundingHeight = 100;
- return ThemeReader.getThemeBackgroundContentMargins(
+ Insets insets = ThemeReader.getThemeBackgroundContentMargins(
part.getControlName(null), part.getValue(),
0, boundingWidth, boundingHeight);
+ return (insets != null) ? insets : new Insets(0, 0, 0, 0);
}
private int getWidth(State state) {
if (size == null) {
size = getPartSize(part, state);
}
- return size.width;
+ return (size != null) ? size.width : 0;
}
int getWidth() {
@@ -529,7 +528,7 @@
if (size == null) {
size = getPartSize(part, state);
}
- return size.height;
+ return (size != null) ? size.height : 0;
}
int getHeight() {
@@ -586,6 +585,9 @@
* @param state which state to paint
*/
void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state) {
+ if (XPStyle.getXP() == null) {
+ return;
+ }
if (ThemeReader.isGetThemeTransitionDurationDefined()
&& component instanceof JComponent
&& SwingUtilities.getAncestorOfClass(CellRendererPane.class,
@@ -611,6 +613,9 @@
* @param state which state to paint
*/
void paintSkinRaw(Graphics g, int dx, int dy, int dw, int dh, State state) {
+ if (XPStyle.getXP() == null) {
+ return;
+ }
skinPainter.paint(null, g, dx, dy, dw, dh, this, state);
}
@@ -629,6 +634,9 @@
*/
void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state,
boolean borderFill) {
+ if (XPStyle.getXP() == null) {
+ return;
+ }
if(borderFill && "borderfill".equals(getTypeEnumName(component, part,
state, Prop.BGTYPE))) {
return;
@@ -684,7 +692,7 @@
public GlyphButton(Component parent, Part part) {
XPStyle xp = getXP();
- skin = xp.getSkin(parent, part);
+ skin = xp != null ? xp.getSkin(parent, part) : null;
setBorder(null);
setContentAreaFilled(false);
setMinimumSize(new Dimension(5, 5));
@@ -709,13 +717,16 @@
}
public void paintComponent(Graphics g) {
+ if (XPStyle.getXP() == null || skin == null) {
+ return;
+ }
Dimension d = getSize();
skin.paintSkin(g, 0, 0, d.width, d.height, getState());
}
public void setPart(Component parent, Part part) {
XPStyle xp = getXP();
- skin = xp.getSkin(parent, part);
+ skin = xp != null ? xp.getSkin(parent, part) : null;
revalidate();
repaint();
}
--- a/jdk/src/share/classes/com/sun/jmx/remote/security/SubjectDelegator.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/remote/security/SubjectDelegator.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -34,22 +34,14 @@
import javax.management.remote.SubjectDelegationPermission;
-import com.sun.jmx.remote.util.CacheMap;
-import java.util.ArrayList;
-import java.util.Collection;
+import java.util.*;
public class SubjectDelegator {
- private static final int PRINCIPALS_CACHE_SIZE = 10;
- private static final int ACC_CACHE_SIZE = 10;
-
- private CacheMap<Subject, Principal[]> principalsCache;
- private CacheMap<Subject, AccessControlContext> accCache;
-
/* Return the AccessControlContext appropriate to execute an
operation on behalf of the delegatedSubject. If the
authenticatedAccessControlContext does not have permission to
delegate to that subject, throw SecurityException. */
- public synchronized AccessControlContext
+ public AccessControlContext
delegatedContext(AccessControlContext authenticatedACC,
Subject delegatedSubject,
boolean removeCallerContext)
@@ -58,56 +50,14 @@
if (System.getSecurityManager() != null && authenticatedACC == null) {
throw new SecurityException("Illegal AccessControlContext: null");
}
- if (principalsCache == null || accCache == null) {
- principalsCache =
- new CacheMap<>(PRINCIPALS_CACHE_SIZE);
- accCache =
- new CacheMap<>(ACC_CACHE_SIZE);
- }
-
- // Retrieve the principals for the given
- // delegated subject from the cache
- //
- Principal[] delegatedPrincipals = principalsCache.get(delegatedSubject);
-
- // Convert the set of principals stored in the
- // delegated subject into an array of principals
- // and store it in the cache
- //
- if (delegatedPrincipals == null) {
- delegatedPrincipals =
- delegatedSubject.getPrincipals().toArray(new Principal[0]);
- principalsCache.put(delegatedSubject, delegatedPrincipals);
- }
-
- // Retrieve the access control context for the
- // given delegated subject from the cache
- //
- AccessControlContext delegatedACC = accCache.get(delegatedSubject);
-
- // Build the access control context to be used
- // when executing code as the delegated subject
- // and store it in the cache
- //
- if (delegatedACC == null) {
- if (removeCallerContext) {
- delegatedACC =
- JMXSubjectDomainCombiner.getDomainCombinerContext(
- delegatedSubject);
- } else {
- delegatedACC =
- JMXSubjectDomainCombiner.getContext(delegatedSubject);
- }
- accCache.put(delegatedSubject, delegatedACC);
- }
// Check if the subject delegation permission allows the
// authenticated subject to assume the identity of each
// principal in the delegated subject
//
- final Principal[] dp = delegatedPrincipals;
- final Collection<Permission> permissions = new ArrayList<>(dp.length);
- for(Principal p : dp) {
+ Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
+ final Collection<Permission> permissions = new ArrayList<>(ps.size());
+ for(Principal p : ps) {
final String pname = p.getClass().getName() + "." + p.getName();
permissions.add(new SubjectDelegationPermission(pname));
}
@@ -122,7 +72,15 @@
};
AccessController.doPrivileged(action, authenticatedACC);
- return delegatedACC;
+ return getDelegatedAcc(delegatedSubject, removeCallerContext);
+ }
+
+ private AccessControlContext getDelegatedAcc(Subject delegatedSubject, boolean removeCallerContext) {
+ if (removeCallerContext) {
+ return JMXSubjectDomainCombiner.getDomainCombinerContext(delegatedSubject);
+ } else {
+ return JMXSubjectDomainCombiner.getContext(delegatedSubject);
+ }
}
/**
@@ -137,11 +95,9 @@
public static synchronized boolean
checkRemoveCallerContext(Subject subject) {
try {
- final Principal[] dp =
- subject.getPrincipals().toArray(new Principal[0]);
- for (int i = 0 ; i < dp.length ; i++) {
+ for (Principal p : getSubjectPrincipals(subject)) {
final String pname =
- dp[i].getClass().getName() + "." + dp[i].getName();
+ p.getClass().getName() + "." + p.getName();
final Permission sdp =
new SubjectDelegationPermission(pname);
AccessController.checkPermission(sdp);
@@ -151,4 +107,19 @@
}
return true;
}
+
+ /**
+ * Retrieves the {@linkplain Subject} principals
+ * @param subject The subject
+ * @return If the {@code Subject} is immutable it will return the principals directly.
+ * If the {@code Subject} is mutable it will create an unmodifiable copy.
+ */
+ private static Collection<Principal> getSubjectPrincipals(Subject subject) {
+ if (subject.isReadOnly()) {
+ return subject.getPrincipals();
+ }
+
+ List<Principal> principals = Arrays.asList(subject.getPrincipals().toArray(new Principal[0]));
+ return Collections.unmodifiableList(principals);
+ }
}
--- a/jdk/src/share/classes/com/sun/jmx/remote/util/CacheMap.java Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,121 +0,0 @@
-/*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.jmx.remote.util;
-
-import java.lang.ref.SoftReference;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.WeakHashMap;
-
-import com.sun.jmx.mbeanserver.Util;
-
-/**
- * <p>Like WeakHashMap, except that the keys of the <em>n</em> most
- * recently-accessed entries are kept as {@link SoftReference soft
- * references}. Accessing an element means creating it, or retrieving
- * it with {@link #get(Object) get}. Because these entries are kept
- * with soft references, they will tend to remain even if their keys
- * are not referenced elsewhere. But if memory is short, they will
- * be removed.</p>
- */
-public class CacheMap<K, V> extends WeakHashMap<K, V> {
- /**
- * <p>Create a <code>CacheMap</code> that can keep up to
- * <code>nSoftReferences</code> as soft references.</p>
- *
- * @param nSoftReferences Maximum number of keys to keep as soft
- * references. Access times for {@link #get(Object) get} and
- * {@link #put(Object, Object) put} have a component that scales
- * linearly with <code>nSoftReferences</code>, so this value
- * should not be too great.
- *
- * @throws IllegalArgumentException if
- * <code>nSoftReferences</code> is negative.
- */
- public CacheMap(int nSoftReferences) {
- if (nSoftReferences < 0) {
- throw new IllegalArgumentException("nSoftReferences = " +
- nSoftReferences);
- }
- this.nSoftReferences = nSoftReferences;
- }
-
- public V put(K key, V value) {
- cache(key);
- return super.put(key, value);
- }
-
- public V get(Object key) {
- cache(Util.<K>cast(key));
- return super.get(key);
- }
-
- /* We don't override remove(Object) or try to do something with
- the map's iterators to detect removal. So we may keep useless
- entries in the soft reference list for keys that have since
- been removed. The assumption is that entries are added to the
- cache but never removed. But the behavior is not wrong if
- they are in fact removed -- the caching is just less
- performant. */
-
- private void cache(K key) {
- Iterator<SoftReference<K>> it = cache.iterator();
- while (it.hasNext()) {
- SoftReference<K> sref = it.next();
- K key1 = sref.get();
- if (key1 == null)
- it.remove();
- else if (key.equals(key1)) {
- // Move this element to the head of the LRU list
- it.remove();
- cache.add(0, sref);
- return;
- }
- }
-
- int size = cache.size();
- if (size == nSoftReferences) {
- if (size == 0)
- return; // degenerate case, equivalent to WeakHashMap
- it.remove();
- }
-
- cache.add(0, new SoftReference<K>(key));
- }
-
- /* List of soft references for the most-recently referenced keys.
- The list is in most-recently-used order, i.e. the first element
- is the most-recently referenced key. There are never more than
- nSoftReferences elements of this list.
-
- If we didn't care about J2SE 1.3 compatibility, we could use
- LinkedHashSet in conjunction with a subclass of SoftReference
- whose equals and hashCode reflect the referent. */
- private final LinkedList<SoftReference<K>> cache =
- new LinkedList<SoftReference<K>>();
- private final int nSoftReferences;
-}
--- a/jdk/src/share/classes/com/sun/jmx/snmp/EnumRowStatus.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/EnumRowStatus.java Wed Jul 05 19:50:57 2017 +0200
@@ -284,20 +284,20 @@
final static Hashtable<Integer, String> intTable = new Hashtable<>();
final static Hashtable<String, Integer> stringTable = new Hashtable<>();
static {
- intTable.put(new Integer(0), "unspecified");
- intTable.put(new Integer(3), "notReady");
- intTable.put(new Integer(6), "destroy");
- intTable.put(new Integer(2), "notInService");
- intTable.put(new Integer(5), "createAndWait");
- intTable.put(new Integer(1), "active");
- intTable.put(new Integer(4), "createAndGo");
- stringTable.put("unspecified", new Integer(0));
- stringTable.put("notReady", new Integer(3));
- stringTable.put("destroy", new Integer(6));
- stringTable.put("notInService", new Integer(2));
- stringTable.put("createAndWait", new Integer(5));
- stringTable.put("active", new Integer(1));
- stringTable.put("createAndGo", new Integer(4));
+ intTable.put(0, "unspecified");
+ intTable.put(3, "notReady");
+ intTable.put(6, "destroy");
+ intTable.put(2, "notInService");
+ intTable.put(5, "createAndWait");
+ intTable.put(1, "active");
+ intTable.put(4, "createAndGo");
+ stringTable.put("unspecified", 0);
+ stringTable.put("notReady", 3);
+ stringTable.put("destroy", 6);
+ stringTable.put("notInService", 2);
+ stringTable.put("createAndWait", 5);
+ stringTable.put("active", 1);
+ stringTable.put("createAndGo", 4);
}
--- a/jdk/src/share/classes/com/sun/jmx/snmp/Enumerated.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/Enumerated.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,7 +71,7 @@
* the method is illegal or inappropriate.
*/
public Enumerated(int valueIndex) throws IllegalArgumentException {
- if (getIntTable().get(new Integer(valueIndex)) == null) {
+ if (getIntTable().get(valueIndex) == null) {
throw new IllegalArgumentException() ;
}
value = valueIndex ;
@@ -181,7 +181,7 @@
*/
@Override
public String toString() {
- return getIntTable().get(new Integer(value)) ;
+ return getIntTable().get(value);
}
--- a/jdk/src/share/classes/com/sun/jmx/snmp/IPAcl/JJTParserState.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/IPAcl/JJTParserState.java Wed Jul 05 19:50:57 2017 +0200
@@ -100,7 +100,7 @@
void openNodeScope(Node n) {
- marks.push(new Integer(mk));
+ marks.push(mk);
mk = sp;
n.jjtOpen();
}
--- a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpCounter64.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpCounter64.java Wed Jul 05 19:50:57 2017 +0200
@@ -100,7 +100,7 @@
* @return The <CODE>Integer</CODE> representation of the value.
*/
public Integer toInteger() {
- return new Integer((int)value) ;
+ return (int)value;
}
/**
--- a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpInt.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpInt.java Wed Jul 05 19:50:57 2017 +0200
@@ -146,7 +146,7 @@
* @return The <CODE>Integer</CODE> representation of the value.
*/
public Integer toInteger() {
- return new Integer((int)value) ;
+ return (int)value;
}
/**
--- a/jdk/src/share/classes/com/sun/jmx/snmp/daemon/CommunicatorServer.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/daemon/CommunicatorServer.java Wed Jul 05 19:50:57 2017 +0200
@@ -1272,8 +1272,8 @@
message, // message
"State", // attribute name
"int", // attribute type
- new Integer(oldState), // old value
- new Integer(newState) ); // new value
+ oldState, // old value
+ newState ); // new value
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, dbgTag,
"sendStateChangeNotification","Sending AttributeChangeNotification #"
--- a/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java Wed Jul 05 19:50:57 2017 +0200
@@ -569,7 +569,7 @@
*/
@Override
public Integer getTrapPort() {
- return new Integer(trapPort) ;
+ return trapPort;
}
/**
@@ -639,7 +639,7 @@
*/
@Override
public Integer getBufferSize() {
- return new Integer(bufferSize) ;
+ return bufferSize;
}
/**
--- a/jdk/src/share/classes/com/sun/jmx/snmp/internal/SnmpLcd.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/snmp/internal/SnmpLcd.java Wed Jul 05 19:50:57 2017 +0200
@@ -43,15 +43,15 @@
public void addModelLcd(int id,
SnmpModelLcd usmlcd) {
- models.put(new Integer(id), usmlcd);
+ models.put(id, usmlcd);
}
public SnmpModelLcd getModelLcd(int id) {
- return models.get(new Integer(id));
+ return models.get(id);
}
public SnmpModelLcd removeModelLcd(int id) {
- return models.remove(new Integer(id));
+ return models.remove(id);
}
}
--- a/jdk/src/share/classes/com/sun/jndi/cosnaming/RemoteToCorba.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/cosnaming/RemoteToCorba.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -71,17 +71,10 @@
if (orig instanceof Remote) {
// Turn remote object into org.omg.CORBA.Object
- try {
- // Returns null if JRMP; let next factory try
- // CNCtx will eventually throw IllegalArgumentException if
- // no CORBA object gotten
- return
- CorbaUtils.remoteToCorba((Remote)orig, ((CNCtx)ctx)._orb);
- } catch (ClassNotFoundException e) {
- // RMI-IIOP library not available
- throw new ConfigurationException(
- "javax.rmi packages not available");
- }
+ // Returns null if JRMP; let next factory try
+ // CNCtx will eventually throw IllegalArgumentException if
+ // no CORBA object gotten
+ return CorbaUtils.remoteToCorba((Remote)orig, ((CNCtx)ctx)._orb);
}
return null; // pass and let next state factory try
}
--- a/jdk/src/share/classes/com/sun/jndi/ldap/ClientId.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/ClientId.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -86,9 +86,8 @@
try {
Class<?> socketFactoryClass =
Obj.helper.loadClass(socketFactory);
- Class<?> objClass = Class.forName("java.lang.Object");
this.sockComparator = socketFactoryClass.getMethod(
- "compare", new Class<?>[]{objClass, objClass});
+ "compare", new Class<?>[]{Object.class, Object.class});
Method getDefault = socketFactoryClass.getMethod(
"getDefault", new Class<?>[]{});
this.factory =
--- a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java Wed Jul 05 19:50:57 2017 +0200
@@ -31,6 +31,7 @@
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
+import java.net.InetSocketAddress;
import java.net.Socket;
import javax.net.ssl.SSLSocket;
@@ -42,11 +43,10 @@
import javax.naming.ldap.Control;
import java.lang.reflect.Method;
-import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import sun.misc.IOUtils;
-//import javax.net.SocketFactory;
+import javax.net.SocketFactory;
/**
* A thread that creates a connection to an LDAP server.
@@ -219,9 +219,7 @@
ce.setRootCause(realException);
throw ce;
} catch (Exception e) {
- // Class.forName() seems to do more error checking
- // and will throw IllegalArgumentException and such.
- // That's why we need to have a catch all here and
+ // We need to have a catch all here and
// ignore generic exceptions.
// Also catches all IO errors generated by socket creation.
CommunicationException ce =
@@ -238,27 +236,8 @@
/*
* Create an InetSocketAddress using the specified hostname and port number.
*/
- private Object createInetSocketAddress(String host, int port)
- throws NoSuchMethodException {
-
- try {
- Class<?> inetSocketAddressClass =
- Class.forName("java.net.InetSocketAddress");
-
- Constructor<?> inetSocketAddressCons =
- inetSocketAddressClass.getConstructor(new Class<?>[]{
- String.class, int.class});
-
- return inetSocketAddressCons.newInstance(new Object[]{
- host, new Integer(port)});
-
- } catch (ClassNotFoundException |
- InstantiationException |
- InvocationTargetException |
- IllegalAccessException e) {
- throw new NoSuchMethodException();
-
- }
+ private InetSocketAddress createInetSocketAddress(String host, int port) {
+ return new InetSocketAddress(host, port);
}
/*
@@ -279,82 +258,57 @@
// create the factory
- Class<?> socketFactoryClass = Obj.helper.loadClass(socketFactory);
+ @SuppressWarnings("unchecked")
+ Class<? extends SocketFactory> socketFactoryClass =
+ (Class<? extends SocketFactory>)Obj.helper.loadClass(socketFactory);
Method getDefault =
socketFactoryClass.getMethod("getDefault", new Class<?>[]{});
- Object factory = getDefault.invoke(null, new Object[]{});
+ SocketFactory factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
// create the socket
- Method createSocket = null;
-
if (connectTimeout > 0) {
- try {
- createSocket = socketFactoryClass.getMethod("createSocket",
- new Class<?>[]{});
+ InetSocketAddress endpoint =
+ createInetSocketAddress(host, port);
- Method connect = Socket.class.getMethod("connect",
- new Class<?>[]{Class.forName("java.net.SocketAddress"),
- int.class});
- Object endpoint = createInetSocketAddress(host, port);
-
- // unconnected socket
- socket =
- (Socket)createSocket.invoke(factory, new Object[]{});
+ // unconnected socket
+ socket = factory.createSocket();
- if (debug) {
- System.err.println("Connection: creating socket with " +
+ if (debug) {
+ System.err.println("Connection: creating socket with " +
"a timeout using supplied socket factory");
- }
+ }
- // connected socket
- connect.invoke(socket, new Object[]{
- endpoint, new Integer(connectTimeout)});
-
- } catch (NoSuchMethodException e) {
- // continue (but ignore connectTimeout)
- }
+ // connected socket
+ socket.connect(endpoint, connectTimeout);
}
+ // continue (but ignore connectTimeout)
if (socket == null) {
- createSocket = socketFactoryClass.getMethod("createSocket",
- new Class<?>[]{String.class, int.class});
-
if (debug) {
System.err.println("Connection: creating socket using " +
"supplied socket factory");
}
// connected socket
- socket = (Socket) createSocket.invoke(factory,
- new Object[]{host, new Integer(port)});
+ socket = factory.createSocket(host, port);
}
} else {
if (connectTimeout > 0) {
- try {
- Constructor<Socket> socketCons =
- Socket.class.getConstructor(new Class<?>[]{});
+ InetSocketAddress endpoint = createInetSocketAddress(host, port);
- Method connect = Socket.class.getMethod("connect",
- new Class<?>[]{Class.forName("java.net.SocketAddress"),
- int.class});
- Object endpoint = createInetSocketAddress(host, port);
-
- socket = socketCons.newInstance(new Object[]{});
+ socket = new Socket();
if (debug) {
System.err.println("Connection: creating socket with " +
"a timeout");
}
- connect.invoke(socket, new Object[]{
- endpoint, new Integer(connectTimeout)});
+ socket.connect(endpoint, connectTimeout);
+ }
- } catch (NoSuchMethodException e) {
- // continue (but ignore connectTimeout)
- }
- }
+ // continue (but ignore connectTimeout)
if (socket == null) {
if (debug) {
--- a/jdk/src/share/classes/com/sun/jndi/ldap/LdapPoolManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/LdapPoolManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -406,7 +406,7 @@
try {
return Integer.getInteger(propName, defVal);
} catch (SecurityException e) {
- return new Integer(defVal);
+ return defVal;
}
}
});
--- a/jdk/src/share/classes/com/sun/jndi/ldap/VersionHelper.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/VersionHelper.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,32 +30,10 @@
abstract class VersionHelper {
- private static VersionHelper helper = null;
+ private static final VersionHelper helper = new VersionHelper12();
VersionHelper() {} // Disallow anyone from creating one of these.
- static {
- try {
- Class.forName("java.net.URLClassLoader"); // 1.2 test
- Class.forName("java.security.PrivilegedAction"); // 1.2 test
- helper = (VersionHelper)
- Class.forName(
- "com.sun.jndi.ldap.VersionHelper12").newInstance();
- } catch (Exception e) {
- }
-
- // Use 1.1 helper if 1.2 test fails, or if we cannot create 1.2 helper
- if (helper == null) {
- try {
- helper = (VersionHelper)
- Class.forName(
- "com.sun.jndi.ldap.VersionHelper11").newInstance();
- } catch (Exception e) {
- // should never happen
- }
- }
- }
-
static VersionHelper getVersionHelper() {
return helper;
}
--- a/jdk/src/share/classes/com/sun/jndi/toolkit/corba/CorbaUtils.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/toolkit/corba/CorbaUtils.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,16 +28,18 @@
// Needed for RMI/IIOP
import java.rmi.Remote;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
+import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Enumeration;
+import java.applet.Applet;
import org.omg.CORBA.ORB;
import javax.naming.Context;
import javax.naming.ConfigurationException;
+import javax.rmi.CORBA.Stub;
+import javax.rmi.PortableRemoteObject;
/**
* Contains utilities for performing CORBA-related tasks:
@@ -76,71 +78,43 @@
* @param orb The non-null ORB to connect the remote object to
* @return The CORBA Object for remoteObj; null if <tt>remoteObj</tt>
* is a JRMP implementation or JRMP stub.
- * @exception ClassNotFoundException The RMI-IIOP package is not available
* @exception ConfigurationException The CORBA Object cannot be obtained
* because of configuration problems.
*/
public static org.omg.CORBA.Object remoteToCorba(Remote remoteObj, ORB orb)
- throws ClassNotFoundException, ConfigurationException {
- synchronized (CorbaUtils.class) {
- if (toStubMethod == null) {
- initMethodHandles();
- }
- }
+ throws ConfigurationException {
// First, get remoteObj's stub
// javax.rmi.CORBA.Stub stub = PortableRemoteObject.toStub(remoteObj);
- java.lang.Object stub;
+ Remote stub;
try {
- stub = toStubMethod.invoke(null, new java.lang.Object[]{remoteObj});
-
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- // realException.printStackTrace();
-
+ stub = PortableRemoteObject.toStub(remoteObj);
+ } catch (Throwable t) {
ConfigurationException ce = new ConfigurationException(
"Problem with PortableRemoteObject.toStub(); object not exported or stub not found");
- ce.setRootCause(realException);
- throw ce;
-
- } catch (IllegalAccessException e) {
- ConfigurationException ce = new ConfigurationException(
- "Cannot invoke javax.rmi.PortableRemoteObject.toStub(java.rmi.Remote)");
-
- ce.setRootCause(e);
+ ce.setRootCause(t);
throw ce;
}
// Next, make sure that the stub is javax.rmi.CORBA.Stub
- if (!corbaStubClass.isInstance(stub)) {
+ if (!(stub instanceof Stub)) {
return null; // JRMP implementation or JRMP stub
}
// Next, make sure that the stub is connected
- // Invoke stub.connect(orb)
try {
- connectMethod.invoke(stub, new java.lang.Object[]{orb});
-
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- // realException.printStackTrace();
-
- if (!(realException instanceof java.rmi.RemoteException)) {
- ConfigurationException ce = new ConfigurationException(
- "Problem invoking javax.rmi.CORBA.Stub.connect()");
- ce.setRootCause(realException);
- throw ce;
- }
+ ((Stub) stub).connect(orb);
+ } catch (RemoteException e) {
// ignore RemoteException because stub might have already
// been connected
- } catch (IllegalAccessException e) {
+ } catch (Throwable t) {
ConfigurationException ce = new ConfigurationException(
- "Cannot invoke javax.rmi.CORBA.Stub.connect()");
- ce.setRootCause(e);
+ "Problem invoking javax.rmi.CORBA.Stub.connect()");
+ ce.setRootCause(t);
throw ce;
}
// Finally, return stub
@@ -192,83 +166,13 @@
// Get Applet from environment
if (env != null) {
- Object applet = env.get(Context.APPLET);
+ Applet applet = (Applet) env.get(Context.APPLET);
if (applet != null) {
- // Create ORBs for an applet
- return initAppletORB(applet, orbProp);
+ // Create ORBs using applet and orbProp
+ return ORB.init(applet, orbProp);
}
}
- // Create ORBs using orbProp for a standalone application
return ORB.init(new String[0], orbProp);
}
-
- /**
- * This method returns a new ORB instance for the given applet
- * without creating a static dependency on java.applet.
- */
- private static ORB initAppletORB(Object applet, Properties orbProp) {
- try {
- Class<?> appletClass = Class.forName("java.applet.Applet", true, null);
- if (!appletClass.isInstance(applet)) {
- throw new ClassCastException(applet.getClass().getName());
- }
-
- // invoke the static method ORB.init(applet, orbProp);
- Method method = ORB.class.getMethod("init", appletClass, Properties.class);
- return (ORB) method.invoke(null, applet, orbProp);
- } catch (ClassNotFoundException e) {
- // java.applet.Applet doesn't exist and the applet parameter is
- // non-null; so throw CCE
- throw new ClassCastException(applet.getClass().getName());
- } catch (NoSuchMethodException e) {
- throw new AssertionError(e);
- } catch (InvocationTargetException e) {
- Throwable cause = e.getCause();
- if (cause instanceof RuntimeException) {
- throw (RuntimeException) cause;
- } else if (cause instanceof Error) {
- throw (Error) cause;
- }
- throw new AssertionError(e);
- } catch (IllegalAccessException iae) {
- throw new AssertionError(iae);
- }
- }
-
- // Fields used for reflection of RMI-IIOP
- private static Method toStubMethod = null;
- private static Method connectMethod = null;
- private static Class<?> corbaStubClass = null;
- /**
- * Initializes reflection method handles for RMI-IIOP.
- * @exception ClassNotFoundException javax.rmi.CORBA.* not available
- */
- private static void initMethodHandles() throws ClassNotFoundException {
- // Get javax.rmi.CORBA.Stub class
- corbaStubClass = Class.forName("javax.rmi.CORBA.Stub");
-
- // Get javax.rmi.CORBA.Stub.connect(org.omg.CORBA.ORB) method
-
- try {
- connectMethod = corbaStubClass.getMethod("connect",
- new Class<?>[] {org.omg.CORBA.ORB.class});
- } catch (NoSuchMethodException e) {
- throw new IllegalStateException(
- "No method definition for javax.rmi.CORBA.Stub.connect(org.omg.CORBA.ORB)");
- }
-
- // Get javax.rmi.PortableRemoteObject class
- Class<?> proClass = Class.forName("javax.rmi.PortableRemoteObject");
-
- // Get javax.rmi.PortableRemoteObject.toStub(java.rmi.Remote) method
- try {
- toStubMethod = proClass.getMethod("toStub",
- new Class<?>[] {java.rmi.Remote.class});
-
- } catch (NoSuchMethodException e) {
- throw new IllegalStateException(
-"No method definition for javax.rmi.PortableRemoteObject.toStub(java.rmi.Remote)");
- }
- }
}
--- a/jdk/src/share/classes/com/sun/security/sasl/CramMD5Base.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/CramMD5Base.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
+import java.util.Arrays;
import java.util.logging.Logger;
/**
@@ -159,7 +160,7 @@
MessageDigest md5 = MessageDigest.getInstance("MD5");
/* digest the key if longer than 64 bytes */
- if (key.length > 64) {
+ if (key.length > MD5_BLOCKSIZE) {
key = md5.digest(key);
}
@@ -169,13 +170,9 @@
int i;
/* store key in pads */
- for (i = 0; i < MD5_BLOCKSIZE; i++) {
- for ( ; i < key.length; i++) {
- ipad[i] = key[i];
- opad[i] = key[i];
- }
- ipad[i] = 0x00;
- opad[i] = 0x00;
+ for (i = 0; i < key.length; i++) {
+ ipad[i] = key[i];
+ opad[i] = key[i];
}
/* XOR key with pads */
@@ -207,6 +204,11 @@
}
}
+ Arrays.fill(ipad, (byte)0);
+ Arrays.fill(opad, (byte)0);
+ ipad = null;
+ opad = null;
+
return (digestString.toString());
}
--- a/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java Wed Jul 05 19:50:57 2017 +0200
@@ -1410,7 +1410,7 @@
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST,
"DIGEST33:Expecting sequence num: {0}",
- new Integer(peerSeqNum));
+ peerSeqNum);
traceOutput(DP_CLASS_NAME, "unwrap", "DIGEST34:incoming: ",
encryptedMsg);
}
--- a/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Client.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Client.java Wed Jul 05 19:50:57 2017 +0200
@@ -439,7 +439,7 @@
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "DIGEST61:Raw send size: {0}",
- new Integer(rawSendSize));
+ rawSendSize);
}
}
--- a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java Wed Jul 05 19:50:57 2017 +0200
@@ -275,9 +275,9 @@
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"KRB5CLNT07:Client max recv size: {0}; server max recv size: {1}; rawSendSize: {2}",
- new Object[] {new Integer(recvMaxBufSize),
- new Integer(srvMaxBufSize),
- new Integer(rawSendSize)});
+ new Object[] {recvMaxBufSize,
+ srvMaxBufSize,
+ rawSendSize});
}
// Construct negotiated security layers and client's max
--- a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java Wed Jul 05 19:50:57 2017 +0200
@@ -222,7 +222,7 @@
logger.log(Level.FINE,
"KRB5SRV06:Supported protections: {0}; recv max buf size: {1}",
new Object[]{allQop,
- new Integer(recvMaxBufSize)});
+ recvMaxBufSize});
}
handshakeStage = 2; // progress to next stage
@@ -293,9 +293,9 @@
Boolean.valueOf(integrity)});
logger.log(Level.FINE,
"KRB5SRV11:Client max recv size: {0}; server max send size: {1}; rawSendSize: {2}",
- new Object[] {new Integer(clntMaxBufSize),
- new Integer(sendMaxBufSize),
- new Integer(rawSendSize)});
+ new Object[] {clntMaxBufSize,
+ sendMaxBufSize,
+ rawSendSize});
}
// Get authorization identity, if any
--- a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -286,7 +286,7 @@
// Message id supplied by caller as part of traceTag
logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
- new Object[] {traceTag, new Integer(origlen), content});
+ new Object[] {traceTag, origlen, content});
} catch (Exception e) {
logger.logp(Level.WARNING, srcClass, srcMethod,
"SASLIMPL09:Error generating trace output: {0}", e);
--- a/jdk/src/share/classes/com/sun/tools/example/debug/gui/ContextManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/example/debug/gui/ContextManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -211,7 +211,7 @@
}
private void setCurrentFrameIndex(ThreadInfo tinfo, int index) {
- tinfo.setUserObject(new Integer(index));
+ tinfo.setUserObject(index);
//### In fact, the value may not have changed at this point.
//### We need to signal that the user attempted to change it,
//### however, so that the selection can be "warped" to the
--- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/Commands.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/Commands.java Wed Jul 05 19:50:57 2017 +0200
@@ -84,7 +84,7 @@
MessageOutput.println("Current thread isnt suspended.");
} catch (ArrayIndexOutOfBoundsException e) {
MessageOutput.println("Requested stack frame is no longer active:",
- new Object []{new Integer(stackFrame)});
+ new Object []{stackFrame});
}
}
MessageOutput.printPrompt();
@@ -942,14 +942,14 @@
}
if (pc != -1) {
MessageOutput.println("stack frame dump with pc",
- new Object [] {new Integer(frameNumber + 1),
+ new Object [] {(frameNumber + 1),
meth.declaringType().name(),
meth.name(),
methodInfo,
Long.valueOf(pc)});
} else {
MessageOutput.println("stack frame dump",
- new Object [] {new Integer(frameNumber + 1),
+ new Object [] {(frameNumber + 1),
meth.declaringType().name(),
meth.name(),
methodInfo});
@@ -2093,8 +2093,8 @@
VirtualMachineManager vmm) {
MessageOutput.println("minus version",
new Object [] { debuggerName,
- new Integer(vmm.majorInterfaceVersion()),
- new Integer(vmm.minorInterfaceVersion()),
+ vmm.majorInterfaceVersion(),
+ vmm.minorInterfaceVersion(),
System.getProperty("java.version")});
if (Env.connection() != null) {
try {
--- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTY.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTY.java Wed Jul 05 19:50:57 2017 +0200
@@ -241,7 +241,7 @@
}
if (line != null) {
MessageOutput.println("source line number and line",
- new Object [] {new Integer(loc.lineNumber()),
+ new Object [] {loc.lineNumber(),
line});
}
}
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaLazyReadObject.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaLazyReadObject.java Wed Jul 05 19:50:57 2017 +0200
@@ -100,7 +100,7 @@
// make Integer or Long for given object ID
protected static Number makeId(long id) {
if ((id & ~Snapshot.SMALL_ID_MASK) == 0) {
- return new Integer((int)id);
+ return (int)id;
} else {
return id;
}
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/model/Snapshot.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/model/Snapshot.java Wed Jul 05 19:50:57 2017 +0200
@@ -581,7 +581,7 @@
// Internals only below this point
private Number makeId(long id) {
if (identifierSize == 4) {
- return new Integer((int)id);
+ return (int)id;
} else {
return id;
}
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/parser/HprofReader.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/parser/HprofReader.java Wed Jul 05 19:50:57 2017 +0200
@@ -227,7 +227,7 @@
String nm = getNameFromID(classNameID).replace('/', '.');
classNameFromObjectID.put(classIdI, nm);
if (classNameFromSerialNo != null) {
- classNameFromSerialNo.put(new Integer(serialNo), nm);
+ classNameFromSerialNo.put(serialNo, nm);
}
break;
}
@@ -297,7 +297,7 @@
String methodSig = getNameFromID(readID());
String sourceFile = getNameFromID(readID());
int classSer = in.readInt();
- String className = classNameFromSerialNo.get(new Integer(classSer));
+ String className = classNameFromSerialNo.get(classSer);
int lineNumber = in.readInt();
if (lineNumber < StackFrame.LINE_NUMBER_NATIVE) {
warn("Weird stack frame line number: " + lineNumber);
@@ -324,7 +324,7 @@
throw new IOException("Stack frame " + toHex(fid) + " not found");
}
}
- stackTraces.put(new Integer(serialNo),
+ stackTraces.put(serialNo,
new StackTrace(frames));
}
break;
@@ -404,7 +404,7 @@
int threadSeq = in.readInt();
int stackSeq = in.readInt();
bytesLeft -= identifierSize + 8;
- threadObjects.put(new Integer(threadSeq),
+ threadObjects.put(threadSeq,
new ThreadObject(id, stackSeq));
break;
}
@@ -610,7 +610,7 @@
private ThreadObject getThreadObjectFromSequence(int threadSeq)
throws IOException {
- ThreadObject to = threadObjects.get(new Integer(threadSeq));
+ ThreadObject to = threadObjects.get(threadSeq);
if (to == null) {
throw new IOException("Thread " + threadSeq +
" not found for JNI local ref");
@@ -638,7 +638,7 @@
if (stackTraces == null) {
return null;
}
- StackTrace result = stackTraces.get(new Integer(ser));
+ StackTrace result = stackTraces.get(ser);
if (result == null) {
warn("Stack trace not found for serial # " + ser);
}
--- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/ObjectQuery.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/ObjectQuery.java Wed Jul 05 19:50:57 2017 +0200
@@ -99,7 +99,7 @@
final JavaField[] fields = obj.getClazz().getFieldsForInstance();
Integer[] hack = new Integer[things.length];
for (int i = 0; i < things.length; i++) {
- hack[i] = new Integer(i);
+ hack[i] = i;
}
ArraySorter.sort(hack, new Comparer() {
public int compare(Object lhs, Object rhs) {
--- a/jdk/src/share/classes/com/sun/tools/jdi/ConcreteMethodImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/jdi/ConcreteMethodImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -143,7 +143,7 @@
* Find the locations which match the line number
* passed in.
*/
- List<Location> list = info.lineMapper.get(new Integer(lineNumber));
+ List<Location> list = info.lineMapper.get(lineNumber);
if (list == null) {
list = new ArrayList<Location>(0);
@@ -329,7 +329,7 @@
lineLocations.add(loc);
// Add to the line -> locations map
- Integer key = new Integer(lineNumber);
+ Integer key = lineNumber;
List<Location> mappedLocs = lineMapper.get(key);
if (mappedLocs == null) {
mappedLocs = new ArrayList<Location>(1);
@@ -399,7 +399,7 @@
lineLocations.add(loc);
// Add to the line -> locations map
- Integer key = new Integer(lineNumber);
+ Integer key = lineNumber;
List<Location> mappedLocs = lineMapper.get(key);
if (mappedLocs == null) {
mappedLocs = new ArrayList<Location>(1);
--- a/jdk/src/share/classes/com/sun/tools/jdi/ReferenceTypeImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tools/jdi/ReferenceTypeImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -529,7 +529,7 @@
* to filter that ordered collection.
*/
List<Method> list = allMethods();
- list.retainAll(map.values());
+ list.retainAll(new HashSet<Method>(map.values()));
return list;
}
--- a/jdk/src/share/classes/java/awt/Component.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Component.java Wed Jul 05 19:50:57 2017 +0200
@@ -67,7 +67,6 @@
import sun.awt.ConstrainableGraphics;
import sun.awt.SubRegionShowable;
import sun.awt.SunToolkit;
-import sun.awt.WindowClosingListener;
import sun.awt.CausedFocusEvent;
import sun.awt.EmbeddedFrame;
import sun.awt.dnd.SunDropTargetEvent;
@@ -544,8 +543,6 @@
transient MouseWheelListener mouseWheelListener;
transient InputMethodListener inputMethodListener;
- transient RuntimeException windowClosingException = null;
-
/** Internal, constants for serialization */
final static String actionListenerK = "actionL";
final static String adjustmentListenerK = "adjustmentL";
@@ -4959,16 +4956,6 @@
}
break;
- case WindowEvent.WINDOW_CLOSING:
- if (toolkit instanceof WindowClosingListener) {
- windowClosingException = ((WindowClosingListener)
- toolkit).windowClosingNotify((WindowEvent)e);
- if (checkWindowClosingException()) {
- return;
- }
- }
- break;
-
default:
break;
}
@@ -5024,21 +5011,6 @@
}
/*
- * 8. Special handling for 4061116 : Hook for browser to close modal
- * dialogs.
- */
- if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) {
- if (toolkit instanceof WindowClosingListener) {
- windowClosingException =
- ((WindowClosingListener)toolkit).
- windowClosingDelivered((WindowEvent)e);
- if (checkWindowClosingException()) {
- return;
- }
- }
- }
-
- /*
* 9. Allow the peer to process the event.
* Except KeyEvents, they will be processed by peer after
* all KeyEventPostProcessors
@@ -5145,20 +5117,6 @@
return false;
}
- boolean checkWindowClosingException() {
- if (windowClosingException != null) {
- if (this instanceof Dialog) {
- ((Dialog)this).interruptBlocking();
- } else {
- windowClosingException.fillInStackTrace();
- windowClosingException.printStackTrace();
- windowClosingException = null;
- }
- return true;
- }
- return false;
- }
-
boolean areInputMethodsEnabled() {
// in 1.2, we assume input method support is required for all
// components that handle key events, but components can turn off
--- a/jdk/src/share/classes/java/awt/Container.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Container.java Wed Jul 05 19:50:57 2017 +0200
@@ -2910,17 +2910,10 @@
}
}
- Runnable pumpEventsForHierarchy = new Runnable() {
- public void run() {
- EventDispatchThread dispatchThread =
- (EventDispatchThread)Thread.currentThread();
- dispatchThread.pumpEventsForHierarchy(
- new Conditional() {
- public boolean evaluate() {
- return ((windowClosingException == null) && (nativeContainer.modalComp != null)) ;
- }
- }, Container.this);
- }
+ Runnable pumpEventsForHierarchy = () -> {
+ EventDispatchThread dispatchThread = (EventDispatchThread)Thread.currentThread();
+ dispatchThread.pumpEventsForHierarchy(() -> nativeContainer.modalComp != null,
+ Container.this);
};
if (EventQueue.isDispatchThread()) {
@@ -2938,8 +2931,7 @@
postEvent(new PeerEvent(this,
pumpEventsForHierarchy,
PeerEvent.PRIORITY_EVENT));
- while ((windowClosingException == null) &&
- (nativeContainer.modalComp != null))
+ while (nativeContainer.modalComp != null)
{
try {
getTreeLock().wait();
@@ -2949,10 +2941,6 @@
}
}
}
- if (windowClosingException != null) {
- windowClosingException.fillInStackTrace();
- throw windowClosingException;
- }
if (predictedFocusOwner != null) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
dequeueKeyEvents(time, predictedFocusOwner);
--- a/jdk/src/share/classes/java/awt/Dialog.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Dialog.java Wed Jul 05 19:50:57 2017 +0200
@@ -40,6 +40,7 @@
import sun.awt.util.IdentityArrayList;
import sun.awt.util.IdentityLinkedList;
import java.security.AccessControlException;
+import java.util.function.BooleanSupplier;
/**
* A Dialog is a top-level window with a title and a border
@@ -1044,13 +1045,6 @@
predictedFocusOwner = getMostRecentFocusOwner();
if (conditionalShow(predictedFocusOwner, time)) {
modalFilter = ModalEventFilter.createFilterForDialog(this);
- final Conditional cond = new Conditional() {
- @Override
- public boolean evaluate() {
- return windowClosingException == null;
- }
- };
-
// if this dialog is toolkit-modal, the filter should be added
// to all EDTs (for all AppContexts)
if (modalityType == ModalityType.TOOLKIT_MODAL) {
@@ -1063,10 +1057,7 @@
EventQueue eventQueue = (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY);
// it may occur that EDT for appContext hasn't been started yet, so
// we post an empty invocation event to trigger EDT initialization
- Runnable createEDT = new Runnable() {
- public void run() {};
- };
- eventQueue.postEvent(new InvocationEvent(this, createEDT));
+ eventQueue.postEvent(new InvocationEvent(this, () -> {}));
EventDispatchThread edt = eventQueue.getDispatchThread();
edt.addEventFilter(modalFilter);
}
@@ -1075,12 +1066,8 @@
modalityPushed();
try {
final EventQueue eventQueue = AccessController.doPrivileged(
- new PrivilegedAction<EventQueue>() {
- public EventQueue run() {
- return Toolkit.getDefaultToolkit().getSystemEventQueue();
- }
- });
- secondaryLoop = eventQueue.createSecondaryLoop(cond, modalFilter, 0);
+ (PrivilegedAction<EventQueue>) Toolkit.getDefaultToolkit()::getSystemEventQueue);
+ secondaryLoop = eventQueue.createSecondaryLoop(() -> true, modalFilter, 0);
if (!secondaryLoop.enter()) {
secondaryLoop = null;
}
@@ -1102,11 +1089,6 @@
edt.removeEventFilter(modalFilter);
}
}
-
- if (windowClosingException != null) {
- windowClosingException.fillInStackTrace();
- throw windowClosingException;
- }
}
} finally {
if (predictedFocusOwner != null) {
@@ -1134,16 +1116,6 @@
}
}
- void interruptBlocking() {
- if (isModal()) {
- disposeImpl();
- } else if (windowClosingException != null) {
- windowClosingException.fillInStackTrace();
- windowClosingException.printStackTrace();
- windowClosingException = null;
- }
- }
-
private void hideAndDisposePreHandler() {
isInHide = true;
synchronized (getTreeLock()) {
--- a/jdk/src/share/classes/java/awt/SplashScreen.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/awt/SplashScreen.java Wed Jul 05 19:50:57 2017 +0200
@@ -245,7 +245,14 @@
public Rectangle getBounds() throws IllegalStateException {
synchronized (SplashScreen.class) {
checkVisible();
- return _getBounds(splashPtr);
+ float scale = _getScaleFactor(splashPtr);
+ Rectangle bounds = _getBounds(splashPtr);
+ assert scale > 0;
+ if (scale > 0 && scale != 1) {
+ bounds.setSize((int) (bounds.getWidth() / scale),
+ (int) (bounds.getWidth() / scale));
+ }
+ return bounds;
}
}
@@ -287,10 +294,19 @@
public Graphics2D createGraphics() throws IllegalStateException {
synchronized (SplashScreen.class) {
if (image==null) {
- Dimension dim = getSize();
- image = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
+ // get unscaled splash image size
+ Dimension dim = _getBounds(splashPtr).getSize();
+ image = new BufferedImage(dim.width, dim.height,
+ BufferedImage.TYPE_INT_ARGB);
}
- return image.createGraphics();
+ float scale = _getScaleFactor(splashPtr);
+ Graphics2D g = image.createGraphics();
+ assert (scale > 0);
+ if (scale <= 0) {
+ scale = 1;
+ }
+ g.scale(scale, scale);
+ return g;
}
}
@@ -401,5 +417,6 @@
private native static String _getImageFileName(long splashPtr);
private native static String _getImageJarName(long SplashPtr);
private native static boolean _setImageData(long SplashPtr, byte[] data);
+ private native static float _getScaleFactor(long SplashPtr);
};
--- a/jdk/src/share/classes/java/beans/BeanDescriptor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/beans/BeanDescriptor.java Wed Jul 05 19:50:57 2017 +0200
@@ -22,10 +22,10 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-
package java.beans;
import java.lang.ref.Reference;
+import javax.swing.SwingContainer;
/**
* A BeanDescriptor provides global information about a "bean",
@@ -69,6 +69,23 @@
name = name.substring(name.indexOf('.')+1);
}
setName(name);
+
+ JavaBean annotation = beanClass.getAnnotation(JavaBean.class);
+ if (annotation != null) {
+ setPreferred(true);
+ String description = annotation.description();
+ if (!description.isEmpty()) {
+ setShortDescription(description);
+ }
+ }
+ SwingContainer container = beanClass.getAnnotation(SwingContainer.class);
+ if (container != null) {
+ setValue("isContainer", container.value());
+ String delegate = container.delegate();
+ if (!delegate.isEmpty()) {
+ setValue("containerDelegate", delegate);
+ }
+ }
}
/**
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/beans/BeanProperty.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package java.beans;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * An annotation used to specify some property-related information
+ * for the automatically generated {@link BeanInfo} classes.
+ * This annotation is not used if the annotated class
+ * has a corresponding user-defined {@code BeanInfo} class,
+ * which does not imply the automatic analysis.
+ *
+ * @see BeanInfo#getPropertyDescriptors
+ * @since 1.9
+ *
+ * @author Sergey A. Malenkov
+ */
+@Documented
+@Target({METHOD})
+@Retention(RUNTIME)
+public @interface BeanProperty {
+ /**
+ * The value that indicates whether the annotated property can be
+ * a {@link PropertyDescriptor#isBound bound} property or not.
+ * This value applies only to the beans that have the
+ * {@link PropertyChangeListener propertyChange} event set.
+ *
+ * @return {@code true} if the annotated property can be a bound property;
+ * {@code false} otherwise.
+ */
+ boolean bound() default true;
+
+ /**
+ * The value that indicates whether the annotated property is
+ * an {@link PropertyDescriptor#isExpert expert} property or not.
+ *
+ * @return {@code true} if the annotated property is an expert property;
+ * {@code false} otherwise.
+ */
+ boolean expert() default false;
+
+ /**
+ * The value that indicates whether the annotated property is
+ * a {@link PropertyDescriptor#isHidden hidden} property or not.
+ *
+ * @return {@code true} if the annotated property is a hidden property;
+ * {@code false} otherwise.
+ */
+ boolean hidden() default false;
+
+ /**
+ * The value that indicates whether the annotated property is
+ * a {@link PropertyDescriptor#isPreferred preferred} property or not.
+ *
+ * @return {@code true} if the annotated property is a preferred property;
+ * {@code false} otherwise.
+ */
+ boolean preferred() default false;
+
+ /**
+ * The value that indicates whether the annotated property is
+ * a required property or not.
+ *
+ * @return {@code true} if the annotated property is a required property;
+ * {@code false} otherwise.
+ */
+ boolean required() default false;
+
+ /**
+ * The value that indicates whether the corresponding component
+ * is repainted after the annotated property got changed or not.
+ *
+ * @return {@code true} if the corresponding component is repainted;
+ * {@code false} otherwise.
+ */
+ boolean visualUpdate() default false;
+
+ /**
+ * The {@link PropertyDescriptor#getShortDescription short description}
+ * for the {@link BeanInfo#getPropertyDescriptors descriptor}
+ * of the annotated property.
+ *
+ * @return the property description,
+ * or an empty string if the description is not set.
+ */
+ String description() default "";
+
+ /**
+ * The array of names for the public static fields
+ * that contains the valid values of the annotated property.
+ * These names are used to generate the {@code enumerationValues}
+ * {@link java.beans.BeanDescriptor#getValue feature attribute}
+ * that must contain the following items per each property value:
+ * a displayable name for the property value, the actual property value,
+ * and a Java code piece used for the code generator.
+ *
+ * @return the names of the valid values of the annotated property,
+ * or an empty array if the names are not provided.
+ */
+ String[] enumerationValues() default {};
+}
--- a/jdk/src/share/classes/java/beans/EventSetDescriptor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/beans/EventSetDescriptor.java Wed Jul 05 19:50:57 2017 +0200
@@ -22,13 +22,14 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-
package java.beans;
import java.lang.ref.Reference;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import com.sun.beans.introspect.EventSetInfo;
+
/**
* An EventSetDescriptor describes a group of events that a given Java
* bean fires.
@@ -255,6 +256,16 @@
setListenerType(listenerType);
}
+ EventSetDescriptor(String base, EventSetInfo info, Method... methods) {
+ setName(Introspector.decapitalize(base));
+ setListenerMethods(methods);
+ setAddListenerMethod(info.getAddMethod());
+ setRemoveListenerMethod(info.getRemoveMethod());
+ setGetListenerMethod(info.getGetMethod());
+ setListenerType(info.getListenerType());
+ setUnicast(info.isUnicast());
+ }
+
/**
* Creates an <TT>EventSetDescriptor</TT> from scratch using
* <TT>java.lang.reflect.MethodDescriptor</TT> and <TT>java.lang.Class</TT>
--- a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java Wed Jul 05 19:50:57 2017 +0200
@@ -22,11 +22,13 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-
package java.beans;
import java.lang.ref.Reference;
import java.lang.reflect.Method;
+import java.util.Map.Entry;
+
+import com.sun.beans.introspect.PropertyInfo;
/**
* An IndexedPropertyDescriptor describes a property that acts like an
@@ -143,27 +145,21 @@
}
/**
- * Creates <code>PropertyDescriptor</code> for the specified bean
- * with the specified name and methods to read/write the property value.
+ * Creates {@code IndexedPropertyDescriptor} from the specified property info.
*
- * @param bean the type of the target bean
- * @param base the base name of the property (the rest of the method name)
- * @param read the method used for reading the property value
- * @param write the method used for writing the property value
- * @param readIndexed the method used for reading an indexed property value
- * @param writeIndexed the method used for writing an indexed property value
- * @exception IntrospectionException if an exception occurs during introspection
+ * @param entry the key-value pair,
+ * where the {@code key} is the base name of the property (the rest of the method name)
+ * and the {@code value} is the automatically generated property info
+ * @param bound the flag indicating whether it is possible to treat this property as a bound property
*
- * @since 1.7
+ * @since 1.9
*/
- IndexedPropertyDescriptor(Class<?> bean, String base, Method read, Method write, Method readIndexed, Method writeIndexed) throws IntrospectionException {
- super(bean, base, read, write);
-
- setIndexedReadMethod0(readIndexed);
- setIndexedWriteMethod0(writeIndexed);
-
- // Type checking
- setIndexedPropertyType(findIndexedPropertyType(readIndexed, writeIndexed));
+ IndexedPropertyDescriptor(Entry<String,PropertyInfo> entry, boolean bound) {
+ super(entry, bound);
+ PropertyInfo info = entry.getValue().getIndexed();
+ setIndexedReadMethod0(info.getReadMethod());
+ setIndexedWriteMethod0(info.getWriteMethod());
+ setIndexedPropertyType(info.getPropertyType());
}
/**
--- a/jdk/src/share/classes/java/beans/Introspector.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/beans/Introspector.java Wed Jul 05 19:50:57 2017 +0200
@@ -22,32 +22,30 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-
package java.beans;
import com.sun.beans.TypeResolver;
import com.sun.beans.WeakCache;
import com.sun.beans.finder.ClassFinder;
-import com.sun.beans.finder.MethodFinder;
+import com.sun.beans.introspect.ClassInfo;
+import com.sun.beans.introspect.EventSetInfo;
+import com.sun.beans.introspect.PropertyInfo;
import java.awt.Component;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.EventListener;
import java.util.EventObject;
import java.util.List;
import java.util.TreeMap;
-import sun.misc.JavaBeansIntrospectorAccess;
import sun.misc.SharedSecrets;
import sun.reflect.misc.ReflectUtil;
@@ -122,7 +120,6 @@
private BeanInfo additionalBeanInfo[];
private boolean propertyChangeSource = false;
- private static Class<EventListener> eventListenerType = EventListener.class;
// These should be removed.
private String defaultEventName;
@@ -501,78 +498,15 @@
addPropertyDescriptors(explicitProperties);
} else {
-
// Apply some reflection to the current class.
-
- // First get an array of all the public methods at this level
- Method methodList[] = getPublicDeclaredMethods(beanClass);
-
- // Now analyze each method.
- for (int i = 0; i < methodList.length; i++) {
- Method method = methodList[i];
- if (method == null) {
- continue;
- }
- // skip static methods.
- int mods = method.getModifiers();
- if (Modifier.isStatic(mods)) {
- continue;
- }
- String name = method.getName();
- Class<?>[] argTypes = method.getParameterTypes();
- Class<?> resultType = method.getReturnType();
- int argCount = argTypes.length;
- PropertyDescriptor pd = null;
-
- if (name.length() <= 3 && !name.startsWith(IS_PREFIX)) {
- // Optimization. Don't bother with invalid propertyNames.
- continue;
- }
-
- try {
-
- if (argCount == 0) {
- if (name.startsWith(GET_PREFIX)) {
- // Simple getter
- pd = new PropertyDescriptor(this.beanClass, name.substring(3), method, null);
- } else if (resultType == boolean.class && name.startsWith(IS_PREFIX)) {
- // Boolean getter
- pd = new PropertyDescriptor(this.beanClass, name.substring(2), method, null);
- }
- } else if (argCount == 1) {
- if (int.class.equals(argTypes[0]) && name.startsWith(GET_PREFIX)) {
- pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, method, null);
- } else if (void.class.equals(resultType) && name.startsWith(SET_PREFIX)) {
- // Simple setter
- pd = new PropertyDescriptor(this.beanClass, name.substring(3), null, method);
- if (throwsException(method, PropertyVetoException.class)) {
- pd.setConstrained(true);
- }
- }
- } else if (argCount == 2) {
- if (void.class.equals(resultType) && int.class.equals(argTypes[0]) && name.startsWith(SET_PREFIX)) {
- pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, null, method);
- if (throwsException(method, PropertyVetoException.class)) {
- pd.setConstrained(true);
- }
- }
- }
- } catch (IntrospectionException ex) {
- // This happens if a PropertyDescriptor or IndexedPropertyDescriptor
- // constructor fins that the method violates details of the deisgn
- // pattern, e.g. by having an empty name, or a getter returning
- // void , or whatever.
- pd = null;
- }
-
- if (pd != null) {
- // If this class or one of its base classes is a PropertyChange
- // source, then we assume that any properties we discover are "bound".
- if (propertyChangeSource) {
- pd.setBound(true);
- }
- addPropertyDescriptor(pd);
- }
+ for (Map.Entry<String,PropertyInfo> entry : ClassInfo.get(this.beanClass).getProperties().entrySet()) {
+ addPropertyDescriptor(null != entry.getValue().getIndexed()
+ ? new IndexedPropertyDescriptor(entry, this.propertyChangeSource)
+ : new PropertyDescriptor(entry, this.propertyChangeSource));
+ }
+ JavaBean annotation = this.beanClass.getAnnotation(JavaBean.class);
+ if ((annotation != null) && !annotation.defaultProperty().isEmpty()) {
+ this.defaultPropertyName = annotation.defaultProperty();
}
}
processPropertyDescriptors();
@@ -589,7 +523,6 @@
}
}
}
-
return result;
}
@@ -1003,143 +936,24 @@
}
} else {
-
// Apply some reflection to the current class.
-
- // Get an array of all the public beans methods at this level
- Method methodList[] = getPublicDeclaredMethods(beanClass);
-
- // Find all suitable "add", "remove" and "get" Listener methods
- // The name of the listener type is the key for these hashtables
- // i.e, ActionListener
- Map<String, Method> adds = null;
- Map<String, Method> removes = null;
- Map<String, Method> gets = null;
-
- for (int i = 0; i < methodList.length; i++) {
- Method method = methodList[i];
- if (method == null) {
- continue;
- }
- // skip static methods.
- int mods = method.getModifiers();
- if (Modifier.isStatic(mods)) {
- continue;
- }
- String name = method.getName();
- // Optimization avoid getParameterTypes
- if (!name.startsWith(ADD_PREFIX) && !name.startsWith(REMOVE_PREFIX)
- && !name.startsWith(GET_PREFIX)) {
- continue;
- }
-
- if (name.startsWith(ADD_PREFIX)) {
- Class<?> returnType = method.getReturnType();
- if (returnType == void.class) {
- Type[] parameterTypes = method.getGenericParameterTypes();
- if (parameterTypes.length == 1) {
- Class<?> type = TypeResolver.erase(TypeResolver.resolveInClass(beanClass, parameterTypes[0]));
- if (Introspector.isSubclass(type, eventListenerType)) {
- String listenerName = name.substring(3);
- if (listenerName.length() > 0 &&
- type.getName().endsWith(listenerName)) {
- if (adds == null) {
- adds = new HashMap<>();
- }
- adds.put(listenerName, method);
- }
- }
- }
- }
- }
- else if (name.startsWith(REMOVE_PREFIX)) {
- Class<?> returnType = method.getReturnType();
- if (returnType == void.class) {
- Type[] parameterTypes = method.getGenericParameterTypes();
- if (parameterTypes.length == 1) {
- Class<?> type = TypeResolver.erase(TypeResolver.resolveInClass(beanClass, parameterTypes[0]));
- if (Introspector.isSubclass(type, eventListenerType)) {
- String listenerName = name.substring(6);
- if (listenerName.length() > 0 &&
- type.getName().endsWith(listenerName)) {
- if (removes == null) {
- removes = new HashMap<>();
- }
- removes.put(listenerName, method);
- }
- }
- }
+ for (Map.Entry<String,EventSetInfo> entry : ClassInfo.get(this.beanClass).getEventSets().entrySet()) {
+ // generate a list of Method objects for each of the target methods:
+ List<Method> methods = new ArrayList<>();
+ for (Method method : ClassInfo.get(entry.getValue().getListenerType()).getMethods()) {
+ if (isEventHandler(method)) {
+ methods.add(method);
}
}
- else if (name.startsWith(GET_PREFIX)) {
- Class<?>[] parameterTypes = method.getParameterTypes();
- if (parameterTypes.length == 0) {
- Class<?> returnType = FeatureDescriptor.getReturnType(beanClass, method);
- if (returnType.isArray()) {
- Class<?> type = returnType.getComponentType();
- if (Introspector.isSubclass(type, eventListenerType)) {
- String listenerName = name.substring(3, name.length() - 1);
- if (listenerName.length() > 0 &&
- type.getName().endsWith(listenerName)) {
- if (gets == null) {
- gets = new HashMap<>();
- }
- gets.put(listenerName, method);
- }
- }
- }
- }
- }
+ addEvent(new EventSetDescriptor(
+ entry.getKey(),
+ entry.getValue(),
+ methods.toArray(new Method[methods.size()])));
}
-
- if (adds != null && removes != null) {
- // Now look for matching addFooListener+removeFooListener pairs.
- // Bonus if there is a matching getFooListeners method as well.
- Iterator<String> keys = adds.keySet().iterator();
- while (keys.hasNext()) {
- String listenerName = keys.next();
- // Skip any "add" which doesn't have a matching "remove" or
- // a listener name that doesn't end with Listener
- if (removes.get(listenerName) == null || !listenerName.endsWith("Listener")) {
- continue;
- }
- String eventName = decapitalize(listenerName.substring(0, listenerName.length()-8));
- Method addMethod = adds.get(listenerName);
- Method removeMethod = removes.get(listenerName);
- Method getMethod = null;
- if (gets != null) {
- getMethod = gets.get(listenerName);
- }
- Class<?> argType = FeatureDescriptor.getParameterTypes(beanClass, addMethod)[0];
-
- // generate a list of Method objects for each of the target methods:
- Method allMethods[] = getPublicDeclaredMethods(argType);
- List<Method> validMethods = new ArrayList<>(allMethods.length);
- for (int i = 0; i < allMethods.length; i++) {
- if (allMethods[i] == null) {
- continue;
- }
-
- if (isEventHandler(allMethods[i])) {
- validMethods.add(allMethods[i]);
- }
- }
- Method[] methods = validMethods.toArray(new Method[validMethods.size()]);
-
- EventSetDescriptor esd = new EventSetDescriptor(eventName, argType,
- methods, addMethod,
- removeMethod,
- getMethod);
-
- // If the adder method throws the TooManyListenersException then it
- // is a Unicast event source.
- if (throwsException(addMethod,
- java.util.TooManyListenersException.class)) {
- esd.setUnicast(true);
- }
- addEvent(esd);
- }
- } // if (adds != null ...
+ JavaBean annotation = this.beanClass.getAnnotation(JavaBean.class);
+ if ((annotation != null) && !annotation.defaultEventSet().isEmpty()) {
+ this.defaultEventName = annotation.defaultEventSet();
+ }
}
EventSetDescriptor[] result;
if (events.size() == 0) {
@@ -1148,7 +962,6 @@
// Allocate and populate the result array.
result = new EventSetDescriptor[events.size()];
result = events.values().toArray(result);
-
// Set the default index.
if (defaultEventName != null) {
for (int i = 0; i < result.length; i++) {
@@ -1215,20 +1028,9 @@
}
} else {
-
// Apply some reflection to the current class.
-
- // First get an array of all the beans methods at this level
- Method methodList[] = getPublicDeclaredMethods(beanClass);
-
- // Now analyze each method.
- for (int i = 0; i < methodList.length; i++) {
- Method method = methodList[i];
- if (method == null) {
- continue;
- }
- MethodDescriptor md = new MethodDescriptor(method);
- addMethod(md);
+ for (Method method : ClassInfo.get(this.beanClass).getMethods()) {
+ addMethod(new MethodDescriptor(method));
}
}
@@ -1346,44 +1148,6 @@
return isSubclass(TypeResolver.erase(TypeResolver.resolveInClass(beanClass, argTypes[0])), EventObject.class);
}
- /*
- * Internal method to return *public* methods within a class.
- */
- private static Method[] getPublicDeclaredMethods(Class<?> clz) {
- // Looking up Class.getDeclaredMethods is relatively expensive,
- // so we cache the results.
- if (!ReflectUtil.isPackageAccessible(clz)) {
- return new Method[0];
- }
- synchronized (declaredMethodCache) {
- Method[] result = declaredMethodCache.get(clz);
- if (result == null) {
- result = clz.getMethods();
- for (int i = 0; i < result.length; i++) {
- Method method = result[i];
- if (!method.getDeclaringClass().equals(clz)) {
- result[i] = null; // ignore methods declared elsewhere
- }
- else {
- try {
- method = MethodFinder.findAccessibleMethod(method);
- Class<?> type = method.getDeclaringClass();
- result[i] = type.equals(clz) || type.isInterface()
- ? method
- : null; // ignore methods from superclasses
- }
- catch (NoSuchMethodException exception) {
- // commented out because of 6976577
- // result[i] = null; // ignore inaccessible methods
- }
- }
- }
- declaredMethodCache.put(clz, result);
- }
- return result;
- }
- }
-
//======================================================================
// Package private support methods.
//======================================================================
@@ -1396,17 +1160,8 @@
int argCount, Class<?> args[]) {
// For overriden methods we need to find the most derived version.
// So we start with the given class and walk up the superclass chain.
-
- Method method = null;
-
for (Class<?> cl = start; cl != null; cl = cl.getSuperclass()) {
- Method methods[] = getPublicDeclaredMethods(cl);
- for (int i = 0; i < methods.length; i++) {
- method = methods[i];
- if (method == null) {
- continue;
- }
-
+ for (Method method : ClassInfo.get(cl).getMethods()) {
// make sure method signature matches.
if (method.getName().equals(methodName)) {
Type[] params = method.getGenericParameterTypes();
@@ -1430,8 +1185,6 @@
}
}
}
- method = null;
-
// Now check any inherited interfaces. This is necessary both when
// the argument class is itself an interface, and when the argument
// class is an abstract class.
@@ -1440,12 +1193,12 @@
// Note: The original implementation had both methods calling
// the 3 arg method. This is preserved but perhaps it should
// pass the args array instead of null.
- method = internalFindMethod(ifcs[i], methodName, argCount, null);
+ Method method = internalFindMethod(ifcs[i], methodName, argCount, null);
if (method != null) {
- break;
+ return method;
}
}
- return method;
+ return null;
}
/**
@@ -1508,19 +1261,6 @@
}
/**
- * Return true iff the given method throws the given exception.
- */
- private boolean throwsException(Method method, Class<?> exception) {
- Class<?>[] exs = method.getExceptionTypes();
- for (int i = 0; i < exs.length; i++) {
- if (exs[i] == exception) {
- return true;
- }
- }
- return false;
- }
-
- /**
* Try to create an instance of a named class.
* First try the classloader of "sibling", then try the system
* classloader then the class loader of the current Thread.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/beans/JavaBean.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package java.beans;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * An annotation used to specify some class-related information
+ * for the automatically generated {@link BeanInfo} classes.
+ * This annotation is not used if the annotated class
+ * has a corresponding user-defined {@code BeanInfo} class,
+ * which does not imply the automatic analysis.
+ *
+ * @see BeanInfo#getBeanDescriptor
+ * @since 1.9
+ *
+ * @author Sergey A. Malenkov
+ */
+@Documented
+@Target({TYPE})
+@Retention(RUNTIME)
+public @interface JavaBean {
+ /**
+ * The {@link BeanDescriptor#getShortDescription short description}
+ * for the {@link BeanInfo#getBeanDescriptor bean descriptor}
+ * of the annotated class.
+ *
+ * @return the bean description,
+ * or an empty string if the description is not set.
+ */
+ String description() default "";
+
+ /**
+ * The name of the default property is used to calculate its
+ * {@link BeanInfo#getDefaultPropertyIndex index} in the
+ * {@link BeanInfo#getPropertyDescriptors array} of properties
+ * defined in the annotated class. If the name is not set or
+ * the annotated class does not define a property
+ * with the specified name, the default property index
+ * will be calculated automatically by the
+ * {@link Introspector} depending on its state.
+ *
+ * @return the name of the default property,
+ * or an empty string if the name is not set.
+ */
+ String defaultProperty() default "";
+
+ /**
+ * The name of the default event set is used to calculate its
+ * {@link BeanInfo#getDefaultEventIndex index} in the
+ * {@link BeanInfo#getEventSetDescriptors array} of event sets
+ * defined in the annotated class. If the name is not set or
+ * the annotated class does not define an event set
+ * with the specified name, the default event set index
+ * will be calculated automatically by the
+ * {@link Introspector} depending on its state.
+ *
+ * @return the name of the default event set,
+ * or an empty string if the name is not set.
+ */
+ String defaultEventSet() default "";
+}
--- a/jdk/src/share/classes/java/beans/PropertyDescriptor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/beans/PropertyDescriptor.java Wed Jul 05 19:50:57 2017 +0200
@@ -22,12 +22,14 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-
package java.beans;
import java.lang.ref.Reference;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
+import java.util.Map.Entry;
+
+import com.sun.beans.introspect.PropertyInfo;
/**
* A PropertyDescriptor describes one property that a Java Bean
@@ -140,25 +142,47 @@
}
/**
- * Creates <code>PropertyDescriptor</code> for the specified bean
- * with the specified name and methods to read/write the property value.
+ * Creates {@code PropertyDescriptor} from the specified property info.
*
- * @param bean the type of the target bean
- * @param base the base name of the property (the rest of the method name)
- * @param read the method used for reading the property value
- * @param write the method used for writing the property value
- * @exception IntrospectionException if an exception occurs during introspection
+ * @param entry the pair of values,
+ * where the {@code key} is the base name of the property (the rest of the method name)
+ * and the {@code value} is the automatically generated property info
+ * @param bound the flag indicating whether it is possible to treat this property as a bound property
*
- * @since 1.7
+ * @since 1.9
*/
- PropertyDescriptor(Class<?> bean, String base, Method read, Method write) throws IntrospectionException {
- if (bean == null) {
- throw new IntrospectionException("Target Bean class is null");
+ PropertyDescriptor(Entry<String,PropertyInfo> entry, boolean bound) {
+ String base = entry.getKey();
+ PropertyInfo info = entry.getValue();
+ setName(Introspector.decapitalize(base));
+ setReadMethod0(info.getReadMethod());
+ setWriteMethod0(info.getWriteMethod());
+ setPropertyType(info.getPropertyType());
+ setConstrained(info.isConstrained());
+ setBound(bound && info.is(PropertyInfo.Name.bound));
+ if (info.is(PropertyInfo.Name.expert)) {
+ setValue(PropertyInfo.Name.expert.name(), Boolean.TRUE); // compatibility
+ setExpert(true);
}
- setClass0(bean);
- setName(Introspector.decapitalize(base));
- setReadMethod(read);
- setWriteMethod(write);
+ if (info.is(PropertyInfo.Name.hidden)) {
+ setValue(PropertyInfo.Name.hidden.name(), Boolean.TRUE); // compatibility
+ setHidden(true);
+ }
+ if (info.is(PropertyInfo.Name.preferred)) {
+ setPreferred(true);
+ }
+ Object visual = info.get(PropertyInfo.Name.visualUpdate);
+ if (visual != null) {
+ setValue(PropertyInfo.Name.visualUpdate.name(), visual);
+ }
+ Object description = info.get(PropertyInfo.Name.description);
+ if (description != null) {
+ setShortDescription(description.toString());
+ }
+ Object values = info.get(PropertyInfo.Name.enumerationValues);
+ if (values != null) {
+ setValue(PropertyInfo.Name.enumerationValues.name(), values);
+ }
this.baseName = base;
}
@@ -249,13 +273,17 @@
*/
public synchronized void setReadMethod(Method readMethod)
throws IntrospectionException {
+ // The property type is determined by the read method.
+ setPropertyType(findPropertyType(readMethod, this.writeMethodRef.get()));
+ setReadMethod0(readMethod);
+ }
+
+ private void setReadMethod0(Method readMethod) {
this.readMethodRef.set(readMethod);
if (readMethod == null) {
readMethodName = null;
return;
}
- // The property type is determined by the read method.
- setPropertyType(findPropertyType(readMethod, this.writeMethodRef.get()));
setClass0(readMethod.getDeclaringClass());
readMethodName = readMethod.getName();
@@ -320,13 +348,17 @@
*/
public synchronized void setWriteMethod(Method writeMethod)
throws IntrospectionException {
+ // Set the property type - which validates the method
+ setPropertyType(findPropertyType(getReadMethod(), writeMethod));
+ setWriteMethod0(writeMethod);
+ }
+
+ private void setWriteMethod0(Method writeMethod) {
this.writeMethodRef.set(writeMethod);
if (writeMethod == null) {
writeMethodName = null;
return;
}
- // Set the property type - which validates the method
- setPropertyType(findPropertyType(getReadMethod(), writeMethod));
setClass0(writeMethod.getDeclaringClass());
writeMethodName = writeMethod.getName();
--- a/jdk/src/share/classes/java/lang/Class.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/lang/Class.java Wed Jul 05 19:50:57 2017 +0200
@@ -134,10 +134,11 @@
* This constructor is not used and prevents the default constructor being
* generated.
*/
- private Class(ClassLoader loader) {
+ private Class(ClassLoader loader, Class<?> arrayComponentType) {
// Initialize final field for classLoader. The initialization value of non-null
// prevents future JIT optimizations from assuming this final field is null.
classLoader = loader;
+ componentType = arrayComponentType;
}
/**
@@ -917,7 +918,16 @@
* @see java.lang.reflect.Array
* @since 1.1
*/
- public native Class<?> getComponentType();
+ public Class<?> getComponentType() {
+ // Only return for array types. Storage may be reused for Class for instance types.
+ if (isArray()) {
+ return componentType;
+ } else {
+ return null;
+ }
+ }
+
+ private final Class<?> componentType;
/**
--- a/jdk/src/share/classes/java/lang/ConditionalSpecialCasing.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/lang/ConditionalSpecialCasing.java Wed Jul 05 19:50:57 2017 +0200
@@ -147,7 +147,7 @@
}
private static char[] lookUpTable(String src, int index, Locale locale, boolean bLowerCasing) {
- HashSet<Entry> set = entryTable.get(new Integer(src.codePointAt(index)));
+ HashSet<Entry> set = entryTable.get(src.codePointAt(index));
char[] ret = null;
if (set != null) {
--- a/jdk/src/share/classes/java/lang/ProcessBuilder.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/lang/ProcessBuilder.java Wed Jul 05 19:50:57 2017 +0200
@@ -957,6 +957,7 @@
* <li>The operating system program file was not found.
* <li>Access to the program file was denied.
* <li>The working directory does not exist.
+ * <li>Invalid character in command argument, such as NUL.
* </ul>
*
* <p>In such cases an exception will be thrown. The exact nature
@@ -1019,6 +1020,12 @@
String dir = directory == null ? null : directory.toString();
+ for (int i = 1; i < cmdarray.length; i++) {
+ if (cmdarray[i].indexOf('\u0000') >= 0) {
+ throw new IOException("invalid null character in command");
+ }
+ }
+
try {
return ProcessImpl.start(cmdarray,
environment,
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java Wed Jul 05 19:50:57 2017 +0200
@@ -1505,6 +1505,10 @@
// that is *not* the bytecode behavior.
mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
}
+ if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
+ // cannot "new" a protected ctor in a different package
+ mods ^= Modifier.PROTECTED;
+ }
if (Modifier.isFinal(mods) &&
MethodHandleNatives.refKindIsSetter(refKind))
throw m.makeAccessException("unexpected set of a final field", this);
--- a/jdk/src/share/classes/java/lang/reflect/Proxy.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Proxy.java Wed Jul 05 19:50:57 2017 +0200
@@ -362,12 +362,13 @@
Class<?>... interfaces)
throws IllegalArgumentException
{
- SecurityManager sm = System.getSecurityManager();
+ final Class<?>[] intfs = interfaces.clone();
+ final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
- checkProxyAccess(Reflection.getCallerClass(), loader, interfaces);
+ checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
- return getProxyClass0(loader, interfaces);
+ return getProxyClass0(loader, intfs);
}
/*
@@ -706,15 +707,16 @@
{
Objects.requireNonNull(h);
+ final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
- checkProxyAccess(Reflection.getCallerClass(), loader, interfaces);
+ checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
*/
- Class<?> cl = getProxyClass0(loader, interfaces);
+ Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
--- a/jdk/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -322,13 +322,13 @@
switch (optID) {
case SO_TIMEOUT:
- result = new Integer(timeout);
+ result = timeout;
break;
case IP_TOS:
result = socketGetOption(optID);
if ( ((Integer)result).intValue() == -1) {
- result = new Integer(trafficClass);
+ result = trafficClass;
}
break;
--- a/jdk/src/share/classes/java/net/AbstractPlainSocketImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/net/AbstractPlainSocketImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -279,7 +279,7 @@
throw new SocketException("Socket Closed");
}
if (opt == SO_TIMEOUT) {
- return new Integer(timeout);
+ return timeout;
}
int ret = 0;
/*
@@ -299,7 +299,7 @@
return Boolean.valueOf(ret != -1);
case SO_LINGER:
ret = socketGetOption(opt, null);
- return (ret == -1) ? Boolean.FALSE: (Object)(new Integer(ret));
+ return (ret == -1) ? Boolean.FALSE: (Object)(ret);
case SO_REUSEADDR:
ret = socketGetOption(opt, null);
return Boolean.valueOf(ret != -1);
@@ -310,13 +310,13 @@
case SO_SNDBUF:
case SO_RCVBUF:
ret = socketGetOption(opt, null);
- return new Integer(ret);
+ return ret;
case IP_TOS:
ret = socketGetOption(opt, null);
if (ret == -1) { // ipv6 tos
- return new Integer(trafficClass);
+ return trafficClass;
} else {
- return new Integer(ret);
+ return ret;
}
case SO_KEEPALIVE:
ret = socketGetOption(opt, null);
--- a/jdk/src/share/classes/java/net/DatagramSocket.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/net/DatagramSocket.java Wed Jul 05 19:50:57 2017 +0200
@@ -858,7 +858,7 @@
public synchronized void setSoTimeout(int timeout) throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
+ getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
}
/**
@@ -920,7 +920,7 @@
}
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));
+ getImpl().setOption(SocketOptions.SO_SNDBUF, size);
}
/**
@@ -978,7 +978,7 @@
}
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
+ getImpl().setOption(SocketOptions.SO_RCVBUF, size);
}
/**
@@ -1040,7 +1040,7 @@
throw new SocketException("Socket is closed");
// Integer instead of Boolean for compatibility with older DatagramSocketImpl
if (oldImpl)
- getImpl().setOption(SocketOptions.SO_REUSEADDR, new Integer(on?-1:0));
+ getImpl().setOption(SocketOptions.SO_REUSEADDR, on?-1:0);
else
getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
}
@@ -1141,7 +1141,7 @@
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.IP_TOS, new Integer(tc));
+ getImpl().setOption(SocketOptions.IP_TOS, tc);
}
/**
--- a/jdk/src/share/classes/java/net/ServerSocket.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/net/ServerSocket.java Wed Jul 05 19:50:57 2017 +0200
@@ -650,7 +650,7 @@
public synchronized void setSoTimeout(int timeout) throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
+ getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
}
/**
@@ -847,7 +847,7 @@
}
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
+ getImpl().setOption(SocketOptions.SO_RCVBUF, size);
}
/**
--- a/jdk/src/share/classes/java/net/Socket.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/net/Socket.java Wed Jul 05 19:50:57 2017 +0200
@@ -1024,7 +1024,7 @@
}
if (linger > 65535)
linger = 65535;
- getImpl().setOption(SocketOptions.SO_LINGER, new Integer(linger));
+ getImpl().setOption(SocketOptions.SO_LINGER, linger);
}
}
@@ -1140,7 +1140,7 @@
if (timeout < 0)
throw new IllegalArgumentException("timeout can't be negative");
- getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
+ getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
}
/**
@@ -1196,7 +1196,7 @@
}
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));
+ getImpl().setOption(SocketOptions.SO_SNDBUF, size);
}
/**
@@ -1270,7 +1270,7 @@
}
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
+ getImpl().setOption(SocketOptions.SO_RCVBUF, size);
}
/**
@@ -1380,7 +1380,7 @@
if (isClosed())
throw new SocketException("Socket is closed");
- getImpl().setOption(SocketOptions.IP_TOS, new Integer(tc));
+ getImpl().setOption(SocketOptions.IP_TOS, tc);
}
/**
--- a/jdk/src/share/classes/java/nio/charset/CoderResult.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/nio/charset/CoderResult.java Wed Jul 05 19:50:57 2017 +0200
@@ -200,7 +200,7 @@
private synchronized CoderResult get(int len) {
if (len <= 0)
throw new IllegalArgumentException("Non-positive length");
- Integer k = new Integer(len);
+ Integer k = len;
WeakReference<CoderResult> w;
CoderResult e = null;
if (cache == null) {
--- a/jdk/src/share/classes/java/security/Provider.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/security/Provider.java Wed Jul 05 19:50:57 2017 +0200
@@ -1376,7 +1376,7 @@
* <p>This class defines the methods {@link #supportsParameter
* supportsParameter()} and {@link #newInstance newInstance()}
* which are used by the Java security framework when it searches for
- * suitable services and instantes them. The valid arguments to those
+ * suitable services and instantiates them. The valid arguments to those
* methods depend on the type of service. For the service types defined
* within Java SE, see the
* <a href="../../../technotes/guides/security/crypto/CryptoSpec.html">
@@ -1566,7 +1566,7 @@
*
* @throws InvalidParameterException if the value of
* constructorParameter is invalid for this type of service.
- * @throws NoSuchAlgorithmException if instantation failed for
+ * @throws NoSuchAlgorithmException if instantiation failed for
* any other reason.
*/
public Object newInstance(Object constructorParameter)
@@ -1594,7 +1594,9 @@
+ " engines");
}
Class<?> clazz = getImplClass();
- return clazz.newInstance();
+ Class<?>[] empty = {};
+ Constructor<?> con = clazz.getConstructor(empty);
+ return con.newInstance();
} else {
Class<?> paramClass = cap.getConstructorParameterClass();
if (constructorParameter != null) {
@@ -1637,13 +1639,18 @@
} else {
clazz = cl.loadClass(className);
}
+ if (!Modifier.isPublic(clazz.getModifiers())) {
+ throw new NoSuchAlgorithmException
+ ("class configured for " + type + " (provider: " +
+ provider.getName() + ") is not public.");
+ }
classRef = new WeakReference<Class<?>>(clazz);
}
return clazz;
} catch (ClassNotFoundException e) {
throw new NoSuchAlgorithmException
- ("class configured for " + type + "(provider: " +
- provider.getName() + ")" + "cannot be found.", e);
+ ("class configured for " + type + " (provider: " +
+ provider.getName() + ") cannot be found.", e);
}
}
@@ -1656,15 +1663,21 @@
throws Exception {
Class<?> clazz = getImplClass();
if (constructorParameter == null) {
- Object o = clazz.newInstance();
- return o;
+ // create instance with public no-arg constructor if it exists
+ try {
+ Class<?>[] empty = {};
+ Constructor<?> con = clazz.getConstructor(empty);
+ return con.newInstance();
+ } catch (NoSuchMethodException e) {
+ throw new NoSuchAlgorithmException("No public no-arg "
+ + "constructor found in class " + className);
+ }
}
Class<?> argClass = constructorParameter.getClass();
Constructor<?>[] cons = clazz.getConstructors();
// find first public constructor that can take the
// argument as parameter
- for (int i = 0; i < cons.length; i++) {
- Constructor<?> con = cons[i];
+ for (Constructor<?> con : cons) {
Class<?>[] paramTypes = con.getParameterTypes();
if (paramTypes.length != 1) {
continue;
@@ -1672,10 +1685,9 @@
if (paramTypes[0].isAssignableFrom(argClass) == false) {
continue;
}
- Object o = con.newInstance(new Object[] {constructorParameter});
- return o;
+ return con.newInstance(constructorParameter);
}
- throw new NoSuchAlgorithmException("No constructor matching "
+ throw new NoSuchAlgorithmException("No public constructor matching "
+ argClass.getName() + " found in class " + className);
}
--- a/jdk/src/share/classes/java/security/SignedObject.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/security/SignedObject.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -211,7 +211,9 @@
* @param verificationKey the public key for verification.
* @param verificationEngine the signature verification engine.
*
- * @exception SignatureException if signature verification failed.
+ * @exception SignatureException if signature verification failed (an
+ * exception prevented the signature verification engine from completing
+ * normally).
* @exception InvalidKeyException if the verification key is invalid.
*
* @return {@code true} if the signature
--- a/jdk/src/share/classes/java/util/Locale.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/Locale.java Wed Jul 05 19:50:57 2017 +0200
@@ -1924,7 +1924,7 @@
// the qualifier; if there are no qualifiers, the third element is
// unused by the format pattern.
Object[] displayNames = {
- new Integer(qualifierNames.length != 0 ? 2 : 1),
+ qualifierNames.length != 0 ? 2 : 1,
mainName,
// We could also just call formatList() and have it handle the empty
// list case, but this is more efficient, and we want it to be
@@ -2078,7 +2078,7 @@
// Rebuild the argument list with the list length as the first element
Object[] args = new Object[stringList.length + 1];
System.arraycopy(stringList, 0, args, 1, stringList.length);
- args[0] = new Integer(stringList.length);
+ args[0] = stringList.length;
// Format it using the pattern in the resource
MessageFormat format = new MessageFormat(listPattern);
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java Wed Jul 05 19:50:57 2017 +0200
@@ -334,6 +334,8 @@
if (vclass != fieldClass)
throw new ClassCastException();
+ if (vclass.isPrimitive())
+ throw new IllegalArgumentException("Must be reference type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
--- a/jdk/src/share/classes/java/util/prefs/XmlSupport.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/prefs/XmlSupport.java Wed Jul 05 19:50:57 2017 +0200
@@ -262,7 +262,7 @@
try {
TransformerFactory tf = TransformerFactory.newInstance();
try {
- tf.setAttribute("indent-number", new Integer(2));
+ tf.setAttribute("indent-number", 2);
} catch (IllegalArgumentException iae) {
//Ignore the IAE. Should not fail the writeout even the
//transformer provider does not support "indent-number".
--- a/jdk/src/share/classes/java/util/regex/Pattern.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/regex/Pattern.java Wed Jul 05 19:50:57 2017 +0200
@@ -917,6 +917,13 @@
*/
public static final int UNICODE_CHARACTER_CLASS = 0x100;
+ /**
+ * Contains all possible flags for compile(regex, flags).
+ */
+ private static final int ALL_FLAGS = CASE_INSENSITIVE | MULTILINE |
+ DOTALL | UNICODE_CASE | CANON_EQ | UNIX_LINES | LITERAL |
+ UNICODE_CHARACTER_CLASS | COMMENTS;
+
/* Pattern has only two serialized components: The pattern string
* and the flags, which are all that is needed to recompile the pattern
* when it is deserialized.
@@ -1336,6 +1343,10 @@
* only a Start node and a LastNode node.
*/
private Pattern(String p, int f) {
+ if ((f & ~ALL_FLAGS) != 0) {
+ throw new IllegalArgumentException("Unknown flag 0x"
+ + Integer.toHexString(f));
+ }
pattern = p;
flags = f;
--- a/jdk/src/share/classes/java/util/stream/AbstractPipeline.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/AbstractPipeline.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -322,6 +322,7 @@
@Override
@SuppressWarnings("unchecked")
public S onClose(Runnable closeHandler) {
+ Objects.requireNonNull(closeHandler);
Runnable existingHandler = sourceStage.sourceCloseAction;
sourceStage.sourceCloseAction =
(existingHandler == null)
@@ -406,7 +407,7 @@
// Clear the short circuit flag for next pipeline stage
// This stage encapsulates short-circuiting, the next
// stage may not have any short-circuit operations, and
- // if so spliterator.forEachRemaining should be be used
+ // if so spliterator.forEachRemaining should be used
// for traversal
thisOpFlags = thisOpFlags & ~StreamOpFlag.IS_SHORT_CIRCUIT;
}
--- a/jdk/src/share/classes/java/util/stream/BaseStream.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/BaseStream.java Wed Jul 05 19:50:57 2017 +0200
@@ -53,7 +53,7 @@
* parallelism, which governs the behavior of all stream types.
*
* @param <T> the type of the stream elements
- * @param <S> the type of of the stream implementing {@code BaseStream}
+ * @param <S> the type of the stream implementing {@code BaseStream}
* @since 1.8
* @see Stream
* @see IntStream
--- a/jdk/src/share/classes/java/util/stream/DoublePipeline.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/DoublePipeline.java Wed Jul 05 19:50:57 2017 +0200
@@ -254,6 +254,7 @@
@Override
public final DoubleStream flatMap(DoubleFunction<? extends DoubleStream> mapper) {
+ Objects.requireNonNull(mapper);
return new StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
@@ -469,6 +470,7 @@
public final <R> R collect(Supplier<R> supplier,
ObjDoubleConsumer<R> accumulator,
BiConsumer<R, R> combiner) {
+ Objects.requireNonNull(combiner);
BinaryOperator<R> operator = (left, right) -> {
combiner.accept(left, right);
return left;
--- a/jdk/src/share/classes/java/util/stream/DoubleStream.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/DoubleStream.java Wed Jul 05 19:50:57 2017 +0200
@@ -768,7 +768,7 @@
* to the element at position {@code n - 1}.
*
* @param seed the initial element
- * @param f a function to be applied to to the previous element to produce
+ * @param f a function to be applied to the previous element to produce
* a new element
* @return a new sequential {@code DoubleStream}
*/
--- a/jdk/src/share/classes/java/util/stream/IntPipeline.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/IntPipeline.java Wed Jul 05 19:50:57 2017 +0200
@@ -290,6 +290,7 @@
@Override
public final IntStream flatMap(IntFunction<? extends IntStream> mapper) {
+ Objects.requireNonNull(mapper);
return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
@@ -465,6 +466,7 @@
public final <R> R collect(Supplier<R> supplier,
ObjIntConsumer<R> accumulator,
BiConsumer<R, R> combiner) {
+ Objects.requireNonNull(combiner);
BinaryOperator<R> operator = (left, right) -> {
combiner.accept(left, right);
return left;
--- a/jdk/src/share/classes/java/util/stream/IntStream.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/IntStream.java Wed Jul 05 19:50:57 2017 +0200
@@ -734,7 +734,7 @@
* element at position {@code n - 1}.
*
* @param seed the initial element
- * @param f a function to be applied to to the previous element to produce
+ * @param f a function to be applied to the previous element to produce
* a new element
* @return A new sequential {@code IntStream}
*/
--- a/jdk/src/share/classes/java/util/stream/LongPipeline.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/LongPipeline.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -271,6 +271,7 @@
@Override
public final LongStream flatMap(LongFunction<? extends LongStream> mapper) {
+ Objects.requireNonNull(mapper);
return new StatelessOp<Long>(this, StreamShape.LONG_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
@@ -447,6 +448,7 @@
public final <R> R collect(Supplier<R> supplier,
ObjLongConsumer<R> accumulator,
BiConsumer<R, R> combiner) {
+ Objects.requireNonNull(combiner);
BinaryOperator<R> operator = (left, right) -> {
combiner.accept(left, right);
return left;
--- a/jdk/src/share/classes/java/util/stream/LongStream.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/LongStream.java Wed Jul 05 19:50:57 2017 +0200
@@ -727,7 +727,7 @@
* element at position {@code n - 1}.
*
* @param seed the initial element
- * @param f a function to be applied to to the previous element to produce
+ * @param f a function to be applied to the previous element to produce
* a new element
* @return a new sequential {@code LongStream}
*/
--- a/jdk/src/share/classes/java/util/stream/PipelineHelper.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/PipelineHelper.java Wed Jul 05 19:50:57 2017 +0200
@@ -74,7 +74,7 @@
/**
* Returns the exact output size of the portion of the output resulting from
* applying the pipeline stages described by this {@code PipelineHelper} to
- * the the portion of the input described by the provided
+ * the portion of the input described by the provided
* {@code Spliterator}, if known. If not known or known infinite, will
* return {@code -1}.
*
--- a/jdk/src/share/classes/java/util/stream/SliceOps.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/SliceOps.java Wed Jul 05 19:50:57 2017 +0200
@@ -693,7 +693,7 @@
* size.
*
* @param target the target size
- * @return return the number of completed elements
+ * @return the number of completed elements
*/
private long completedSize(long target) {
if (completed)
--- a/jdk/src/share/classes/java/util/stream/Stream.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/Stream.java Wed Jul 05 19:50:57 2017 +0200
@@ -1013,7 +1013,7 @@
*
* @param <T> the type of stream elements
* @param seed the initial element
- * @param f a function to be applied to to the previous element to produce
+ * @param f a function to be applied to the previous element to produce
* a new element
* @return a new sequential {@code Stream}
*/
--- a/jdk/src/share/classes/java/util/stream/StreamOpFlag.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/StreamOpFlag.java Wed Jul 05 19:50:57 2017 +0200
@@ -115,7 +115,7 @@
* characteristics that stream has; when describing a stream operation, one need
* describe whether the operation preserves, injects, or clears that
* characteristic. Accordingly, two bits are used for each flag, so as to allow
- * representing not only the presence of of a characteristic, but how an
+ * representing not only the presence of a characteristic, but how an
* operation modifies that characteristic. There are two common forms in which
* flag bits are combined into an {@code int} bit set. <em>Stream flags</em>
* are a unioned bit set constructed by ORing the enum characteristic values of
--- a/jdk/src/share/classes/javax/accessibility/AccessibleBundle.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/accessibility/AccessibleBundle.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -49,7 +49,7 @@
*/
public abstract class AccessibleBundle {
- private static Hashtable table = new Hashtable();
+ private static Hashtable<Locale, Hashtable<String, Object>> table = new Hashtable<>();
private final String defaultResourceBundleName
= "com.sun.accessibility.internal.resources.accessibility";
@@ -85,14 +85,12 @@
loadResourceBundle(resourceBundleName, locale);
// returns the localized string
- Object o = table.get(locale);
- if (o != null && o instanceof Hashtable) {
- Hashtable resourceTable = (Hashtable) o;
- o = resourceTable.get(key);
-
- if (o != null && o instanceof String) {
- return (String)o;
- }
+ Hashtable<String, Object> ht = table.get(locale);
+ if (ht != null) {
+ Object o = ht.get(key);
+ if (o != null && o instanceof String) {
+ return (String)o;
+ }
}
return key;
}
@@ -134,13 +132,13 @@
if (! table.contains(locale)) {
try {
- Hashtable resourceTable = new Hashtable();
+ Hashtable<String, Object> resourceTable = new Hashtable<>();
ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName, locale);
- Enumeration iter = bundle.getKeys();
+ Enumeration<String> iter = bundle.getKeys();
while(iter.hasMoreElements()) {
- String key = (String)iter.nextElement();
+ String key = iter.nextElement();
resourceTable.put(key, bundle.getObject(key));
}
--- a/jdk/src/share/classes/javax/accessibility/AccessibleRelationSet.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/accessibility/AccessibleRelationSet.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,7 +71,7 @@
*/
public AccessibleRelationSet(AccessibleRelation[] relations) {
if (relations.length != 0) {
- this.relations = new Vector(relations.length);
+ this.relations = new Vector<>(relations.length);
for (int i = 0; i < relations.length; i++) {
add(relations[i]);
}
@@ -90,7 +90,7 @@
*/
public boolean add(AccessibleRelation relation) {
if (relations == null) {
- relations = new Vector();
+ relations = new Vector<>();
}
// Merge the relation targets if the key exists
@@ -125,7 +125,7 @@
public void addAll(AccessibleRelation[] relations) {
if (relations.length != 0) {
if (this.relations == null) {
- this.relations = new Vector(relations.length);
+ this.relations = new Vector<>(relations.length);
}
for (int i = 0; i < relations.length; i++) {
add(relations[i]);
--- a/jdk/src/share/classes/javax/accessibility/AccessibleStateSet.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/accessibility/AccessibleStateSet.java Wed Jul 05 19:50:57 2017 +0200
@@ -68,7 +68,7 @@
*/
public AccessibleStateSet(AccessibleState[] states) {
if (states.length != 0) {
- this.states = new Vector(states.length);
+ this.states = new Vector<>(states.length);
for (int i = 0; i < states.length; i++) {
if (!this.states.contains(states[i])) {
this.states.addElement(states[i]);
@@ -92,7 +92,7 @@
// to always use a vector of states. It could be improved by
// caching the states as a bit set.]]]
if (states == null) {
- states = new Vector();
+ states = new Vector<>();
}
if (!states.contains(state)) {
@@ -111,7 +111,7 @@
public void addAll(AccessibleState[] states) {
if (states.length != 0) {
if (this.states == null) {
- this.states = new Vector(states.length);
+ this.states = new Vector<>(states.length);
}
for (int i = 0; i < states.length; i++) {
if (!this.states.contains(states[i])) {
--- a/jdk/src/share/classes/javax/crypto/CryptoPolicyParser.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/crypto/CryptoPolicyParser.java Wed Jul 05 19:50:57 2017 +0200
@@ -256,11 +256,11 @@
while (peek(",")) {
match(",");
if (peek("number")) {
- paramsV.addElement(new Integer(match()));
+ paramsV.addElement(match());
} else {
if (peek("*")) {
match("*");
- paramsV.addElement(new Integer(Integer.MAX_VALUE));
+ paramsV.addElement(Integer.MAX_VALUE);
} else {
throw new ParsingException(st.lineno(),
"Expecting an integer");
--- a/jdk/src/share/classes/javax/management/loading/MLet.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/management/loading/MLet.java Wed Jul 05 19:50:57 2017 +0200
@@ -1313,7 +1313,7 @@
if (type.compareTo("java.lang.Long") == 0)
return Long.valueOf(param);
if (type.compareTo("java.lang.Integer") == 0)
- return new Integer(param);
+ return param;
if (type.compareTo("java.lang.Float") == 0)
return new Float(param);
if (type.compareTo("java.lang.Double") == 0)
--- a/jdk/src/share/classes/javax/management/relation/RelationService.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/management/relation/RelationService.java Wed Jul 05 19:50:57 2017 +0200
@@ -3208,7 +3208,7 @@
// End of check :)
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(0);
+ return 0;
}
}
@@ -3218,7 +3218,7 @@
if (!isWritable) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(RoleStatus.ROLE_NOT_WRITABLE);
+ return RoleStatus.ROLE_NOT_WRITABLE;
}
}
@@ -3229,7 +3229,7 @@
if (!chkMinFlag) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(RoleStatus.LESS_THAN_MIN_ROLE_DEGREE);
+ return RoleStatus.LESS_THAN_MIN_ROLE_DEGREE;
}
// Checks maximum cardinality
@@ -3237,7 +3237,7 @@
if (!chkMaxFlag) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(RoleStatus.MORE_THAN_MAX_ROLE_DEGREE);
+ return RoleStatus.MORE_THAN_MAX_ROLE_DEGREE;
}
// Verifies that each referenced MBean is registered in the MBean
@@ -3254,7 +3254,7 @@
if (currObjName == null) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED);
+ return RoleStatus.REF_MBEAN_NOT_REGISTERED;
}
// Checks if it is of the correct class
@@ -3265,19 +3265,19 @@
if (!classSts) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS);
+ return RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS;
}
} catch (InstanceNotFoundException exc) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED);
+ return RoleStatus.REF_MBEAN_NOT_REGISTERED;
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
- return new Integer(0);
+ return 0;
}
--- a/jdk/src/share/classes/javax/swing/AbstractButton.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/AbstractButton.java Wed Jul 05 19:50:57 2017 +0200
@@ -1123,7 +1123,7 @@
}
}
- private boolean isListener(Class c, ActionListener a) {
+ private boolean isListener(Class<?> c, ActionListener a) {
boolean isListener = false;
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
--- a/jdk/src/share/classes/javax/swing/ArrayTable.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/ArrayTable.java Wed Jul 05 19:50:57 2017 +0200
@@ -133,7 +133,9 @@
if ((size==ARRAY_BOUNDARY) && isArray()) {
grow();
}
- ((Hashtable<Object,Object>)table).put(key, value);
+ @SuppressWarnings("unchecked")
+ Hashtable<Object,Object> tmp = (Hashtable<Object,Object>)table;
+ tmp.put(key, value);
}
}
}
--- a/jdk/src/share/classes/javax/swing/DebugGraphics.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/DebugGraphics.java Wed Jul 05 19:50:57 2017 +0200
@@ -1463,7 +1463,5 @@
}
return debugGraphicsInfo;
}
- private static final Class debugGraphicsInfoKey = DebugGraphicsInfo.class;
-
-
+ private static final Class<DebugGraphicsInfo> debugGraphicsInfoKey = DebugGraphicsInfo.class;
}
--- a/jdk/src/share/classes/javax/swing/DefaultCellEditor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultCellEditor.java Wed Jul 05 19:50:57 2017 +0200
@@ -131,7 +131,7 @@
*
* @param comboBox a <code>JComboBox</code> object
*/
- public DefaultCellEditor(final JComboBox comboBox) {
+ public DefaultCellEditor(final JComboBox<?> comboBox) {
editorComponent = comboBox;
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
delegate = new EditorDelegate() {
--- a/jdk/src/share/classes/javax/swing/DefaultRowSorter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultRowSorter.java Wed Jul 05 19:50:57 2017 +0200
@@ -128,7 +128,7 @@
/**
* Comparators specified by column.
*/
- private Comparator[] comparators;
+ private Comparator<?>[] comparators;
/**
* Whether or not the specified column is sortable, by column.
@@ -143,7 +143,7 @@
/**
* Cached comparators for the current sort
*/
- private Comparator[] sortComparators;
+ private Comparator<?>[] sortComparators;
/**
* Developer supplied Filter.
@@ -695,7 +695,7 @@
*/
private void cacheSortKeys(List<? extends SortKey> keys) {
int keySize = keys.size();
- sortComparators = new Comparator[keySize];
+ sortComparators = new Comparator<?>[keySize];
for (int i = 0; i < keySize; i++) {
sortComparators[i] = getComparator0(keys.get(i).getColumn());
}
@@ -762,7 +762,7 @@
public void setComparator(int column, Comparator<?> comparator) {
checkColumn(column);
if (comparators == null) {
- comparators = new Comparator[getModelWrapper().getColumnCount()];
+ comparators = new Comparator<?>[getModelWrapper().getColumnCount()];
}
comparators[column] = comparator;
}
@@ -788,8 +788,8 @@
// Returns the Comparator to use during sorting. Where as
// getComparator() may return null, this will never return null.
- private Comparator getComparator0(int column) {
- Comparator comparator = getComparator(column);
+ private Comparator<?> getComparator0(int column) {
+ Comparator<?> comparator = getComparator(column);
if (comparator != null) {
return comparator;
}
@@ -967,7 +967,9 @@
} else if (v2 == null) {
result = 1;
} else {
- result = sortComparators[counter].compare(v1, v2);
+ Comparator<Object> c =
+ (Comparator<Object>)sortComparators[counter];
+ result = c.compare(v1, v2);
}
if (sortOrder == SortOrder.DESCENDING) {
result *= -1;
@@ -1366,10 +1368,10 @@
*/
// NOTE: this class is static so that it can be placed in an array
private static class Row implements Comparable<Row> {
- private DefaultRowSorter sorter;
+ private DefaultRowSorter<?, ?> sorter;
int modelIndex;
- public Row(DefaultRowSorter sorter, int index) {
+ public Row(DefaultRowSorter<?, ?> sorter, int index) {
this.sorter = sorter;
modelIndex = index;
}
--- a/jdk/src/share/classes/javax/swing/JComboBox.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JComboBox.java Wed Jul 05 19:50:57 2017 +0200
@@ -1100,7 +1100,7 @@
}
}
- private boolean isListener(Class c, ActionListener a) {
+ private boolean isListener(Class<?> c, ActionListener a) {
boolean isListener = false;
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
@@ -1530,11 +1530,11 @@
* @return an int equal to the selected row, where 0 is the
* first item and -1 is none.
*/
- int selectionForKey(char aKey,ComboBoxModel aModel);
+ int selectionForKey(char aKey,ComboBoxModel<?> aModel);
}
class DefaultKeySelectionManager implements KeySelectionManager, Serializable {
- public int selectionForKey(char aKey,ComboBoxModel aModel) {
+ public int selectionForKey(char aKey,ComboBoxModel<?> aModel) {
int i,c;
int currentSelection = -1;
Object selectedItem = aModel.getSelectedItem();
@@ -1656,7 +1656,7 @@
implements AccessibleAction, AccessibleSelection {
- private JList popupList; // combo box popup list
+ private JList<?> popupList; // combo box popup list
private Accessible previousSelectedAccessible = null;
/**
@@ -1980,7 +1980,7 @@
a instanceof javax.swing.plaf.basic.ComboPopup) {
// get the popup list
- JList list = ((javax.swing.plaf.basic.ComboPopup)a).getList();
+ JList<?> list = ((javax.swing.plaf.basic.ComboPopup)a).getList();
// return the i-th selection in the popup list
AccessibleContext ac = list.getAccessibleContext();
--- a/jdk/src/share/classes/javax/swing/JComponent.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JComponent.java Wed Jul 05 19:50:57 2017 +0200
@@ -2111,6 +2111,7 @@
private void registerWithKeyboardManager(boolean onlyIfNew) {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
KeyStroke[] strokes;
+ @SuppressWarnings("unchecked")
Hashtable<KeyStroke, KeyStroke> registered =
(Hashtable<KeyStroke, KeyStroke>)getClientProperty
(WHEN_IN_FOCUSED_WINDOW_BINDINGS);
@@ -2164,6 +2165,7 @@
* <code>WHEN_IN_FOCUSED_WINDOW</code> <code>KeyStroke</code> bindings.
*/
private void unregisterWithKeyboardManager() {
+ @SuppressWarnings("unchecked")
Hashtable<KeyStroke, KeyStroke> registered =
(Hashtable<KeyStroke, KeyStroke>)getClientProperty
(WHEN_IN_FOCUSED_WINDOW_BINDINGS);
@@ -4126,16 +4128,20 @@
setFlag(AUTOSCROLLS_SET, false);
}
} else if (propertyName == "focusTraversalKeysForward") {
+ @SuppressWarnings("unchecked")
+ Set<AWTKeyStroke> strokeSet = (Set<AWTKeyStroke>) value;
if (!getFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET)) {
super.setFocusTraversalKeys(KeyboardFocusManager.
FORWARD_TRAVERSAL_KEYS,
- (Set<AWTKeyStroke>)value);
+ strokeSet);
}
} else if (propertyName == "focusTraversalKeysBackward") {
+ @SuppressWarnings("unchecked")
+ Set<AWTKeyStroke> strokeSet = (Set<AWTKeyStroke>) value;
if (!getFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET)) {
super.setFocusTraversalKeys(KeyboardFocusManager.
BACKWARD_TRAVERSAL_KEYS,
- (Set<AWTKeyStroke>)value);
+ strokeSet);
}
} else {
throw new IllegalArgumentException("property \""+
@@ -4713,6 +4719,7 @@
* @see #getVetoableChangeListeners
* @see #getAncestorListeners
*/
+ @SuppressWarnings("unchecked") // Casts to (T[])
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
T[] result;
if (listenerType == AncestorListener.class) {
--- a/jdk/src/share/classes/javax/swing/JEditorPane.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JEditorPane.java Wed Jul 05 19:50:57 2017 +0200
@@ -1191,7 +1191,7 @@
String classname = getKitTypeRegistry().get(type);
ClassLoader loader = getKitLoaderRegistry().get(type);
try {
- Class c;
+ Class<?> c;
if (loader != null) {
c = loader.loadClass(classname);
} else {
@@ -1265,18 +1265,26 @@
private static Hashtable<String, String> getKitTypeRegistry() {
loadDefaultKitsIfNecessary();
- return (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
+ @SuppressWarnings("unchecked")
+ Hashtable<String, String> tmp =
+ (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
+ return tmp;
}
private static Hashtable<String, ClassLoader> getKitLoaderRegistry() {
loadDefaultKitsIfNecessary();
- return (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
+ @SuppressWarnings("unchecked")
+ Hashtable<String, ClassLoader> tmp =
+ (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
+ return tmp;
}
private static Hashtable<String, EditorKit> getKitRegisty() {
- Hashtable ht = (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
+ @SuppressWarnings("unchecked")
+ Hashtable<String, EditorKit> ht =
+ (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
if (ht == null) {
- ht = new Hashtable(3);
+ ht = new Hashtable<>(3);
SwingUtilities.appContextPut(kitRegistryKey, ht);
}
return ht;
@@ -1302,9 +1310,9 @@
"javax.swing.text.rtf.RTFEditorKit");
}
}
- Hashtable ht = new Hashtable();
+ Hashtable<Object, Object> ht = new Hashtable<>();
SwingUtilities.appContextPut(kitTypeRegistryKey, ht);
- ht = new Hashtable();
+ ht = new Hashtable<>();
SwingUtilities.appContextPut(kitLoaderRegistryKey, ht);
for (String key : defaultEditorKitMap.keySet()) {
registerEditorKitForContentType(key,defaultEditorKitMap.get(key));
--- a/jdk/src/share/classes/javax/swing/JLayer.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JLayer.java Wed Jul 05 19:50:57 2017 +0200
@@ -721,7 +721,7 @@
AWTEvent.HIERARCHY_EVENT_MASK |
AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({"unchecked", "rawtypes"})
public void eventDispatched(AWTEvent event) {
Object source = event.getSource();
if (source instanceof Component) {
@@ -729,7 +729,7 @@
while (component != null) {
if (component instanceof JLayer) {
JLayer l = (JLayer) component;
- LayerUI ui = l.getUI();
+ LayerUI<?> ui = l.getUI();
if (ui != null &&
isEventEnabled(l.getLayerEventMask(), event.getID()) &&
(!(event instanceof InputEvent) || !((InputEvent)event).isConsumed())) {
--- a/jdk/src/share/classes/javax/swing/JOptionPane.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JOptionPane.java Wed Jul 05 19:50:57 2017 +0200
@@ -2387,7 +2387,7 @@
throws IOException, ClassNotFoundException {
s.defaultReadObject();
- Vector values = (Vector)s.readObject();
+ Vector<?> values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
--- a/jdk/src/share/classes/javax/swing/JSlider.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JSlider.java Wed Jul 05 19:50:57 2017 +0200
@@ -138,7 +138,7 @@
/**
* {@code Dictionary} of what labels to draw at which values
*/
- private Dictionary labelTable;
+ private Dictionary<Integer, JComponent> labelTable;
/**
@@ -773,10 +773,10 @@
}
// Check that there is a label with such image
- Enumeration elements = labelTable.elements();
+ Enumeration<JComponent> elements = labelTable.elements();
while (elements.hasMoreElements()) {
- Component component = (Component) elements.nextElement();
+ JComponent component = elements.nextElement();
if (component instanceof JLabel) {
JLabel label = (JLabel) component;
@@ -797,7 +797,7 @@
* @return the <code>Dictionary</code> containing labels and
* where to draw them
*/
- public Dictionary getLabelTable() {
+ public Dictionary<Integer, JComponent> getLabelTable() {
/*
if ( labelTable == null && getMajorTickSpacing() > 0 ) {
setLabelTable( createStandardLabels( getMajorTickSpacing() ) );
@@ -830,8 +830,8 @@
* attribute: visualUpdate true
* description: Specifies what labels will be drawn for any given value.
*/
- public void setLabelTable( Dictionary labels ) {
- Dictionary oldTable = labelTable;
+ public void setLabelTable( Dictionary<Integer, JComponent> labels ) {
+ Dictionary<Integer, JComponent> oldTable = labelTable;
labelTable = labels;
updateLabelUIs();
firePropertyChange("labelTable", oldTable, labelTable );
@@ -852,25 +852,25 @@
* @see JComponent#updateUI
*/
protected void updateLabelUIs() {
- Dictionary labelTable = getLabelTable();
+ Dictionary<Integer, JComponent> labelTable = getLabelTable();
if (labelTable == null) {
return;
}
- Enumeration labels = labelTable.keys();
+ Enumeration<Integer> labels = labelTable.keys();
while ( labels.hasMoreElements() ) {
- JComponent component = (JComponent) labelTable.get(labels.nextElement());
+ JComponent component = labelTable.get(labels.nextElement());
component.updateUI();
component.setSize(component.getPreferredSize());
}
}
private void updateLabelSizes() {
- Dictionary labelTable = getLabelTable();
+ Dictionary<Integer, JComponent> labelTable = getLabelTable();
if (labelTable != null) {
- Enumeration labels = labelTable.elements();
+ Enumeration<JComponent> labels = labelTable.elements();
while (labels.hasMoreElements()) {
- JComponent component = (JComponent) labels.nextElement();
+ JComponent component = labels.nextElement();
component.setSize(component.getPreferredSize());
}
}
@@ -898,7 +898,7 @@
* @throws IllegalArgumentException if {@code increment} is less than or
* equal to zero
*/
- public Hashtable createStandardLabels( int increment ) {
+ public Hashtable<Integer, JComponent> createStandardLabels( int increment ) {
return createStandardLabels( increment, getMinimum() );
}
@@ -926,7 +926,7 @@
* out of range, or if {@code increment} is less than or equal
* to zero
*/
- public Hashtable createStandardLabels( int increment, int start ) {
+ public Hashtable<Integer, JComponent> createStandardLabels( int increment, int start ) {
if ( start > getMaximum() || start < getMinimum() ) {
throw new IllegalArgumentException( "Slider label start point out of range." );
}
@@ -935,7 +935,7 @@
throw new IllegalArgumentException( "Label incremement must be > 0" );
}
- class SmartHashtable extends Hashtable<Object, Object> implements PropertyChangeListener {
+ class SmartHashtable extends Hashtable<Integer, JComponent> implements PropertyChangeListener {
int increment = 0;
int start = 0;
boolean startAtMin = false;
@@ -982,13 +982,13 @@
if ( e.getPropertyName().equals( "minimum" ) ||
e.getPropertyName().equals( "maximum" ) ) {
- Enumeration keys = getLabelTable().keys();
- Hashtable<Object, Object> hashtable = new Hashtable<Object, Object>();
+ Enumeration<Integer> keys = getLabelTable().keys();
+ Hashtable<Integer, JComponent> hashtable = new Hashtable<>();
// Save the labels that were added by the developer
while ( keys.hasMoreElements() ) {
- Object key = keys.nextElement();
- Object value = labelTable.get(key);
+ Integer key = keys.nextElement();
+ JComponent value = labelTable.get(key);
if ( !(value instanceof LabelUIResource) ) {
hashtable.put( key, value );
}
@@ -1000,7 +1000,7 @@
// Add the saved labels
keys = hashtable.keys();
while ( keys.hasMoreElements() ) {
- Object key = keys.nextElement();
+ Integer key = keys.nextElement();
put( key, hashtable.get( key ) );
}
@@ -1017,7 +1017,7 @@
SmartHashtable table = new SmartHashtable( increment, start );
- Dictionary labelTable = getLabelTable();
+ Dictionary<Integer, JComponent> labelTable = getLabelTable();
if (labelTable != null && (labelTable instanceof PropertyChangeListener)) {
removePropertyChangeListener((PropertyChangeListener) labelTable);
--- a/jdk/src/share/classes/javax/swing/JSpinner.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JSpinner.java Wed Jul 05 19:50:57 2017 +0200
@@ -907,7 +907,7 @@
/**
* This subclass of javax.swing.DateFormatter maps the minimum/maximum
- * properties to te start/end properties of a SpinnerDateModel.
+ * properties to the start/end properties of a SpinnerDateModel.
*/
private static class DateEditorFormatter extends DateFormatter {
private final SpinnerDateModel model;
@@ -917,19 +917,25 @@
this.model = model;
}
- public void setMinimum(Comparable min) {
- model.setStart(min);
+ @Override
+ @SuppressWarnings("unchecked")
+ public void setMinimum(Comparable<?> min) {
+ model.setStart((Comparable<Date>)min);
}
- public Comparable getMinimum() {
+ @Override
+ public Comparable<Date> getMinimum() {
return model.getStart();
}
- public void setMaximum(Comparable max) {
- model.setEnd(max);
+ @Override
+ @SuppressWarnings("unchecked")
+ public void setMaximum(Comparable<?> max) {
+ model.setEnd((Comparable<Date>)max);
}
- public Comparable getMaximum() {
+ @Override
+ public Comparable<Date> getMaximum() {
return model.getEnd();
}
}
@@ -1095,19 +1101,23 @@
setValueClass(model.getValue().getClass());
}
- public void setMinimum(Comparable min) {
+ @Override
+ public void setMinimum(Comparable<?> min) {
model.setMinimum(min);
}
- public Comparable getMinimum() {
+ @Override
+ public Comparable<?> getMinimum() {
return model.getMinimum();
}
- public void setMaximum(Comparable max) {
+ @Override
+ public void setMaximum(Comparable<?> max) {
model.setMaximum(max);
}
- public Comparable getMaximum() {
+ @Override
+ public Comparable<?> getMaximum() {
return model.getMaximum();
}
}
--- a/jdk/src/share/classes/javax/swing/JTable.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JTable.java Wed Jul 05 19:50:57 2017 +0200
@@ -354,19 +354,23 @@
/** Identifies the row of the cell being edited. */
transient protected int editingRow;
- /**
+ /**
* A table of objects that display the contents of a cell,
* indexed by class as declared in <code>getColumnClass</code>
* in the <code>TableModel</code> interface.
*/
- transient protected Hashtable defaultRenderersByColumnClass;
+ transient protected Hashtable<Object, Object> defaultRenderersByColumnClass;
+ // Logicaly, the above is a Hashtable<Class<?>, TableCellRenderer>.
+ // It is declared otherwise to accomodate using UIDefaults.
/**
* A table of objects that display and edit the contents of a cell,
* indexed by class as declared in <code>getColumnClass</code>
* in the <code>TableModel</code> interface.
*/
- transient protected Hashtable defaultEditorsByColumnClass;
+ transient protected Hashtable<Object, Object> defaultEditorsByColumnClass;
+ // Logicaly, the above is a Hashtable<Class<?>, TableCellEditor>.
+ // It is declared otherwise to accomodate using UIDefaults.
/** The foreground color of selected cells. */
protected Color selectionForeground;
@@ -665,7 +669,7 @@
* @param rowData the data for the new table
* @param columnNames names of each column
*/
- public JTable(Vector rowData, Vector columnNames) {
+ public JTable(Vector<Vector<Object>> rowData, Vector<Object> columnNames) {
this(new DefaultTableModel(rowData, columnNames));
}
@@ -1338,7 +1342,7 @@
return (TableCellRenderer)renderer;
}
else {
- Class c = columnClass.getSuperclass();
+ Class<?> c = columnClass.getSuperclass();
if (c == null && columnClass != Object.class) {
c = Object.class;
}
@@ -2621,7 +2625,7 @@
* @since 1.6
*/
public int convertRowIndexToView(int modelRowIndex) {
- RowSorter sorter = getRowSorter();
+ RowSorter<?> sorter = getRowSorter();
if (sorter != null) {
return sorter.convertRowIndexToView(modelRowIndex);
}
@@ -2643,7 +2647,7 @@
* @since 1.6
*/
public int convertRowIndexToModel(int viewRowIndex) {
- RowSorter sorter = getRowSorter();
+ RowSorter<?> sorter = getRowSorter();
if (sorter != null) {
return sorter.convertRowIndexToModel(viewRowIndex);
}
@@ -2661,7 +2665,7 @@
* @see #getColumnCount
*/
public int getRowCount() {
- RowSorter sorter = getRowSorter();
+ RowSorter<?> sorter = getRowSorter();
if (sorter != null) {
return sorter.getViewRowCount();
}
@@ -3631,13 +3635,13 @@
}
// Update the UIs of all the default renderers.
- Enumeration defaultRenderers = defaultRenderersByColumnClass.elements();
+ Enumeration<?> defaultRenderers = defaultRenderersByColumnClass.elements();
while (defaultRenderers.hasMoreElements()) {
SwingUtilities.updateRendererOrEditorUI(defaultRenderers.nextElement());
}
// Update the UIs of all the default editors.
- Enumeration defaultEditors = defaultEditorsByColumnClass.elements();
+ Enumeration<?> defaultEditors = defaultEditorsByColumnClass.elements();
while (defaultEditors.hasMoreElements()) {
SwingUtilities.updateRendererOrEditorUI(defaultEditors.nextElement());
}
@@ -5451,8 +5455,8 @@
*/
static class GenericEditor extends DefaultCellEditor {
- Class[] argTypes = new Class[]{String.class};
- java.lang.reflect.Constructor constructor;
+ Class<?>[] argTypes = new Class<?>[]{String.class};
+ java.lang.reflect.Constructor<?> constructor;
Object value;
public GenericEditor() {
--- a/jdk/src/share/classes/javax/swing/JTextField.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JTextField.java Wed Jul 05 19:50:57 2017 +0200
@@ -587,7 +587,7 @@
}
}
- private boolean isListener(Class c, ActionListener a) {
+ private boolean isListener(Class<?> c, ActionListener a) {
boolean isListener = false;
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
--- a/jdk/src/share/classes/javax/swing/JTree.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JTree.java Wed Jul 05 19:50:57 2017 +0200
@@ -4032,7 +4032,7 @@
/**
* Subclassed to load the children, if necessary.
*/
- public Enumeration children() {
+ public Enumeration<TreeNode> children() {
if(!loadedChildren)
loadChildren();
return super.children();
--- a/jdk/src/share/classes/javax/swing/KeyboardManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/KeyboardManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -68,13 +68,13 @@
/**
* maps top-level containers to a sub-hashtable full of keystrokes
*/
- Hashtable<Container, Hashtable> containerMap = new Hashtable<Container, Hashtable>();
+ Hashtable<Container, Hashtable<Object, Object>> containerMap = new Hashtable<>();
/**
* Maps component/keystroke pairs to a topLevel container
* This is mainly used for fast unregister operations
*/
- Hashtable<ComponentKeyStrokePair, Container> componentKeyStrokeMap = new Hashtable<ComponentKeyStrokePair, Container>();
+ Hashtable<ComponentKeyStrokePair, Container> componentKeyStrokeMap = new Hashtable<>();
public static KeyboardManager getCurrentManager() {
return currentManager;
@@ -95,7 +95,7 @@
if (topContainer == null) {
return;
}
- Hashtable keyMap = containerMap.get(topContainer);
+ Hashtable<Object, Object> keyMap = containerMap.get(topContainer);
if (keyMap == null) { // lazy evaluate one
keyMap = registerNewTopContainer(topContainer);
@@ -105,7 +105,8 @@
if (tmp == null) {
keyMap.put(k,c);
} else if (tmp instanceof Vector) { // if there's a Vector there then add to it.
- Vector v = (Vector)tmp;
+ @SuppressWarnings("unchecked")
+ Vector<Object> v = (Vector)tmp;
if (!v.contains(c)) { // only add if this keystroke isn't registered for this component
v.addElement(c);
}
@@ -114,7 +115,7 @@
// Then add the old compoennt and the new compoent to the vector
// then insert the vector in the table
if (tmp != c) { // this means this is already registered for this component, no need to dup
- Vector<JComponent> v = new Vector<JComponent>();
+ Vector<JComponent> v = new Vector<>();
v.addElement((JComponent) tmp);
v.addElement(c);
keyMap.put(k, v);
@@ -160,7 +161,7 @@
return;
}
- Hashtable keyMap = containerMap.get(topContainer);
+ Hashtable<Object, Object> keyMap = containerMap.get(topContainer);
if (keyMap == null) { // this should never happen, but I'm being safe
Thread.dumpStack();
return;
@@ -176,7 +177,7 @@
keyMap.remove(ks); // remove the KeyStroke from the Map
//System.out.println("removed a stroke" + ks);
} else if (tmp instanceof Vector ) { // this means there is more than one component reg for this key
- Vector v = (Vector)tmp;
+ Vector<?> v = (Vector)tmp;
v.removeElement(c);
if ( v.isEmpty() ) {
keyMap.remove(ks); // remove the KeyStroke from the Map
@@ -227,7 +228,7 @@
ks=KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers(), !pressed);
}
- Hashtable keyMap = containerMap.get(topAncestor);
+ Hashtable<Object, Object> keyMap = containerMap.get(topAncestor);
if (keyMap != null) { // this container isn't registered, so bail
Object tmp = null;
@@ -250,7 +251,7 @@
fireBinding(c, ks, e, pressed);
}
} else if ( tmp instanceof Vector) { //more than one comp registered for this
- Vector v = (Vector)tmp;
+ Vector<?> v = (Vector)tmp;
// There is no well defined order for WHEN_IN_FOCUSED_WINDOW
// bindings, but we give precedence to those bindings just
// added. This is done so that JMenus WHEN_IN_FOCUSED_WINDOW
@@ -279,11 +280,12 @@
// The're handled differently. The key is to let any JMenuBars
// process the event
if ( keyMap != null) {
- Vector v = (Vector)keyMap.get(JMenuBar.class);
+ @SuppressWarnings("unchecked")
+ Vector<JMenuBar> v = (Vector)keyMap.get(JMenuBar.class);
if (v != null) {
- Enumeration iter = v.elements();
+ Enumeration<JMenuBar> iter = v.elements();
while (iter.hasMoreElements()) {
- JMenuBar mb = (JMenuBar)iter.nextElement();
+ JMenuBar mb = iter.nextElement();
if ( mb.isShowing() && mb.isEnabled() ) { // don't want to give these out
boolean extended = (ksE != null) && !ksE.equals(ks);
if (extended) {
@@ -315,17 +317,18 @@
if (top == null) {
return;
}
- Hashtable keyMap = containerMap.get(top);
+ Hashtable<Object, Object> keyMap = containerMap.get(top);
if (keyMap == null) { // lazy evaluate one
keyMap = registerNewTopContainer(top);
}
// use the menubar class as the key
- Vector menuBars = (Vector)keyMap.get(JMenuBar.class);
+ @SuppressWarnings("unchecked")
+ Vector<Object> menuBars = (Vector)keyMap.get(JMenuBar.class);
if (menuBars == null) { // if we don't have a list of menubars,
// then make one.
- menuBars = new Vector();
+ menuBars = new Vector<>();
keyMap.put(JMenuBar.class, menuBars);
}
@@ -340,9 +343,9 @@
if (topContainer == null) {
return;
}
- Hashtable keyMap = containerMap.get(topContainer);
+ Hashtable<Object, Object> keyMap = containerMap.get(topContainer);
if (keyMap!=null) {
- Vector v = (Vector)keyMap.get(JMenuBar.class);
+ Vector<?> v = (Vector)keyMap.get(JMenuBar.class);
if (v != null) {
v.removeElement(mb);
if (v.isEmpty()) {
@@ -355,8 +358,8 @@
}
}
}
- protected Hashtable registerNewTopContainer(Container topContainer) {
- Hashtable keyMap = new Hashtable();
+ protected Hashtable<Object, Object> registerNewTopContainer(Container topContainer) {
+ Hashtable<Object, Object> keyMap = new Hashtable<>();
containerMap.put(topContainer, keyMap);
return keyMap;
}
--- a/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java Wed Jul 05 19:50:57 2017 +0200
@@ -98,7 +98,7 @@
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
}
- Comparator comparator = getComparator();
+ Comparator<? super Component> comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
@@ -134,7 +134,7 @@
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
}
- Comparator comparator = getComparator();
+ Comparator<? super Component> comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
@@ -158,7 +158,7 @@
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
}
- Comparator comparator = getComparator();
+ Comparator<? super Component> comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
@@ -182,7 +182,7 @@
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
}
- Comparator comparator = getComparator();
+ Comparator<? super Component> comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
@@ -233,7 +233,7 @@
// to be focusable by returning true here.
return true;
} else if (SunToolkit.isInstanceOf(aComponent, "javax.swing.JComboBox")) {
- JComboBox box = (JComboBox)aComponent;
+ JComboBox<?> box = (JComboBox)aComponent;
return box.getUI().isFocusTraversable(box);
} else if (aComponent instanceof JComponent) {
JComponent jComponent = (JComponent)aComponent;
@@ -256,10 +256,11 @@
out.writeObject(getComparator());
out.writeBoolean(getImplicitDownCycleTraversal());
}
+ @SuppressWarnings("unchecked") // Cast to (Comparator<? super Component>)
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
- setComparator((Comparator)in.readObject());
+ setComparator((Comparator<? super Component>)in.readObject());
setImplicitDownCycleTraversal(in.readBoolean());
}
}
--- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -222,7 +222,6 @@
MenuElement menuElement;
MenuElement subElements[];
MenuElement path[];
- Vector<MenuElement> tmp;
int selectionSize;
p = event.getPoint();
@@ -251,7 +250,8 @@
screenX = p.x;
screenY = p.y;
- tmp = (Vector<MenuElement>)selection.clone();
+ @SuppressWarnings("unchecked")
+ Vector<MenuElement> tmp = (Vector<MenuElement>)selection.clone();
selectionSize = tmp.size();
boolean success = false;
for (i=selectionSize - 1;i >= 0 && success == false; i--) {
@@ -386,7 +386,6 @@
int cWidth,cHeight;
MenuElement menuElement;
MenuElement subElements[];
- Vector<MenuElement> tmp;
int selectionSize;
SwingUtilities.convertPointToScreen(p,source);
@@ -394,7 +393,8 @@
screenX = p.x;
screenY = p.y;
- tmp = (Vector<MenuElement>)selection.clone();
+ @SuppressWarnings("unchecked")
+ Vector<MenuElement> tmp = (Vector<MenuElement>)selection.clone();
selectionSize = tmp.size();
for(i=selectionSize - 1 ; i >= 0 ; i--) {
menuElement = tmp.elementAt(i);
--- a/jdk/src/share/classes/javax/swing/MultiUIDefaults.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/MultiUIDefaults.java Wed Jul 05 19:50:57 2017 +0200
@@ -192,7 +192,7 @@
public synchronized String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
- Enumeration keys = keys();
+ Enumeration<?> keys = keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
sb.append(key + "=" + get(key) + ", ");
--- a/jdk/src/share/classes/javax/swing/PopupFactory.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/PopupFactory.java Wed Jul 05 19:50:57 2017 +0200
@@ -243,7 +243,8 @@
case HEAVY_WEIGHT_POPUP:
Popup popup = getHeavyWeightPopup(owner, contents, ownerX, ownerY);
if ((AccessController.doPrivileged(OSInfo.getOSTypeAction()) ==
- OSInfo.OSType.MACOSX) && (EmbeddedFrame.getAppletIfAncestorOf(owner) != null)) {
+ OSInfo.OSType.MACOSX) && (owner != null) &&
+ (EmbeddedFrame.getAppletIfAncestorOf(owner) != null)) {
((HeavyWeightPopup)popup).setCacheEnabled(false);
}
return popup;
@@ -401,13 +402,14 @@
* <code>Window</code> to a <code>List</code> of
* <code>HeavyWeightPopup</code>s.
*/
+ @SuppressWarnings("unchecked")
private static Map<Window, List<HeavyWeightPopup>> getHeavyWeightPopupCache() {
synchronized (HeavyWeightPopup.class) {
Map<Window, List<HeavyWeightPopup>> cache = (Map<Window, List<HeavyWeightPopup>>)SwingUtilities.appContextGet(
heavyWeightPopupCacheKey);
if (cache == null) {
- cache = new HashMap<Window, List<HeavyWeightPopup>>(2);
+ cache = new HashMap<>(2);
SwingUtilities.appContextPut(heavyWeightPopupCacheKey,
cache);
}
@@ -698,11 +700,12 @@
/**
* Returns the cache to use for heavy weight popups.
*/
+ @SuppressWarnings("unchecked")
private static List<LightWeightPopup> getLightWeightPopupCache() {
List<LightWeightPopup> cache = (List<LightWeightPopup>)SwingUtilities.appContextGet(
lightWeightPopupCacheKey);
if (cache == null) {
- cache = new ArrayList<LightWeightPopup>();
+ cache = new ArrayList<>();
SwingUtilities.appContextPut(lightWeightPopupCacheKey, cache);
}
return cache;
@@ -854,12 +857,13 @@
/**
* Returns the cache to use for medium weight popups.
*/
+ @SuppressWarnings("unchecked")
private static List<MediumWeightPopup> getMediumWeightPopupCache() {
List<MediumWeightPopup> cache = (List<MediumWeightPopup>)SwingUtilities.appContextGet(
mediumWeightPopupCacheKey);
if (cache == null) {
- cache = new ArrayList<MediumWeightPopup>();
+ cache = new ArrayList<>();
SwingUtilities.appContextPut(mediumWeightPopupCacheKey, cache);
}
return cache;
--- a/jdk/src/share/classes/javax/swing/RowFilter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/RowFilter.java Wed Jul 05 19:50:57 2017 +0200
@@ -175,8 +175,7 @@
*/
public static <M,I> RowFilter<M,I> regexFilter(String regex,
int... indices) {
- return (RowFilter<M,I>)new RegexFilter(Pattern.compile(regex),
- indices);
+ return new RegexFilter<M, I>(Pattern.compile(regex), indices);
}
/**
@@ -205,7 +204,7 @@
*/
public static <M,I> RowFilter<M,I> dateFilter(ComparisonType type,
Date date, int... indices) {
- return (RowFilter<M,I>)new DateFilter(type, date.getTime(), indices);
+ return new DateFilter<M, I>(type, date.getTime(), indices);
}
/**
@@ -231,7 +230,7 @@
*/
public static <M,I> RowFilter<M,I> numberFilter(ComparisonType type,
Number number, int... indices) {
- return (RowFilter<M,I>)new NumberFilter(type, number, indices);
+ return new NumberFilter<M, I>(type, number, indices);
}
/**
@@ -410,7 +409,7 @@
}
- private static abstract class GeneralFilter extends RowFilter<Object,Object> {
+ private static abstract class GeneralFilter<M, I> extends RowFilter<M, I> {
private int[] columns;
GeneralFilter(int[] columns) {
@@ -418,7 +417,8 @@
this.columns = columns;
}
- public boolean include(Entry<? extends Object,? extends Object> value){
+ @Override
+ public boolean include(Entry<? extends M, ? extends I> value){
int count = value.getValueCount();
if (columns.length > 0) {
for (int i = columns.length - 1; i >= 0; i--) {
@@ -429,8 +429,7 @@
}
}
}
- }
- else {
+ } else {
while (--count >= 0) {
if (include(value, count)) {
return true;
@@ -441,11 +440,11 @@
}
protected abstract boolean include(
- Entry<? extends Object,? extends Object> value, int index);
+ Entry<? extends M, ? extends I> value, int index);
}
- private static class RegexFilter extends GeneralFilter {
+ private static class RegexFilter<M, I> extends GeneralFilter<M, I> {
private Matcher matcher;
RegexFilter(Pattern regex, int[] columns) {
@@ -456,15 +455,16 @@
matcher = regex.matcher("");
}
+ @Override
protected boolean include(
- Entry<? extends Object,? extends Object> value, int index) {
+ Entry<? extends M, ? extends I> value, int index) {
matcher.reset(value.getStringValue(index));
return matcher.find();
}
}
- private static class DateFilter extends GeneralFilter {
+ private static class DateFilter<M, I> extends GeneralFilter<M, I> {
private long date;
private ComparisonType type;
@@ -477,8 +477,9 @@
this.date = date;
}
+ @Override
protected boolean include(
- Entry<? extends Object,? extends Object> value, int index) {
+ Entry<? extends M, ? extends I> value, int index) {
Object v = value.getValue(index);
if (v instanceof Date) {
@@ -500,10 +501,7 @@
}
}
-
-
-
- private static class NumberFilter extends GeneralFilter {
+ private static class NumberFilter<M, I> extends GeneralFilter<M, I> {
private boolean isComparable;
private Number number;
private ComparisonType type;
@@ -519,15 +517,16 @@
isComparable = (number instanceof Comparable);
}
+ @Override
@SuppressWarnings("unchecked")
protected boolean include(
- Entry<? extends Object,? extends Object> value, int index) {
+ Entry<? extends M, ? extends I> value, int index) {
Object v = value.getValue(index);
if (v instanceof Number) {
boolean compared = true;
int compareResult;
- Class vClass = v.getClass();
+ Class<?> vClass = v.getClass();
if (number.getClass() == vClass && isComparable) {
compareResult = ((Comparable)number).compareTo(v);
}
--- a/jdk/src/share/classes/javax/swing/ScrollPaneLayout.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/ScrollPaneLayout.java Wed Jul 05 19:50:57 2017 +0200
@@ -823,10 +823,7 @@
Rectangle vsbR = new Rectangle(0, availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
- if (isEmpty) {
- vsbNeeded = false;
- }
- else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
+ if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
@@ -849,10 +846,7 @@
Rectangle hsbR = new Rectangle(availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
- if (isEmpty) {
- hsbNeeded = false;
- }
- else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
+ if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
--- a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java Wed Jul 05 19:50:57 2017 +0200
@@ -30,6 +30,11 @@
import java.util.*;
import java.awt.FocusTraversalPolicy;
import sun.util.logging.PlatformLogger;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import sun.security.action.GetPropertyAction;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
/**
* A FocusTraversalPolicy that determines traversal order by sorting the
@@ -89,6 +94,34 @@
final private int FORWARD_TRAVERSAL = 0;
final private int BACKWARD_TRAVERSAL = 1;
+ /*
+ * When true (by default), the legacy merge-sort algo is used to sort an FTP cycle.
+ * When false, the default (tim-sort) algo is used, which may lead to an exception.
+ * See: JDK-8048887
+ */
+ private static final boolean legacySortingFTPEnabled;
+ private static final Method legacyMergeSortMethod;
+
+ static {
+ legacySortingFTPEnabled = "true".equals(AccessController.doPrivileged(
+ new GetPropertyAction("swing.legacySortingFTPEnabled", "true")));
+ legacyMergeSortMethod = legacySortingFTPEnabled ?
+ AccessController.doPrivileged(new PrivilegedAction<Method>() {
+ public Method run() {
+ try {
+ Class c = Class.forName("java.util.Arrays");
+ Method m = c.getDeclaredMethod("legacyMergeSort", new Class[]{Object[].class, Comparator.class});
+ m.setAccessible(true);
+ return m;
+ } catch (ClassNotFoundException | NoSuchMethodException e) {
+ // using default sorting algo
+ return null;
+ }
+ }
+ }) :
+ null;
+ }
+
/**
* Constructs a SortingFocusTraversalPolicy without a Comparator.
* Subclasses must set the Comparator using <code>setComparator</code>
@@ -135,10 +168,32 @@
private void enumerateAndSortCycle(Container focusCycleRoot, List<Component> cycle) {
if (focusCycleRoot.isShowing()) {
enumerateCycle(focusCycleRoot, cycle);
- Collections.sort(cycle, comparator);
+ if (!legacySortingFTPEnabled ||
+ !legacySort(cycle, comparator))
+ {
+ Collections.sort(cycle, comparator);
+ }
}
}
+ private boolean legacySort(List<Component> l, Comparator<? super Component> c) {
+ if (legacyMergeSortMethod == null)
+ return false;
+
+ Object[] a = l.toArray();
+ try {
+ legacyMergeSortMethod.invoke(null, a, c);
+ } catch (IllegalAccessException | InvocationTargetException e) {
+ return false;
+ }
+ ListIterator<Component> i = l.listIterator();
+ for (Object e : a) {
+ i.next();
+ i.set((Component)e);
+ }
+ return true;
+ }
+
private void enumerateCycle(Container container, List<Component> cycle) {
if (!(container.isVisible() && container.isDisplayable())) {
return;
--- a/jdk/src/share/classes/javax/swing/SpinnerDateModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/SpinnerDateModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -89,7 +89,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
public class SpinnerDateModel extends AbstractSpinnerModel implements Serializable
{
- private Comparable start, end;
+ private Comparable<Date> start, end;
private Calendar value;
private int calendarField;
@@ -173,7 +173,7 @@
* @see #setEnd
* @see #setCalendarField
*/
- public SpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField) {
+ public SpinnerDateModel(Date value, Comparable<Date> start, Comparable<Date> end, int calendarField) {
if (value == null) {
throw new IllegalArgumentException("value is null");
}
@@ -241,7 +241,7 @@
* @see #setEnd
* @see #addChangeListener
*/
- public void setStart(Comparable start) {
+ public void setStart(Comparable<Date> start) {
if ((start == null) ? (this.start != null) : !start.equals(this.start)) {
this.start = start;
fireStateChanged();
@@ -255,7 +255,7 @@
* @return the value of the <code>start</code> property
* @see #setStart
*/
- public Comparable getStart() {
+ public Comparable<Date> getStart() {
return start;
}
@@ -282,7 +282,7 @@
* @see #setStart
* @see #addChangeListener
*/
- public void setEnd(Comparable end) {
+ public void setEnd(Comparable<Date> end) {
if ((end == null) ? (this.end != null) : !end.equals(this.end)) {
this.end = end;
fireStateChanged();
@@ -296,7 +296,7 @@
* @return the value of the <code>end</code> property
* @see #setEnd
*/
- public Comparable getEnd() {
+ public Comparable<Date> getEnd() {
return end;
}
--- a/jdk/src/share/classes/javax/swing/SpinnerListModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/SpinnerListModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -59,7 +59,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
public class SpinnerListModel extends AbstractSpinnerModel implements Serializable
{
- private List list;
+ private List<?> list;
private int index;
--- a/jdk/src/share/classes/javax/swing/SpinnerNumberModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/SpinnerNumberModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -84,7 +84,16 @@
public class SpinnerNumberModel extends AbstractSpinnerModel implements Serializable
{
private Number stepSize, value;
- private Comparable minimum, maximum;
+ // Both minimum and maximum are logically Comparable<? extends
+ // Number>, but that type is awkward to use since different
+ // instances of Number are not naturally Comparable. For example,
+ // a Double implements Comparable<Double> and an Integer
+ // implements Comparable<Integer>. Neither Integer nor Double will
+ // have a bridge method for Comparable<Number>. However, it safe
+ // to cast Comparable<?> to Comparable<Object> since all
+ // Comparables will have a compare(Object> method, possibly as a
+ // bridge.
+ private Comparable<?> minimum, maximum;
/**
@@ -117,12 +126,16 @@
* <code>null</code> or if the following expression is false:
* <code>minimum <= value <= maximum</code>
*/
- public SpinnerNumberModel(Number value, Comparable minimum, Comparable maximum, Number stepSize) {
+ @SuppressWarnings("unchecked") // Casts to Comparable<Object>
+ public SpinnerNumberModel(Number value,
+ Comparable<?> minimum,
+ Comparable<?> maximum,
+ Number stepSize) {
if ((value == null) || (stepSize == null)) {
throw new IllegalArgumentException("value and stepSize must be non-null");
}
- if (!(((minimum == null) || (minimum.compareTo(value) <= 0)) &&
- ((maximum == null) || (maximum.compareTo(value) >= 0)))) {
+ if (!(((minimum == null) || (((Comparable<Object>)minimum).compareTo(value) <= 0)) &&
+ ((maximum == null) || (((Comparable<Object>)maximum).compareTo(value) >= 0)))) {
throw new IllegalArgumentException("(minimum <= value <= maximum) is false");
}
this.value = value;
@@ -212,7 +225,7 @@
* @see #setMaximum
* @see SpinnerModel#addChangeListener
*/
- public void setMinimum(Comparable minimum) {
+ public void setMinimum(Comparable<?> minimum) {
if ((minimum == null) ? (this.minimum != null) : !minimum.equals(this.minimum)) {
this.minimum = minimum;
fireStateChanged();
@@ -226,7 +239,7 @@
* @return the value of the <code>minimum</code> property
* @see #setMinimum
*/
- public Comparable getMinimum() {
+ public Comparable<?> getMinimum() {
return minimum;
}
@@ -259,7 +272,7 @@
* @see #setMinimum
* @see SpinnerModel#addChangeListener
*/
- public void setMaximum(Comparable maximum) {
+ public void setMaximum(Comparable<?> maximum) {
if ((maximum == null) ? (this.maximum != null) : !maximum.equals(this.maximum)) {
this.maximum = maximum;
fireStateChanged();
@@ -273,7 +286,7 @@
* @return the value of the <code>maximum</code> property
* @see #setMaximum
*/
- public Comparable getMaximum() {
+ public Comparable<?> getMaximum() {
return maximum;
}
@@ -317,7 +330,7 @@
return stepSize;
}
-
+ @SuppressWarnings("unchecked") // Casts to Comparable<Object>
private Number incrValue(int dir)
{
Number newValue;
@@ -329,8 +342,7 @@
else {
newValue = new Float(v);
}
- }
- else {
+ } else {
long v = value.longValue() + (stepSize.longValue() * (long)dir);
if (value instanceof Long) {
@@ -347,10 +359,10 @@
}
}
- if ((maximum != null) && (maximum.compareTo(newValue) < 0)) {
+ if ((maximum != null) && (((Comparable<Object>)maximum).compareTo(newValue) < 0)) {
return null;
}
- if ((minimum != null) && (minimum.compareTo(newValue) > 0)) {
+ if ((minimum != null) && (((Comparable<Object>)minimum).compareTo(newValue) > 0)) {
return null;
}
else {
--- a/jdk/src/share/classes/javax/swing/SpringLayout.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/SpringLayout.java Wed Jul 05 19:50:57 2017 +0200
@@ -495,7 +495,7 @@
};
}
- private boolean defined(List history, String s1, String s2) {
+ private boolean defined(List<?> history, String s1, String s2) {
return history.contains(s1) && history.contains(s2);
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/SwingContainer.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package javax.swing;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * An annotation used to specify some swing-related information
+ * for the automatically generated {@code BeanInfo} classes.
+ * This annotation is not used if the annotated class
+ * has a corresponding user-defined {@code BeanInfo} class,
+ * which does not imply the automatic analysis.
+ * <p>
+ * The {@code isContainer} {@link java.beans.BeanDescriptor#getValue
+ * feature attribute} was introduced primarily for the Swing library.
+ * All Swing components extend the {@link java.awt.Container Container}
+ * class by design, so the builder tool assumes that all Swing components
+ * are containers. The {@link java.beans.BeanInfo BeanInfo} classes
+ * with the {@code isContainer} attribute allow to directly specify
+ * whether a Swing component is a container or not.
+ *
+ * @since 1.9
+ *
+ * @author Sergey A. Malenkov
+ */
+@Target({TYPE})
+@Retention(RUNTIME)
+public @interface SwingContainer {
+ /**
+ * The value that indicates whether the annotated class can be used
+ * as a container for other Swing components or not.
+ *
+ * @return {@code true} if the annotated class is a Swing container;
+ * {@code false} otherwise.
+ */
+ boolean value() default true;
+
+ /**
+ * The name of the getter method in the annotated class,
+ * which returns the corresponding Swing container,
+ * if it is not recommended to add subcomponents
+ * to the annotated class directly.
+ *
+ * @return the name of the getter method in the annotated class,
+ * which returns the corresponding Swing container,
+ * or an empty string if the method name is not set.
+ */
+ String delegate() default "";
+}
--- a/jdk/src/share/classes/javax/swing/SwingWorker.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/SwingWorker.java Wed Jul 05 19:50:57 2017 +0200
@@ -820,7 +820,9 @@
doSubmit = new DoSubmitAccumulativeRunnable();
appContext.put(DO_SUBMIT_KEY, doSubmit);
}
- return (AccumulativeRunnable<Runnable>) doSubmit;
+ @SuppressWarnings("unchecked")
+ AccumulativeRunnable<Runnable> tmp = (AccumulativeRunnable<Runnable>) doSubmit;
+ return tmp;
}
}
private static class DoSubmitAccumulativeRunnable
--- a/jdk/src/share/classes/javax/swing/UIDefaults.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/UIDefaults.java Wed Jul 05 19:50:57 2017 +0200
@@ -311,10 +311,10 @@
} else {
b = ResourceBundle.getBundle(bundleName, l);
}
- Enumeration keys = b.getKeys();
+ Enumeration<String> keys = b.getKeys();
while (keys.hasMoreElements()) {
- String key = (String)keys.nextElement();
+ String key = keys.nextElement();
if (values.get(key) == null) {
Object value = b.getObject(key);
@@ -682,7 +682,7 @@
if (className != null) {
ReflectUtil.checkPackageAccess(className);
- Class cls = (Class)get(className);
+ Class<?> cls = (Class)get(className);
if (cls == null) {
if (uiClassLoader == null) {
cls = SwingUtilities.loadSystemClass(className);
@@ -695,13 +695,12 @@
put(className, cls);
}
}
- return cls;
+ @SuppressWarnings("unchecked")
+ Class<? extends ComponentUI> tmp = (Class<? extends ComponentUI>)cls;
+ return tmp;
}
}
- catch (ClassNotFoundException e) {
- return null;
- }
- catch (ClassCastException e) {
+ catch (ClassNotFoundException | ClassCastException e) {
return null;
}
return null;
@@ -767,7 +766,7 @@
try {
Method m = (Method)get(uiClass);
if (m == null) {
- m = uiClass.getMethod("createUI", new Class[]{JComponent.class});
+ m = uiClass.getMethod("createUI", new Class<?>[]{JComponent.class});
put(uiClass, m);
}
uiObject = MethodUtil.invoke(m, null, new Object[]{target});
@@ -1106,12 +1105,12 @@
c = Class.forName(className, true, (ClassLoader)cl);
SwingUtilities2.checkAccess(c.getModifiers());
if (methodName != null) {
- Class[] types = getClassArray(args);
+ Class<?>[] types = getClassArray(args);
Method m = c.getMethod(methodName, types);
return MethodUtil.invoke(m, c, args);
} else {
- Class[] types = getClassArray(args);
- Constructor constructor = c.getConstructor(types);
+ Class<?>[] types = getClassArray(args);
+ Constructor<?> constructor = c.getConstructor(types);
SwingUtilities2.checkAccess(constructor.getModifiers());
return constructor.newInstance(args);
}
@@ -1134,10 +1133,10 @@
* and superclasses for subclasses used to add the
* <code>UIResource</code> tag.
*/
- private Class[] getClassArray(Object[] args) {
- Class[] types = null;
+ private Class<?>[] getClassArray(Object[] args) {
+ Class<?>[] types = null;
if (args!=null) {
- types = new Class[args.length];
+ types = new Class<?>[args.length];
for (int i = 0; i< args.length; i++) {
/* PENDING(ges): At present only the primitive types
used are handled correctly; this should eventually
--- a/jdk/src/share/classes/javax/swing/UIManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/UIManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -581,7 +581,7 @@
setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
}
else {
- Class lnfClass = SwingUtilities.loadSystemClass(className);
+ Class<?> lnfClass = SwingUtilities.loadSystemClass(className);
setLookAndFeel((LookAndFeel)(lnfClass.newInstance()));
}
}
@@ -1049,7 +1049,7 @@
String defaultName = "javax.swing.plaf.multi.MultiLookAndFeel";
String className = getLAFState().swingProps.getProperty(multiplexingLAFKey, defaultName);
try {
- Class lnfClass = SwingUtilities.loadSystemClass(className);
+ Class<?> lnfClass = SwingUtilities.loadSystemClass(className);
multiLookAndFeel = (LookAndFeel)lnfClass.newInstance();
} catch (Exception exc) {
System.err.println("UIManager: failed loading " + className);
@@ -1339,10 +1339,11 @@
// Try to get default LAF from system property, then from AppContext
// (6653395), then use cross-platform one by default.
String lafName = null;
- HashMap lafData =
+ @SuppressWarnings("unchecked")
+ HashMap<Object, String> lafData =
(HashMap) AppContext.getAppContext().remove("swing.lafdata");
if (lafData != null) {
- lafName = (String) lafData.remove("defaultlaf");
+ lafName = lafData.remove("defaultlaf");
}
if (lafName == null) {
lafName = getCrossPlatformLookAndFeelClassName();
@@ -1382,7 +1383,7 @@
while (p.hasMoreTokens()) {
String className = p.nextToken();
try {
- Class lnfClass = SwingUtilities.loadSystemClass(className);
+ Class<?> lnfClass = SwingUtilities.loadSystemClass(className);
LookAndFeel newLAF = (LookAndFeel)lnfClass.newInstance();
newLAF.initialize();
auxLookAndFeels.addElement(newLAF);
--- a/jdk/src/share/classes/javax/swing/event/EventListenerList.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/event/EventListenerList.java Wed Jul 05 19:50:57 2017 +0200
@@ -141,11 +141,14 @@
public <T extends EventListener> T[] getListeners(Class<T> t) {
Object[] lList = listenerList;
int n = getListenerCount(lList, t);
+ @SuppressWarnings("unchecked")
T[] result = (T[])Array.newInstance(t, n);
int j = 0;
for (int i = lList.length-2; i>=0; i-=2) {
if (lList[i] == t) {
- result[j++] = (T)lList[i+1];
+ @SuppressWarnings("unchecked")
+ T tmp = (T)lList[i+1];
+ result[j++] = tmp;
}
}
return result;
@@ -172,7 +175,7 @@
return getListenerCount(lList, t);
}
- private int getListenerCount(Object[] list, Class t) {
+ private int getListenerCount(Object[] list, Class<?> t) {
int count = 0;
for (int i = 0; i < list.length; i+=2) {
if (t == (Class)list[i])
@@ -288,7 +291,9 @@
EventListener l = (EventListener)s.readObject();
String name = (String) listenerTypeOrNull;
ReflectUtil.checkPackageAccess(name);
- add((Class<EventListener>)Class.forName(name, true, cl), l);
+ @SuppressWarnings("unchecked")
+ Class<EventListener> tmp = (Class<EventListener>)Class.forName(name, true, cl);
+ add(tmp, l);
}
}
--- a/jdk/src/share/classes/javax/swing/event/RowSorterEvent.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/event/RowSorterEvent.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,7 +71,7 @@
* @throws IllegalArgumentException if <code>source</code> is
* <code>null</code>
*/
- public RowSorterEvent(RowSorter source) {
+ public RowSorterEvent(RowSorter<?> source) {
this(source, Type.SORT_ORDER_CHANGED, null);
}
@@ -85,7 +85,7 @@
* @throws IllegalArgumentException if source or <code>type</code> is
* <code>null</code>
*/
- public RowSorterEvent(RowSorter source, Type type,
+ public RowSorterEvent(RowSorter<?> source, Type type,
int[] previousRowIndexToModel) {
super(source);
if (type == null) {
@@ -100,7 +100,8 @@
*
* @return the source of the event as a <code>RowSorter</code>
*/
- public RowSorter getSource() {
+ @Override
+ public RowSorter<?> getSource() {
return (RowSorter)super.getSource();
}
--- a/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java Wed Jul 05 19:50:57 2017 +0200
@@ -739,7 +739,8 @@
* @return the Desktop folder.
*/
public File getHomeDirectory() {
- return getRoots()[0];
+ File[] roots = getRoots();
+ return (roots.length == 0) ? null : roots[0];
}
/**
--- a/jdk/src/share/classes/javax/swing/plaf/ComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/ComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -38,15 +38,15 @@
/**
* Set the visibility of the popup
*/
- public abstract void setPopupVisible( JComboBox c, boolean v );
+ public abstract void setPopupVisible( JComboBox<?> c, boolean v );
/**
* Determine the visibility of the popup
*/
- public abstract boolean isPopupVisible( JComboBox c );
+ public abstract boolean isPopupVisible( JComboBox<?> c );
/**
* Determine whether or not the combo box itself is traversable
*/
- public abstract boolean isFocusTraversable( JComboBox c );
+ public abstract boolean isFocusTraversable( JComboBox<?> c );
}
--- a/jdk/src/share/classes/javax/swing/plaf/LayerUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/LayerUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -610,7 +610,8 @@
* baseline
*/
public int getBaseline(JComponent c, int width, int height) {
- JLayer l = (JLayer) c;
+ @SuppressWarnings("unchecked")
+ JLayer<?> l = (JLayer) c;
if (l.getView() != null) {
return l.getView().getBaseline(width, height);
}
@@ -627,7 +628,8 @@
* size changes
*/
public Component.BaselineResizeBehavior getBaselineResizeBehavior(JComponent c) {
- JLayer l = (JLayer) c;
+ @SuppressWarnings("unchecked")
+ JLayer<?> l = (JLayer) c;
if (l.getView() != null) {
return l.getView().getBaselineResizeBehavior();
}
@@ -659,7 +661,8 @@
* @return preferred size for the passed {@code JLayer}
*/
public Dimension getPreferredSize(JComponent c) {
- JLayer l = (JLayer) c;
+ @SuppressWarnings("unchecked")
+ JLayer<?> l = (JLayer) c;
Component view = l.getView();
if (view != null) {
return view.getPreferredSize();
@@ -676,7 +679,8 @@
* @return minimal size for the passed {@code JLayer}
*/
public Dimension getMinimumSize(JComponent c) {
- JLayer l = (JLayer) c;
+ @SuppressWarnings("unchecked")
+ JLayer<?> l = (JLayer) c;
Component view = l.getView();
if (view != null) {
return view.getMinimumSize();
@@ -693,7 +697,8 @@
* @return maximum size for the passed {@code JLayer}
*/
public Dimension getMaximumSize(JComponent c) {
- JLayer l = (JLayer) c;
+ @SuppressWarnings("unchecked")
+ JLayer<?> l = (JLayer) c;
Component view = l.getView();
if (view != null) {
return view.getMaximumSize();
--- a/jdk/src/share/classes/javax/swing/plaf/ListUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/ListUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,7 @@
* @return the cell index closest to the given location, or {@code -1}
* @throws NullPointerException if {@code location} is null
*/
- public abstract int locationToIndex(JList list, Point location);
+ public abstract int locationToIndex(JList<?> list, Point location);
/**
@@ -62,7 +62,7 @@
* @param index the cell index
* @return the origin of the cell, or {@code null}
*/
- public abstract Point indexToLocation(JList list, int index);
+ public abstract Point indexToLocation(JList<?> list, int index);
/**
@@ -80,5 +80,5 @@
* @param index2 the second index in the range
* @return the bounding rectangle for the range of cells, or {@code null}
*/
- public abstract Rectangle getCellBounds(JList list, int index1, int index2);
+ public abstract Rectangle getCellBounds(JList<?> list, int index1, int index2);
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java Wed Jul 05 19:50:57 2017 +0200
@@ -100,7 +100,7 @@
// Must take the value from the editor and get the value and cast it to the new type.
Class<?> cls = oldValue.getClass();
try {
- Method method = MethodUtil.getMethod(cls, "valueOf", new Class[]{String.class});
+ Method method = MethodUtil.getMethod(cls, "valueOf", new Class<?>[]{String.class});
newValue = MethodUtil.invoke(method, oldValue, new Object[] { editor.getText()});
} catch (Exception ex) {
// Fail silently and return the newValue (a String object)
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxRenderer.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxRenderer.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,7 +49,7 @@
*/
@SuppressWarnings("serial") // Same-version serialization only
public class BasicComboBoxRenderer extends JLabel
-implements ListCellRenderer, Serializable {
+implements ListCellRenderer<Object>, Serializable {
/**
* An empty <code>Border</code>. This field might not be used. To change the
@@ -88,8 +88,8 @@
return size;
}
- public Component getListCellRendererComponent(
- JList list,
+ @Override
+ public Component getListCellRendererComponent(JList<?> list,
Object value,
int index,
boolean isSelected,
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -61,7 +61,7 @@
* @author Mark Davidson
*/
public class BasicComboBoxUI extends ComboBoxUI {
- protected JComboBox comboBox;
+ protected JComboBox<Object> comboBox;
/**
* This protected field is implementation specific. Do not access directly
* or override.
@@ -74,7 +74,7 @@
private static final String IS_TABLE_CELL_EDITOR = "JComboBox.isTableCellEditor";
// This list is for drawing the current item in the combo box.
- protected JList listBox;
+ protected JList<Object> listBox;
// Used to render the currently selected item in the combo box.
// It doesn't have anything to do with the popup's rendering.
@@ -203,8 +203,9 @@
protected Insets padding;
// Used for calculating the default size.
- private static ListCellRenderer getDefaultListCellRenderer() {
- ListCellRenderer renderer = (ListCellRenderer)AppContext.
+ private static ListCellRenderer<Object> getDefaultListCellRenderer() {
+ @SuppressWarnings("unchecked")
+ ListCellRenderer<Object> renderer = (ListCellRenderer)AppContext.
getAppContext().get(COMBO_UI_LIST_CELL_RENDERER_KEY);
if (renderer == null) {
@@ -245,7 +246,9 @@
public void installUI( JComponent c ) {
isMinimumSizeDirty = true;
- comboBox = (JComboBox)c;
+ @SuppressWarnings("unchecked")
+ JComboBox<Object> tmp = (JComboBox)c;
+ comboBox = tmp;
installDefaults();
popup = createPopup();
listBox = popup.getList();
@@ -508,7 +511,7 @@
* @return a <code>ListCellRender</code> used for the combo box
* @see javax.swing.JComboBox#setRenderer
*/
- protected ListCellRenderer createRenderer() {
+ protected ListCellRenderer<Object> createRenderer() {
return new BasicComboBoxRenderer.UIResource();
}
@@ -865,14 +868,14 @@
/**
* Tells if the popup is visible or not.
*/
- public boolean isPopupVisible( JComboBox c ) {
+ public boolean isPopupVisible( JComboBox<?> c ) {
return popup.isVisible();
}
/**
* Hides the popup.
*/
- public void setPopupVisible( JComboBox c, boolean v ) {
+ public void setPopupVisible( JComboBox<?> c, boolean v ) {
if ( v ) {
popup.show();
} else {
@@ -884,7 +887,7 @@
* Determines if the JComboBox is focus traversable. If the JComboBox is editable
* this returns false, otherwise it returns true.
*/
- public boolean isFocusTraversable( JComboBox c ) {
+ public boolean isFocusTraversable( JComboBox<?> c ) {
return !comboBox.isEditable();
}
@@ -956,7 +959,7 @@
Insets insets = c.getInsets();
height = height - insets.top - insets.bottom;
if (!comboBox.isEditable()) {
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
if (renderer == null) {
renderer = new DefaultListCellRenderer();
}
@@ -1013,7 +1016,7 @@
return editor.getBaselineResizeBehavior();
}
else if (sameBaseline) {
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
if (renderer == null) {
renderer = new DefaultListCellRenderer();
}
@@ -1205,7 +1208,7 @@
* Paints the currently selected item.
*/
public void paintCurrentValue(Graphics g,Rectangle bounds,boolean hasFocus) {
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
Component c;
if ( hasFocus && !isPopupVisible(comboBox) ) {
@@ -1322,7 +1325,7 @@
}
Dimension result = new Dimension();
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
if (renderer == null) {
renderer = new DefaultListCellRenderer();
}
@@ -1338,7 +1341,7 @@
} else {
// Calculate the dimension by iterating over all the elements in the combo
// box list.
- ComboBoxModel model = comboBox.getModel();
+ ComboBoxModel<Object> model = comboBox.getModel();
int modelSize = model.getSize();
int baseline = -1;
Dimension d;
@@ -1484,7 +1487,8 @@
public void actionPerformed( ActionEvent e ) {
String key = getName();
- JComboBox comboBox = (JComboBox)e.getSource();
+ @SuppressWarnings("unchecked")
+ JComboBox<Object> comboBox = (JComboBox)e.getSource();
BasicComboBoxUI ui = (BasicComboBoxUI)BasicLookAndFeel.getUIOfType(
comboBox.getUI(), BasicComboBoxUI.class);
if (key == HIDE) {
@@ -1625,7 +1629,7 @@
}
}
- private int getNextIndex(JComboBox comboBox, String key) {
+ private int getNextIndex(JComboBox<?> comboBox, String key) {
int listHeight = comboBox.getMaximumRowCount();
int selectedIndex = comboBox.getSelectedIndex();
@@ -1685,10 +1689,13 @@
comboBox.revalidate();
}
} else {
- JComboBox comboBox = (JComboBox)e.getSource();
+ @SuppressWarnings("unchecked")
+ JComboBox<?> comboBox = (JComboBox)e.getSource();
if ( propertyName == "model" ) {
- ComboBoxModel newModel = (ComboBoxModel)e.getNewValue();
- ComboBoxModel oldModel = (ComboBoxModel)e.getOldValue();
+ @SuppressWarnings("unchecked")
+ ComboBoxModel<?> newModel = (ComboBoxModel)e.getNewValue();
+ @SuppressWarnings("unchecked")
+ ComboBoxModel<?> oldModel = (ComboBoxModel)e.getOldValue();
if ( oldModel != null && listDataListener != null ) {
oldModel.removeListDataListener( listDataListener );
@@ -1897,7 +1904,8 @@
}
public void layoutContainer(Container parent) {
- JComboBox cb = (JComboBox)parent;
+ @SuppressWarnings("unchecked")
+ JComboBox<?> cb = (JComboBox)parent;
int width = cb.getWidth();
int height = cb.getHeight();
@@ -1959,7 +1967,7 @@
private String prefix = "";
private String typedString = "";
- public int selectionForKey(char aKey,ComboBoxModel aModel) {
+ public int selectionForKey(char aKey,ComboBoxModel<?> aModel) {
if (lastTime == 0L) {
prefix = "";
typedString = "";
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,11 +71,11 @@
public void removeListDataListener(ListDataListener l) {}
};
- static final ListModel EmptyListModel = new EmptyListModelClass();
+ static final ListModel<Object> EmptyListModel = new EmptyListModelClass();
private static Border LIST_BORDER = new LineBorder(Color.BLACK, 1);
- protected JComboBox comboBox;
+ protected JComboBox<Object> comboBox;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
@@ -83,7 +83,7 @@
* @see #getList
* @see #createList
*/
- protected JList list;
+ protected JList<Object> list;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the create method instead
@@ -229,7 +229,7 @@
/**
* Implementation of ComboPopup.getList().
*/
- public JList getList() {
+ public JList<Object> getList() {
return list;
}
@@ -303,7 +303,7 @@
* @param model The combo box model to install listeners
* @see #installComboBoxModelListeners
*/
- protected void uninstallComboBoxModelListeners( ComboBoxModel model ) {
+ protected void uninstallComboBoxModelListeners( ComboBoxModel<?> model ) {
if (model != null && listDataListener != null) {
model.removeListDataListener(listDataListener);
}
@@ -319,7 +319,7 @@
//===================================================================
// begin Initialization routines
//
- public BasicComboPopup( JComboBox combo ) {
+ public BasicComboPopup( JComboBox<Object> combo ) {
super();
setName("ComboPopup.popup");
comboBox = combo;
@@ -481,8 +481,8 @@
*
* @return a <code>JList</code> used to display the combo box items
*/
- protected JList createList() {
- return new JList( comboBox.getModel() ) {
+ protected JList<Object> createList() {
+ return new JList<Object>( comboBox.getModel() ) {
public void processMouseEvent(MouseEvent e) {
if (BasicGraphicsUtils.isMenuShortcutKeyDown(e)) {
// Fix for 4234053. Filter out the Control Key from the list.
@@ -610,7 +610,7 @@
* @param model The combo box model to install listeners
* @see #uninstallComboBoxModelListeners
*/
- protected void installComboBoxModelListeners( ComboBoxModel model ) {
+ protected void installComboBoxModelListeners( ComboBoxModel<?> model ) {
if (model != null && (listDataListener = createListDataListener()) != null) {
model.addListDataListener(listDataListener);
}
@@ -928,12 +928,15 @@
// PropertyChangeListener
//
public void propertyChange(PropertyChangeEvent e) {
- JComboBox comboBox = (JComboBox)e.getSource();
+ @SuppressWarnings("unchecked")
+ JComboBox<Object> comboBox = (JComboBox)e.getSource();
String propertyName = e.getPropertyName();
if ( propertyName == "model" ) {
- ComboBoxModel oldModel = (ComboBoxModel)e.getOldValue();
- ComboBoxModel newModel = (ComboBoxModel)e.getNewValue();
+ @SuppressWarnings("unchecked")
+ ComboBoxModel<Object> oldModel = (ComboBoxModel)e.getOldValue();
+ @SuppressWarnings("unchecked")
+ ComboBoxModel<Object> newModel = (ComboBoxModel)e.getNewValue();
uninstallComboBoxModelListeners(oldModel);
installComboBoxModelListeners(newModel);
@@ -955,7 +958,7 @@
ComponentOrientation o =(ComponentOrientation)e.getNewValue();
- JList list = getList();
+ JList<?> list = getList();
if (list!=null && list.getComponentOrientation()!=o) {
list.setComponentOrientation(o);
}
@@ -978,7 +981,8 @@
//
public void itemStateChanged( ItemEvent e ) {
if (e.getStateChange() == ItemEvent.SELECTED) {
- JComboBox comboBox = (JComboBox)e.getSource();
+ @SuppressWarnings("unchecked")
+ JComboBox<Object> comboBox = (JComboBox)e.getSource();
setListSelection(comboBox.getSelectedIndex());
}
}
@@ -1172,7 +1176,7 @@
// Set the cached value of the minimum row count
int minRowCount = Math.min( maxRowCount, comboBox.getItemCount() );
int height = 0;
- ListCellRenderer renderer = list.getCellRenderer();
+ ListCellRenderer<Object> renderer = list.getCellRenderer();
Object value = null;
for ( int i = 0; i < minRowCount; ++i ) {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -98,7 +98,7 @@
if (directories != null) {
return directories;
}
- Vector fls = getFiles();
+ Vector<File> fls = getFiles();
return directories;
}
}
@@ -317,7 +317,7 @@
if (isInterrupted()) {
return null;
}
- return new DoChangeContents(null, 0, new Vector(fileCache.subList(start, end)), start, fid);
+ return new DoChangeContents(null, 0, new Vector<>(fileCache.subList(start, end)), start, fid);
}
}
if (!fileCache.equals(newFileCache)) {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -436,7 +436,7 @@
}
protected MouseListener createDoubleClickListener(JFileChooser fc,
- JList list) {
+ JList<?> list) {
return new Handler(list);
}
@@ -445,12 +445,12 @@
}
private class Handler implements MouseListener, ListSelectionListener {
- JList list;
+ JList<?> list;
Handler() {
}
- Handler(JList list) {
+ Handler(JList<?> list) {
this.list = list;
}
@@ -506,7 +506,8 @@
if(!evt.getValueIsAdjusting()) {
JFileChooser chooser = getFileChooser();
FileSystemView fsv = chooser.getFileSystemView();
- JList list = (JList)evt.getSource();
+ @SuppressWarnings("unchecked")
+ JList<?> list = (JList)evt.getSource();
int fsm = chooser.getFileSelectionMode();
boolean useSetDirectory = usesSingleFilePane &&
@@ -570,7 +571,7 @@
// new functionality add it to the Handler, but make sure this
// class calls into the Handler.
Handler handler;
- public DoubleClickListener(JList list) {
+ public DoubleClickListener(JList<?> list) {
handler = new Handler(list);
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicListUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicListUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -59,7 +59,7 @@
private static final StringBuilder BASELINE_COMPONENT_KEY =
new StringBuilder("List.baselineComponent");
- protected JList list = null;
+ protected JList<Object> list = null;
protected CellRendererPane rendererPane;
// Listeners that this UI attaches to the JList
@@ -196,8 +196,8 @@
Graphics g,
int row,
Rectangle rowBounds,
- ListCellRenderer cellRenderer,
- ListModel dataModel,
+ ListCellRenderer<Object> cellRenderer,
+ ListModel<Object> dataModel,
ListSelectionModel selModel,
int leadIndex)
{
@@ -263,8 +263,8 @@
}
maybeUpdateLayoutState();
- ListCellRenderer renderer = list.getCellRenderer();
- ListModel dataModel = list.getModel();
+ ListCellRenderer<Object> renderer = list.getCellRenderer();
+ ListModel<Object> dataModel = list.getModel();
ListSelectionModel selModel = list.getSelectionModel();
int size;
@@ -478,7 +478,8 @@
Component renderer = (Component)lafDefaults.get(
BASELINE_COMPONENT_KEY);
if (renderer == null) {
- ListCellRenderer lcr = (ListCellRenderer)UIManager.get(
+ @SuppressWarnings("unchecked")
+ ListCellRenderer<Object> lcr = (ListCellRenderer)UIManager.get(
"List.cellRenderer");
// fix for 6711072 some LAFs like Nimbus do not provide this
@@ -715,7 +716,7 @@
list.addPropertyChangeListener(propertyChangeListener);
list.addKeyListener(getHandler());
- ListModel model = list.getModel();
+ ListModel<Object> model = list.getModel();
if (model != null) {
model.addListDataListener(listDataListener);
}
@@ -744,7 +745,7 @@
list.removePropertyChangeListener(propertyChangeListener);
list.removeKeyListener(getHandler());
- ListModel model = list.getModel();
+ ListModel<Object> model = list.getModel();
if (model != null) {
model.removeListDataListener(listDataListener);
}
@@ -785,7 +786,9 @@
LookAndFeel.installProperty(list, "opaque", Boolean.TRUE);
if (list.getCellRenderer() == null) {
- list.setCellRenderer((ListCellRenderer)(UIManager.get("List.cellRenderer")));
+ @SuppressWarnings("unchecked")
+ ListCellRenderer<Object> tmp = (ListCellRenderer)(UIManager.get("List.cellRenderer"));
+ list.setCellRenderer(tmp);
}
Color sbg = list.getSelectionBackground();
@@ -866,7 +869,9 @@
*/
public void installUI(JComponent c)
{
- list = (JList)c;
+ @SuppressWarnings("unchecked")
+ JList<Object> tmp = (JList)c;
+ list = tmp;
layoutOrientation = list.getLayoutOrientation();
@@ -925,7 +930,7 @@
* {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
- public int locationToIndex(JList list, Point location) {
+ public int locationToIndex(JList<?> list, Point location) {
maybeUpdateLayoutState();
return convertLocationToModel(location.x, location.y);
}
@@ -934,7 +939,7 @@
/**
* {@inheritDoc}
*/
- public Point indexToLocation(JList list, int index) {
+ public Point indexToLocation(JList<?> list, int index) {
maybeUpdateLayoutState();
Rectangle rect = getCellBounds(list, index, index);
@@ -948,7 +953,7 @@
/**
* {@inheritDoc}
*/
- public Rectangle getCellBounds(JList list, int index1, int index2) {
+ public Rectangle getCellBounds(JList<?> list, int index1, int index2) {
maybeUpdateLayoutState();
int minIndex = Math.min(index1, index2);
@@ -992,7 +997,7 @@
* Gets the bounds of the specified model index, returning the resulting
* bounds, or null if <code>index</code> is not valid.
*/
- private Rectangle getCellBounds(JList list, int index) {
+ private Rectangle getCellBounds(JList<?> list, int index) {
maybeUpdateLayoutState();
int row = convertModelToRow(index);
@@ -1351,9 +1356,9 @@
if ((fixedCellWidth == -1) || (fixedCellHeight == -1)) {
- ListModel dataModel = list.getModel();
+ ListModel<Object> dataModel = list.getModel();
int dataModelSize = dataModel.getSize();
- ListCellRenderer renderer = list.getCellRenderer();
+ ListCellRenderer<Object> renderer = list.getCellRenderer();
if (renderer != null) {
for(int index = 0; index < dataModelSize; index++) {
@@ -1838,7 +1843,8 @@
}
public void actionPerformed(ActionEvent e) {
String name = getName();
- JList list = (JList)e.getSource();
+ @SuppressWarnings("unchecked")
+ JList<Object> list = (JList)e.getSource();
BasicListUI ui = (BasicListUI)BasicLookAndFeel.getUIOfType(
list.getUI(), BasicListUI.class);
@@ -1997,11 +2003,11 @@
return true;
}
- private void clearSelection(JList list) {
+ private void clearSelection(JList<?> list) {
list.clearSelection();
}
- private void selectAll(JList list) {
+ private void selectAll(JList<?> list) {
int size = list.getModel().getSize();
if (size > 0) {
ListSelectionModel lsm = list.getSelectionModel();
@@ -2030,7 +2036,7 @@
}
}
- private int getNextPageIndex(JList list, int direction) {
+ private int getNextPageIndex(JList<?> list, int direction) {
if (list.getModel().getSize() == 0) {
return -1;
}
@@ -2155,7 +2161,7 @@
return index;
}
- private void changeSelection(JList list, int type,
+ private void changeSelection(JList<?> list, int type,
int index, int direction) {
if (index >= 0 && index < list.getModel().getSize()) {
ListSelectionModel lsm = list.getSelectionModel();
@@ -2198,7 +2204,7 @@
* index. When scroll up makes selected index the first visible index.
* Adjust visible rectangle respect to list's component orientation.
*/
- private void adjustScrollPositionIfNecessary(JList list, int index,
+ private void adjustScrollPositionIfNecessary(JList<?> list, int index,
int direction) {
if (direction == 0) {
return;
@@ -2286,7 +2292,7 @@
}
}
- private int getNextColumnIndex(JList list, BasicListUI ui,
+ private int getNextColumnIndex(JList<?> list, BasicListUI ui,
int amount) {
if (list.getLayoutOrientation() != JList.VERTICAL) {
int index = adjustIndex(list.getLeadSelectionIndex(), list);
@@ -2319,7 +2325,7 @@
return -1;
}
- private int getNextIndex(JList list, BasicListUI ui, int amount) {
+ private int getNextIndex(JList<?> list, BasicListUI ui, int amount) {
int index = adjustIndex(list.getLeadSelectionIndex(), list);
int size = list.getModel().getSize();
@@ -2371,8 +2377,8 @@
* of the same letters followed by first typed another letter.
*/
public void keyTyped(KeyEvent e) {
- JList src = (JList)e.getSource();
- ListModel model = src.getModel();
+ JList<?> src = (JList)e.getSource();
+ ListModel<?> model = src.getModel();
if (model.getSize() == 0 || e.isAltDown() ||
BasicGraphicsUtils.isMenuShortcutKeyDown(e) ||
@@ -2468,8 +2474,10 @@
* listDataListener from the old model and add it to the new one.
*/
if (propertyName == "model") {
- ListModel oldModel = (ListModel)e.getOldValue();
- ListModel newModel = (ListModel)e.getNewValue();
+ @SuppressWarnings("unchecked")
+ ListModel<?> oldModel = (ListModel)e.getOldValue();
+ @SuppressWarnings("unchecked")
+ ListModel<?> newModel = (ListModel)e.getNewValue();
if (oldModel != null) {
oldModel.removeListDataListener(listDataListener);
}
@@ -2828,7 +2836,7 @@
}
}
- private static int adjustIndex(int index, JList list) {
+ private static int adjustIndex(int index, JList<?> list) {
return index < list.getModel().getSize() ? index : -1;
}
@@ -2848,7 +2856,7 @@
*/
protected Transferable createTransferable(JComponent c) {
if (c instanceof JList) {
- JList list = (JList) c;
+ JList<?> list = (JList) c;
Object[] values = list.getSelectedValues();
if (values == null || values.length == 0) {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java Wed Jul 05 19:50:57 2017 +0200
@@ -1861,7 +1861,7 @@
* Returns the ui that is of type <code>klass</code>, or null if
* one can not be found.
*/
- static Object getUIOfType(ComponentUI ui, Class klass) {
+ static Object getUIOfType(ComponentUI ui, Class<?> klass) {
if (klass.isInstance(ui)) {
return ui;
}
@@ -2256,4 +2256,4 @@
}
}
}
-}
\ No newline at end of file
+}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -609,7 +609,7 @@
MenuElement path[] = e.getPath();
if (key == Character.toLowerCase(e.getKeyChar())) {
JPopupMenu popupMenu = ((JMenu)menuItem).getPopupMenu();
- ArrayList newList = new ArrayList(Arrays.asList(path));
+ ArrayList<MenuElement> newList = new ArrayList<>(Arrays.asList(path));
newList.add(popupMenu);
MenuElement subs[] = popupMenu.getSubElements();
MenuElement sub =
@@ -619,7 +619,7 @@
}
MenuSelectionManager manager = e.getMenuSelectionManager();
MenuElement newPath[] = new MenuElement[0];;
- newPath = (MenuElement[]) newList.toArray(newPath);
+ newPath = newList.toArray(newPath);
manager.setSelectedPath(newPath);
e.consume();
}
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -450,7 +450,7 @@
if (sValues != null) {
if (sValues.length < 20) {
- JComboBox cBox = new JComboBox();
+ JComboBox<Object> cBox = new JComboBox<>();
cBox.setName("OptionPane.comboBox");
for(int counter = 0, maxCounter = sValues.length;
@@ -464,7 +464,7 @@
toAdd = cBox;
} else {
- JList list = new JList(sValues);
+ JList<Object> list = new JList<>(sValues);
JScrollPane sp = new JScrollPane(list);
sp.setName("OptionPane.scrollPane");
@@ -1232,7 +1232,7 @@
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
- JList list = (JList)e.getSource();
+ JList<?> list = (JList)e.getSource();
int index = list.locationToIndex(e.getPoint());
optionPane.setInputValue(list.getModel().getElementAt(index));
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicScrollBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicScrollBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1265,7 +1265,7 @@
JViewport viewport = scrollpane.getViewport();
Component view = viewport.getView();
if (view instanceof JList) {
- JList list = (JList)view;
+ JList<?> list = (JList)view;
if (DefaultLookup.getBoolean(list, list.getUI(),
"List.lockToPositionOnScroll", false)) {
int adjustedValue = value;
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicSliderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicSliderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -397,13 +397,13 @@
protected boolean labelsHaveSameBaselines() {
if (!checkedLabelBaselines) {
checkedLabelBaselines = true;
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<?, JComponent> dictionary = slider.getLabelTable();
if (dictionary != null) {
sameLabelBaselines = true;
- Enumeration elements = dictionary.elements();
+ Enumeration<JComponent> elements = dictionary.elements();
int baseline = -1;
while (elements.hasMoreElements()) {
- JComponent label = (JComponent) elements.nextElement();
+ JComponent label = elements.nextElement();
Dimension pref = label.getPreferredSize();
int labelBaseline = label.getBaseline(pref.width,
pref.height);
@@ -753,12 +753,12 @@
}
protected int getWidthOfWidestLabel() {
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<?, JComponent> dictionary = slider.getLabelTable();
int widest = 0;
if ( dictionary != null ) {
- Enumeration keys = dictionary.keys();
+ Enumeration<?> keys = dictionary.keys();
while ( keys.hasMoreElements() ) {
- JComponent label = (JComponent) dictionary.get(keys.nextElement());
+ JComponent label = dictionary.get(keys.nextElement());
widest = Math.max( label.getPreferredSize().width, widest );
}
}
@@ -766,12 +766,12 @@
}
protected int getHeightOfTallestLabel() {
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<?, JComponent> dictionary = slider.getLabelTable();
int tallest = 0;
if ( dictionary != null ) {
- Enumeration keys = dictionary.keys();
+ Enumeration<?> keys = dictionary.keys();
while ( keys.hasMoreElements() ) {
- JComponent label = (JComponent) dictionary.get(keys.nextElement());
+ JComponent label = dictionary.get(keys.nextElement());
tallest = Math.max( label.getPreferredSize().height, tallest );
}
}
@@ -842,18 +842,18 @@
* @since 1.6
*/
protected Integer getHighestValue() {
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<Integer, ?> dictionary = slider.getLabelTable();
if (dictionary == null) {
return null;
}
- Enumeration keys = dictionary.keys();
+ Enumeration<Integer> keys = dictionary.keys();
Integer max = null;
while (keys.hasMoreElements()) {
- Integer i = (Integer) keys.nextElement();
+ Integer i = keys.nextElement();
if (max == null || i > max) {
max = i;
@@ -871,18 +871,18 @@
* @since 1.6
*/
protected Integer getLowestValue() {
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<Integer, JComponent> dictionary = slider.getLabelTable();
if (dictionary == null) {
return null;
}
- Enumeration keys = dictionary.keys();
+ Enumeration<Integer> keys = dictionary.keys();
Integer min = null;
while (keys.hasMoreElements()) {
- Integer i = (Integer) keys.nextElement();
+ Integer i = keys.nextElement();
if (min == null || i < min) {
min = i;
@@ -1121,17 +1121,17 @@
public void paintLabels( Graphics g ) {
Rectangle labelBounds = labelRect;
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<Integer, JComponent> dictionary = slider.getLabelTable();
if ( dictionary != null ) {
- Enumeration keys = dictionary.keys();
+ Enumeration<Integer> keys = dictionary.keys();
int minValue = slider.getMinimum();
int maxValue = slider.getMaximum();
boolean enabled = slider.isEnabled();
while ( keys.hasMoreElements() ) {
- Integer key = (Integer)keys.nextElement();
+ Integer key = keys.nextElement();
int value = key.intValue();
if (value >= minValue && value <= maxValue) {
- JComponent label = (JComponent) dictionary.get(key);
+ JComponent label = dictionary.get(key);
label.setEnabled(enabled);
if (label instanceof JLabel) {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -707,7 +707,7 @@
iterator.first();
do {
- Map attrs = iterator.getAttributes();
+ Map<?, ?> attrs = iterator.getAttributes();
if (attrs != null && attrs.containsKey(field)){
int start = iterator.getRunStart(field);
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTableHeaderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTableHeaderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -103,7 +103,7 @@
if (e.getClickCount() % 2 == 1 &&
SwingUtilities.isLeftMouseButton(e)) {
JTable table = header.getTable();
- RowSorter sorter;
+ RowSorter<?> sorter;
if (table != null && (sorter = table.getRowSorter()) != null) {
int columnIndex = header.columnAtPoint(e.getPoint());
if (columnIndex != -1) {
@@ -772,9 +772,9 @@
*/
public Dimension getMinimumSize(JComponent c) {
long width = 0;
- Enumeration enumeration = header.getColumnModel().getColumns();
+ Enumeration<TableColumn> enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
- TableColumn aColumn = (TableColumn)enumeration.nextElement();
+ TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getMinWidth();
}
return createHeaderSize(width);
@@ -788,9 +788,9 @@
*/
public Dimension getPreferredSize(JComponent c) {
long width = 0;
- Enumeration enumeration = header.getColumnModel().getColumns();
+ Enumeration<TableColumn> enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
- TableColumn aColumn = (TableColumn)enumeration.nextElement();
+ TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createHeaderSize(width);
@@ -802,9 +802,9 @@
*/
public Dimension getMaximumSize(JComponent c) {
long width = 0;
- Enumeration enumeration = header.getColumnModel().getColumns();
+ Enumeration<TableColumn> enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
- TableColumn aColumn = (TableColumn)enumeration.nextElement();
+ TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getMaxWidth();
}
return createHeaderSize(width);
@@ -875,7 +875,7 @@
String name = getName();
if (TOGGLE_SORT_ORDER == name) {
JTable table = th.getTable();
- RowSorter sorter = table == null ? null : table.getRowSorter();
+ RowSorter<?> sorter = table == null ? null : table.getRowSorter();
if (sorter != null) {
int columnIndex = ui.getSelectedColumnIndex();
columnIndex = table.convertColumnIndexToModel(
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTableUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTableUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1710,9 +1710,9 @@
*/
public Dimension getMinimumSize(JComponent c) {
long width = 0;
- Enumeration enumeration = table.getColumnModel().getColumns();
+ Enumeration<TableColumn> enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
- TableColumn aColumn = (TableColumn)enumeration.nextElement();
+ TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getMinWidth();
}
return createTableSize(width);
@@ -1725,9 +1725,9 @@
*/
public Dimension getPreferredSize(JComponent c) {
long width = 0;
- Enumeration enumeration = table.getColumnModel().getColumns();
+ Enumeration<TableColumn> enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
- TableColumn aColumn = (TableColumn)enumeration.nextElement();
+ TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createTableSize(width);
@@ -1740,9 +1740,9 @@
*/
public Dimension getMaximumSize(JComponent c) {
long width = 0;
- Enumeration enumeration = table.getColumnModel().getColumns();
+ Enumeration<TableColumn> enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
- TableColumn aColumn = (TableColumn)enumeration.nextElement();
+ TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getMaxWidth();
}
return createTableSize(width);
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1148,7 +1148,7 @@
Insets insets = tree.getInsets();
TreePath initialPath = getClosestPathForLocation
(tree, 0, paintBounds.y);
- Enumeration paintingEnumerator = treeState.getVisiblePathsFrom
+ Enumeration<?> paintingEnumerator = treeState.getVisiblePathsFrom
(initialPath);
int row = treeState.getRowForPath(initialPath);
int endY = paintBounds.y + paintBounds.height;
@@ -1694,7 +1694,7 @@
if(treeState != null) {
treeState.setExpandedState(path, true);
- Enumeration descendants = tree.getExpandedDescendants(path);
+ Enumeration<?> descendants = tree.getExpandedDescendants(path);
if(descendants != null) {
while(descendants.hasMoreElements()) {
--- a/jdk/src/share/classes/javax/swing/plaf/basic/ComboPopup.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/ComboPopup.java Wed Jul 05 19:50:57 2017 +0200
@@ -70,7 +70,7 @@
* This method is highly implementation specific and should not be used
* for general list manipulation.
*/
- public JList getList();
+ public JList<Object> getList();
/**
* Returns a mouse listener that will be added to the combo box or null.
--- a/jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java Wed Jul 05 19:50:57 2017 +0200
@@ -56,7 +56,7 @@
* @param defaultsKey Key to use to defaults table to check for
* existing map and what resulting Map will be registered on.
*/
- static void installLazyActionMap(JComponent c, Class loaderClass,
+ static void installLazyActionMap(JComponent c, Class<?> loaderClass,
String defaultsKey) {
ActionMap map = (ActionMap)UIManager.get(defaultsKey);
if (map == null) {
@@ -79,7 +79,7 @@
* @param defaultsKey Key to use to defaults table to check for
* existing map and what resulting Map will be registered on.
*/
- static ActionMap getActionMap(Class loaderClass,
+ static ActionMap getActionMap(Class<?> loaderClass,
String defaultsKey) {
ActionMap map = (ActionMap)UIManager.get(defaultsKey);
if (map == null) {
@@ -90,7 +90,7 @@
}
- private LazyActionMap(Class loader) {
+ private LazyActionMap(Class<?> loader) {
_loader = loader;
}
@@ -146,7 +146,7 @@
Class<?> klass = (Class<?>)loader;
try {
Method method = klass.getDeclaredMethod("loadActionMap",
- new Class[] { LazyActionMap.class });
+ new Class<?>[] { LazyActionMap.class });
method.invoke(klass, new Object[] { this });
} catch (NoSuchMethodException nsme) {
assert false : "LazyActionMap unable to load actions " +
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -67,6 +67,7 @@
private static BumpBuffer createBuffer(GraphicsConfiguration gc,
Color topColor, Color shadowColor, Color backColor) {
AppContext context = AppContext.getAppContext();
+ @SuppressWarnings("unchecked")
List<BumpBuffer> buffers = (List<BumpBuffer>) context.get(METAL_BUMPS);
if (buffers == null) {
buffers = new ArrayList<BumpBuffer>();
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxButton.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxButton.java Wed Jul 05 19:50:57 2017 +0200
@@ -54,12 +54,12 @@
/**
* The instance of {@code JComboBox}.
*/
- protected JComboBox comboBox;
+ protected JComboBox<Object> comboBox;
/**
* The instance of {@code JList}.
*/
- protected JList listBox;
+ protected JList<Object> listBox;
/**
* The instance of {@code CellRendererPane}.
@@ -81,14 +81,14 @@
*
* @return the {@code JComboBox}
*/
- public final JComboBox getComboBox() { return comboBox;}
+ public final JComboBox<Object> getComboBox() { return comboBox;}
/**
* Sets the {@code JComboBox}.
*
* @param cb the {@code JComboBox}
*/
- public final void setComboBox( JComboBox cb ) { comboBox = cb;}
+ public final void setComboBox( JComboBox<Object> cb ) { comboBox = cb;}
/**
* Returns the icon of the {@code JComboBox}.
@@ -136,8 +136,8 @@
* @param pane an instance of {@code CellRendererPane}
* @param list an instance of {@code JList}
*/
- public MetalComboBoxButton( JComboBox cb, Icon i,
- CellRendererPane pane, JList list ) {
+ public MetalComboBoxButton( JComboBox<Object> cb, Icon i,
+ CellRendererPane pane, JList<Object> list ) {
this();
comboBox = cb;
comboIcon = i;
@@ -155,8 +155,8 @@
* @param pane an instance of {@code CellRendererPane}
* @param list an instance of {@code JList}
*/
- public MetalComboBoxButton( JComboBox cb, Icon i, boolean onlyIcon,
- CellRendererPane pane, JList list ) {
+ public MetalComboBoxButton( JComboBox<Object> cb, Icon i, boolean onlyIcon,
+ CellRendererPane pane, JList<Object> list ) {
this( cb, i, pane, list );
iconOnly = onlyIcon;
}
@@ -238,7 +238,7 @@
// Let the renderer paint
if ( ! iconOnly && comboBox != null ) {
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
Component c;
boolean renderPressed = getModel().isPressed();
c = renderer.getListCellRendererComponent(listBox,
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -391,7 +391,7 @@
*
* @param cBox an instance of {@code JComboBox}
*/
- public MetalComboPopup( JComboBox cBox) {
+ public MetalComboPopup( JComboBox<Object> cBox) {
super( cBox );
}
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -58,7 +58,7 @@
// made most things in this class private.
private JLabel lookInLabel;
- private JComboBox directoryComboBox;
+ private JComboBox<Object> directoryComboBox;
private DirectoryComboBoxModel directoryComboBoxModel;
private Action directoryComboBoxAction = new DirectoryComboBoxAction();
@@ -76,7 +76,7 @@
private JPanel buttonPanel;
private JPanel bottomPanel;
- private JComboBox filterComboBox;
+ private JComboBox<?> filterComboBox;
private static final Dimension hstrut5 = new Dimension(5, 1);
private static final Dimension hstrut11 = new Dimension(11, 1);
@@ -204,7 +204,7 @@
return MetalFileChooserUI.this.getNewFolderAction();
}
- public MouseListener createDoubleClickListener(JList list) {
+ public MouseListener createDoubleClickListener(JList<?> list) {
return MetalFileChooserUI.this.createDoubleClickListener(getFileChooser(),
list);
}
@@ -243,7 +243,7 @@
// CurrentDir ComboBox
@SuppressWarnings("serial") // anonymous class
- JComboBox tmp1 = new JComboBox() {
+ JComboBox<Object> tmp1 = new JComboBox<Object>() {
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
// Must be small enough to not affect total width.
@@ -426,7 +426,7 @@
filterComboBoxModel = createFilterComboBoxModel();
fc.addPropertyChangeListener(filterComboBoxModel);
- filterComboBox = new JComboBox(filterComboBoxModel);
+ filterComboBox = new JComboBox<>(filterComboBoxModel);
filterComboBox.putClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY,
filesOfTypeLabelText);
filesOfTypeLabel.setLabelFor(filterComboBox);
@@ -578,7 +578,7 @@
*
* @param list an instance of {@code JList}
*/
- public SingleClickListener(JList list) {
+ public SingleClickListener(JList<?> list) {
}
}
@@ -927,7 +927,7 @@
@SuppressWarnings("serial") // Superclass is not serializable across versions
class DirectoryComboBoxRenderer extends DefaultListCellRenderer {
IndentIcon ii = new IndentIcon();
- public Component getListCellRendererComponent(JList list, Object value,
+ public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected,
boolean cellHasFocus) {
@@ -1131,7 +1131,7 @@
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
public class FilterComboBoxRenderer extends DefaultListCellRenderer {
- public Component getListCellRendererComponent(JList list,
+ public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -117,7 +117,7 @@
* that shares the JRootPane ancestor of <code>from</code>.
*/
synchronized static Object findRegisteredComponentOfType(JComponent from,
- Class target) {
+ Class<?> target) {
JRootPane rp = SwingUtilities.getRootPane(from);
if (rp != null) {
for (int counter = components.size() - 1; counter >= 0; counter--){
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalUtils.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalUtils.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -210,7 +210,8 @@
*/
static boolean drawGradient(Component c, Graphics g, String key,
int x, int y, int w, int h, boolean vertical) {
- java.util.List gradient = (java.util.List)UIManager.get(key);
+ @SuppressWarnings("unchecked")
+ java.util.List<?> gradient = (java.util.List)UIManager.get(key);
if (gradient == null || !(g instanceof Graphics2D)) {
return false;
}
@@ -251,7 +252,7 @@
}
public void paint(Component c, Graphics2D g,
- java.util.List gradient, int x, int y, int w,
+ java.util.List<?> gradient, int x, int y, int w,
int h, boolean isVertical) {
int imageWidth;
int imageHeight;
@@ -274,7 +275,8 @@
protected void paintToImage(Component c, Image image, Graphics g,
int w, int h, Object[] args) {
Graphics2D g2 = (Graphics2D)g;
- java.util.List gradient = (java.util.List)args[0];
+ @SuppressWarnings("unchecked")
+ java.util.List<?> gradient = (java.util.List)args[0];
boolean isVertical = ((Boolean)args[1]).booleanValue();
// Render to the VolatileImage
if (isVertical) {
--- a/jdk/src/share/classes/javax/swing/plaf/metal/OceanTheme.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/OceanTheme.java Wed Jul 05 19:50:57 2017 +0200
@@ -133,7 +133,7 @@
UIDefaults.LazyValue focusBorder = t ->
new BorderUIResource.LineBorderUIResource(getPrimary1());
// .30 0 DDE8F3 white secondary2
- java.util.List buttonGradient = Arrays.asList(
+ java.util.List<?> buttonGradient = Arrays.asList(
new Object[] {new Float(.3f), new Float(0f),
new ColorUIResource(0xDDE8F3), getWhite(), getSecondary2() });
@@ -149,7 +149,7 @@
Color c8ddf2 = new ColorUIResource(0xC8DDF2);
Object directoryIcon = getIconResource("icons/ocean/directory.gif");
Object fileIcon = getIconResource("icons/ocean/file.gif");
- java.util.List sliderGradient = Arrays.asList(new Object[] {
+ java.util.List<?> sliderGradient = Arrays.asList(new Object[] {
new Float(.3f), new Float(.2f),
c8ddf2, getWhite(), new ColorUIResource(SECONDARY2) });
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiButtonUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiButtonUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiButtonUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiButtonUI) mui).uis,
- a);
+ MultiButtonUI mui = new MultiButtonUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis,a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiColorChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiColorChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiColorChooserUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiColorChooserUI) mui).uis,
- a);
+ MultiColorChooserUI mui = new MultiColorChooserUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -75,7 +75,7 @@
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
- public boolean isFocusTraversable(JComboBox a) {
+ public boolean isFocusTraversable(JComboBox<?> a) {
boolean returnValue =
((ComboBoxUI) (uis.elementAt(0))).isFocusTraversable(a);
for (int i = 1; i < uis.size(); i++) {
@@ -87,7 +87,7 @@
/**
* Invokes the <code>setPopupVisible</code> method on each UI handled by this object.
*/
- public void setPopupVisible(JComboBox a, boolean b) {
+ public void setPopupVisible(JComboBox<?> a, boolean b) {
for (int i = 0; i < uis.size(); i++) {
((ComboBoxUI) (uis.elementAt(i))).setPopupVisible(a,b);
}
@@ -99,7 +99,7 @@
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
- public boolean isPopupVisible(JComboBox a) {
+ public boolean isPopupVisible(JComboBox<?> a) {
boolean returnValue =
((ComboBoxUI) (uis.elementAt(0))).isPopupVisible(a);
for (int i = 1; i < uis.size(); i++) {
@@ -120,9 +120,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -132,7 +132,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -145,10 +145,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiComboBoxUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiComboBoxUI) mui).uis,
- a);
+ MultiComboBoxUI mui = new MultiComboBoxUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -156,7 +154,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -165,7 +163,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -174,7 +172,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -186,9 +184,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -201,9 +199,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -216,9 +214,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -231,9 +229,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -246,9 +244,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopIconUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopIconUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiDesktopIconUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiDesktopIconUI) mui).uis,
- a);
+ MultiDesktopIconUI mui = new MultiDesktopIconUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiDesktopPaneUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiDesktopPaneUI) mui).uis,
- a);
+ MultiDesktopPaneUI mui = new MultiDesktopPaneUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiFileChooserUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiFileChooserUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -52,7 +52,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -163,9 +163,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -175,7 +175,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -188,10 +188,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiFileChooserUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiFileChooserUI) mui).uis,
- a);
+ MultiFileChooserUI mui = new MultiFileChooserUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -199,7 +197,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -208,7 +206,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -217,7 +215,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -229,9 +227,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -244,9 +242,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -259,9 +257,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -274,9 +272,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -289,9 +287,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiInternalFrameUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiInternalFrameUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiInternalFrameUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiInternalFrameUI) mui).uis,
- a);
+ MultiInternalFrameUI mui = new MultiInternalFrameUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiLabelUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiLabelUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiLabelUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiLabelUI) mui).uis,
- a);
+ MultiLabelUI mui = new MultiLabelUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiListUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiListUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -50,7 +50,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -77,7 +77,7 @@
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
- public int locationToIndex(JList a, Point b) {
+ public int locationToIndex(JList<?> a, Point b) {
int returnValue =
((ListUI) (uis.elementAt(0))).locationToIndex(a,b);
for (int i = 1; i < uis.size(); i++) {
@@ -92,7 +92,7 @@
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
- public Point indexToLocation(JList a, int b) {
+ public Point indexToLocation(JList<?> a, int b) {
Point returnValue =
((ListUI) (uis.elementAt(0))).indexToLocation(a,b);
for (int i = 1; i < uis.size(); i++) {
@@ -107,7 +107,7 @@
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
- public Rectangle getCellBounds(JList a, int b, int c) {
+ public Rectangle getCellBounds(JList<?> a, int b, int c) {
Rectangle returnValue =
((ListUI) (uis.elementAt(0))).getCellBounds(a,b,c);
for (int i = 1; i < uis.size(); i++) {
@@ -128,9 +128,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -140,7 +140,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -153,10 +153,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiListUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiListUI) mui).uis,
- a);
+ MultiListUI mui = new MultiListUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -164,7 +162,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -173,7 +171,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -182,7 +180,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -194,9 +192,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -209,9 +207,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -224,9 +222,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -239,9 +237,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -254,9 +252,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiLookAndFeel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiLookAndFeel.java Wed Jul 05 19:50:57 2017 +0200
@@ -221,7 +221,7 @@
* @see MultiButtonUI#createUI
*/
public static ComponentUI createUIs(ComponentUI mui,
- Vector uis,
+ Vector<ComponentUI> uis,
JComponent target) {
ComponentUI ui;
@@ -248,7 +248,7 @@
// get a UI from just the default look and feel.
//
if (uis.size() == 1) {
- return (ComponentUI) uis.elementAt(0);
+ return uis.elementAt(0);
} else {
return mui;
}
@@ -269,7 +269,7 @@
* @return an array equivalent to the passed-in vector
*
*/
- protected static ComponentUI[] uisToArray(Vector uis) {
+ protected static ComponentUI[] uisToArray(Vector<? extends ComponentUI> uis) {
if (uis == null) {
return new ComponentUI[0];
} else {
@@ -277,7 +277,7 @@
if (count > 0) {
ComponentUI[] u = new ComponentUI[count];
for (int i = 0; i < count; i++) {
- u[i] = (ComponentUI)uis.elementAt(i);
+ u[i] = uis.elementAt(i);
}
return u;
} else {
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiMenuBarUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiMenuBarUI) mui).uis,
- a);
+ MultiMenuBarUI mui = new MultiMenuBarUI();
+ return MultiLookAndFeel.createUIs(mui,mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuItemUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuItemUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -85,9 +85,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -97,7 +97,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -110,10 +110,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiMenuItemUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiMenuItemUI) mui).uis,
- a);
+ MultiMenuItemUI mui = new MultiMenuItemUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -121,7 +119,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -130,7 +128,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -139,7 +137,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -151,9 +149,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -166,9 +164,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -181,9 +179,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -196,9 +194,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -211,9 +209,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiOptionPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiOptionPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -105,9 +105,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -117,7 +117,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -130,10 +130,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiOptionPaneUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiOptionPaneUI) mui).uis,
- a);
+ MultiOptionPaneUI mui = new MultiOptionPaneUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -141,7 +139,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -150,7 +148,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -159,7 +157,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -171,9 +169,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -186,9 +184,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -201,9 +199,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -216,9 +214,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -231,9 +229,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiPanelUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiPanelUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiPanelUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiPanelUI) mui).uis,
- a);
+ MultiPanelUI mui = new MultiPanelUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiPopupMenuUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiPopupMenuUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -50,7 +50,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -115,9 +115,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -127,7 +127,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -140,10 +140,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiPopupMenuUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiPopupMenuUI) mui).uis,
- a);
+ MultiPopupMenuUI mui = new MultiPopupMenuUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -151,7 +149,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -160,7 +158,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -169,7 +167,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -181,9 +179,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -196,9 +194,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -211,9 +209,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -226,9 +224,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -241,9 +239,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiProgressBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiProgressBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiProgressBarUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiProgressBarUI) mui).uis,
- a);
+ MultiProgressBarUI mui = new MultiProgressBarUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -81,9 +81,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -93,7 +93,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -106,10 +106,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiRootPaneUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiRootPaneUI) mui).uis,
- a);
+ MultiRootPaneUI mui = new MultiRootPaneUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -117,7 +115,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -126,7 +124,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -135,7 +133,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -147,9 +145,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -162,9 +160,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -177,9 +175,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -192,9 +190,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -207,9 +205,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiScrollBarUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiScrollBarUI) mui).uis,
- a);
+ MultiScrollBarUI mui = new MultiScrollBarUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiScrollPaneUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiScrollPaneUI) mui).uis,
- a);
+ MultiScrollPaneUI mui = new MultiScrollPaneUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSeparatorUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSeparatorUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiSeparatorUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiSeparatorUI) mui).uis,
- a);
+ MultiSeparatorUI mui = new MultiSeparatorUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSliderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSliderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiSliderUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiSliderUI) mui).uis,
- a);
+ MultiSliderUI mui = new MultiSliderUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -81,9 +81,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -93,7 +93,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -106,10 +106,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiSpinnerUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiSpinnerUI) mui).uis,
- a);
+ MultiSpinnerUI mui = new MultiSpinnerUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -117,7 +115,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -126,7 +124,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -135,7 +133,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -147,9 +145,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -162,9 +160,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -177,9 +175,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -192,9 +190,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -207,9 +205,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSplitPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSplitPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -153,9 +153,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -165,7 +165,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -178,10 +178,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiSplitPaneUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiSplitPaneUI) mui).uis,
- a);
+ MultiSplitPaneUI mui = new MultiSplitPaneUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -189,7 +187,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -198,7 +196,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -207,7 +205,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -219,9 +217,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -234,9 +232,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -249,9 +247,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -264,9 +262,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -279,9 +277,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTabbedPaneUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTabbedPaneUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,7 +49,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -127,9 +127,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -139,7 +139,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -152,10 +152,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiTabbedPaneUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiTabbedPaneUI) mui).uis,
- a);
+ MultiTabbedPaneUI mui = new MultiTabbedPaneUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -163,7 +161,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -172,7 +170,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -181,7 +179,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -193,9 +191,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -208,9 +206,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -223,9 +221,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -238,9 +236,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -253,9 +251,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableHeaderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableHeaderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiTableHeaderUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiTableHeaderUI) mui).uis,
- a);
+ MultiTableHeaderUI mui = new MultiTableHeaderUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiTableUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiTableUI) mui).uis,
- a);
+ MultiTableUI mui = new MultiTableUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTextUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTextUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -55,7 +55,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -230,9 +230,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -242,7 +242,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -255,10 +255,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiTextUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiTextUI) mui).uis,
- a);
+ MultiTextUI mui = new MultiTextUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -266,7 +264,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -275,7 +273,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -284,7 +282,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -296,9 +294,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -311,9 +309,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -326,9 +324,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -341,9 +339,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -356,9 +354,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolBarUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolBarUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiToolBarUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiToolBarUI) mui).uis,
- a);
+ MultiToolBarUI mui = new MultiToolBarUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolTipUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolTipUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiToolTipUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiToolTipUI) mui).uis,
- a);
+ MultiToolTipUI mui = new MultiToolTipUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTreeUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTreeUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -50,7 +50,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -221,9 +221,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -233,7 +233,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -246,10 +246,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiTreeUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiTreeUI) mui).uis,
- a);
+ MultiTreeUI mui = new MultiTreeUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -257,7 +255,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -266,7 +264,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -275,7 +273,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -287,9 +285,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -302,9 +300,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -317,9 +315,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -332,9 +330,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -347,9 +345,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiViewportUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiViewportUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -47,7 +47,7 @@
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
- protected Vector uis = new Vector();
+ protected Vector<ComponentUI> uis = new Vector<>();
////////////////////
// Common UI methods
@@ -80,9 +80,9 @@
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
- ((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
+ uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
+ uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
@@ -92,7 +92,7 @@
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).update(a,b);
+ uis.elementAt(i).update(a,b);
}
}
@@ -105,10 +105,8 @@
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
- ComponentUI mui = new MultiViewportUI();
- return MultiLookAndFeel.createUIs(mui,
- ((MultiViewportUI) mui).uis,
- a);
+ MultiViewportUI mui = new MultiViewportUI();
+ return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
@@ -116,7 +114,7 @@
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).installUI(a);
+ uis.elementAt(i).installUI(a);
}
}
@@ -125,7 +123,7 @@
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
+ uis.elementAt(i).uninstallUI(a);
}
}
@@ -134,7 +132,7 @@
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).paint(a,b);
+ uis.elementAt(i).paint(a,b);
}
}
@@ -146,9 +144,9 @@
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
+ uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
+ uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
@@ -161,9 +159,9 @@
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
+ uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
+ uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
@@ -176,9 +174,9 @@
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
- ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
+ uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
+ uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
@@ -191,9 +189,9 @@
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
+ uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
+ uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
@@ -206,9 +204,9 @@
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
- ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
+ uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
- ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
+ uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -50,15 +50,20 @@
this.key = key;
}
+ @SuppressWarnings("unchecked")
+ private static Painter<JComponent> paintFilter(@SuppressWarnings("rawtypes") Painter painter) {
+ return (Painter<JComponent>) painter;
+ }
+
@Override
public void paintIcon(SynthContext context, Graphics g, int x, int y,
int w, int h) {
- Painter painter = null;
+ Painter<JComponent> painter = null;
if (context != null) {
- painter = (Painter)context.getStyle().get(context, key);
+ painter = paintFilter((Painter)context.getStyle().get(context, key));
}
if (painter == null){
- painter = (Painter) UIManager.get(prefix + "[Enabled]." + key);
+ painter = paintFilter((Painter)UIManager.get(prefix + "[Enabled]." + key));
}
if (painter != null && context != null) {
@@ -140,7 +145,8 @@
*/
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
- Painter painter = (Painter)UIManager.get(prefix + "[Enabled]." + key);
+ Painter<JComponent> painter =
+ paintFilter((Painter)UIManager.get(prefix + "[Enabled]." + key));
if (painter != null){
JComponent jc = (c instanceof JComponent) ? (JComponent)c : null;
Graphics2D gfx = (Graphics2D)g;
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -283,12 +283,12 @@
//list may contain only "standard" states (those defined by Synth),
//or it may contain custom states, or it may contain only "standard"
//states but list them in a non-standard order.
- List<State> states = new ArrayList<State>();
+ List<State<?>> states = new ArrayList<>();
//a map of state name to code
- Map<String,Integer> stateCodes = new HashMap<String,Integer>();
+ Map<String,Integer> stateCodes = new HashMap<>();
//This is a list of runtime "state" context objects. These contain
//the values associated with each state.
- List<RuntimeState> runtimeStates = new ArrayList<RuntimeState>();
+ List<RuntimeState> runtimeStates = new ArrayList<>();
//determine whether there are any custom states, or custom state
//order. If so, then read all those custom states and define the
@@ -304,7 +304,7 @@
//this is a non-standard state name, so look for the
//custom state associated with it
String stateName = prefix + "." + s[i];
- State customState = (State)defaults.get(stateName);
+ State<?> customState = (State)defaults.get(stateName);
if (customState != null) {
states.add(customState);
}
@@ -317,12 +317,12 @@
//to be non-null. Otherwise, leave it null (meaning, use the
//standard synth states).
if (states.size() > 0) {
- values.stateTypes = states.toArray(new State[states.size()]);
+ values.stateTypes = states.toArray(new State<?>[states.size()]);
}
//assign codes for each of the state types
int code = 1;
- for (State state : states) {
+ for (State<?> state : states) {
stateCodes.put(state.getName(), code);
code <<= 1;
}
@@ -463,12 +463,14 @@
values.states = runtimeStates.toArray(new RuntimeState[runtimeStates.size()]);
}
- private Painter getPainter(Map<String, Object> defaults, String key) {
+ private Painter<Object> getPainter(Map<String, Object> defaults, String key) {
Object p = defaults.get(key);
if (p instanceof UIDefaults.LazyValue) {
p = ((UIDefaults.LazyValue)p).createValue(UIManager.getDefaults());
}
- return (p instanceof Painter ? (Painter)p : null);
+ @SuppressWarnings("unchecked")
+ Painter<Object> tmp = (p instanceof Painter ? (Painter)p : null);
+ return tmp;
}
/**
@@ -689,6 +691,12 @@
return obj == NULL ? null : obj;
}
+ @SuppressWarnings("unchecked")
+ private static Painter<Object> paintFilter(@SuppressWarnings("rawtypes") Painter painter) {
+ return (Painter<Object>) painter;
+ }
+
+
/**
* Gets the appropriate background Painter, if there is one, for the state
* specified in the given SynthContext. This method does appropriate
@@ -698,14 +706,14 @@
* @return The background painter associated for the given state, or null if
* none could be found.
*/
- public Painter getBackgroundPainter(SynthContext ctx) {
+ public Painter<Object> getBackgroundPainter(SynthContext ctx) {
Values v = getValues(ctx);
int xstate = getExtendedState(ctx, v);
- Painter p = null;
+ Painter<Object> p = null;
// check the cache
tmpKey.init("backgroundPainter$$instance", xstate);
- p = (Painter)v.cache.get(tmpKey);
+ p = paintFilter((Painter)v.cache.get(tmpKey));
if (p != null) return p;
// not in cache, so lookup and store in cache
@@ -713,11 +721,11 @@
int[] lastIndex = new int[] {-1};
while ((s = getNextState(v.states, lastIndex, xstate)) != null) {
if (s.backgroundPainter != null) {
- p = s.backgroundPainter;
+ p = paintFilter(s.backgroundPainter);
break;
}
}
- if (p == null) p = (Painter)get(ctx, "backgroundPainter");
+ if (p == null) p = paintFilter((Painter)get(ctx, "backgroundPainter"));
if (p != null) {
v.cache.put(new CacheKey("backgroundPainter$$instance", xstate), p);
}
@@ -733,14 +741,14 @@
* @return The foreground painter associated for the given state, or null if
* none could be found.
*/
- public Painter getForegroundPainter(SynthContext ctx) {
+ public Painter<Object> getForegroundPainter(SynthContext ctx) {
Values v = getValues(ctx);
int xstate = getExtendedState(ctx, v);
- Painter p = null;
+ Painter<Object> p = null;
// check the cache
tmpKey.init("foregroundPainter$$instance", xstate);
- p = (Painter)v.cache.get(tmpKey);
+ p = paintFilter((Painter)v.cache.get(tmpKey));
if (p != null) return p;
// not in cache, so lookup and store in cache
@@ -748,11 +756,11 @@
int[] lastIndex = new int[] {-1};
while ((s = getNextState(v.states, lastIndex, xstate)) != null) {
if (s.foregroundPainter != null) {
- p = s.foregroundPainter;
+ p = paintFilter(s.foregroundPainter);
break;
}
}
- if (p == null) p = (Painter)get(ctx, "foregroundPainter");
+ if (p == null) p = paintFilter((Painter)get(ctx, "foregroundPainter"));
if (p != null) {
v.cache.put(new CacheKey("foregroundPainter$$instance", xstate), p);
}
@@ -768,14 +776,14 @@
* @return The border painter associated for the given state, or null if
* none could be found.
*/
- public Painter getBorderPainter(SynthContext ctx) {
+ public Painter<Object> getBorderPainter(SynthContext ctx) {
Values v = getValues(ctx);
int xstate = getExtendedState(ctx, v);
- Painter p = null;
+ Painter<Object> p = null;
// check the cache
tmpKey.init("borderPainter$$instance", xstate);
- p = (Painter)v.cache.get(tmpKey);
+ p = paintFilter((Painter)v.cache.get(tmpKey));
if (p != null) return p;
// not in cache, so lookup and store in cache
@@ -783,11 +791,11 @@
int[] lastIndex = new int[] {-1};
while ((s = getNextState(v.states, lastIndex, xstate)) != null) {
if (s.borderPainter != null) {
- p = s.borderPainter;
+ p = paintFilter(s.borderPainter);
break;
}
}
- if (p == null) p = (Painter)get(ctx, "borderPainter");
+ if (p == null) p = paintFilter((Painter)get(ctx, "borderPainter"));
if (p != null) {
v.cache.put(new CacheKey("borderPainter$$instance", xstate), p);
}
@@ -851,6 +859,7 @@
* @param v
* @return
*/
+ @SuppressWarnings({"unchecked", "rawtypes"})
private int getExtendedState(SynthContext ctx, Values v) {
JComponent c = ctx.getComponent();
int xstate = 0;
@@ -871,7 +880,7 @@
}
} else {
// custom states
- for (State s : v.stateTypes) {
+ for (State<?> s : v.stateTypes) {
if (contains(states, s.getName())) {
xstate |= mask;
}
@@ -1018,9 +1027,9 @@
*/
private final class RuntimeState implements Cloneable {
int state;
- Painter backgroundPainter;
- Painter foregroundPainter;
- Painter borderPainter;
+ Painter<Object> backgroundPainter;
+ Painter<Object> foregroundPainter;
+ Painter<Object> borderPainter;
String stateName;
UIDefaults defaults = new UIDefaults(10, .7f);
@@ -1055,7 +1064,7 @@
* The list of State types. A State represents a type of state, such
* as Enabled, Default, WindowFocused, etc. These can be custom states.
*/
- State[] stateTypes = null;
+ State<?>[] stateTypes = null;
/**
* The list of actual runtime state representations. These can represent things such
* as Enabled + Focused. Thus, they differ from States in that they contain
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/State.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/State.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -72,13 +72,13 @@
*/
public abstract class State<T extends JComponent>{
static final Map<String, StandardState> standardStates = new HashMap<String, StandardState>(7);
- static final State Enabled = new StandardState(SynthConstants.ENABLED);
- static final State MouseOver = new StandardState(SynthConstants.MOUSE_OVER);
- static final State Pressed = new StandardState(SynthConstants.PRESSED);
- static final State Disabled = new StandardState(SynthConstants.DISABLED);
- static final State Focused = new StandardState(SynthConstants.FOCUSED);
- static final State Selected = new StandardState(SynthConstants.SELECTED);
- static final State Default = new StandardState(SynthConstants.DEFAULT);
+ static final State<JComponent> Enabled = new StandardState(SynthConstants.ENABLED);
+ static final State<JComponent> MouseOver = new StandardState(SynthConstants.MOUSE_OVER);
+ static final State<JComponent> Pressed = new StandardState(SynthConstants.PRESSED);
+ static final State<JComponent> Disabled = new StandardState(SynthConstants.DISABLED);
+ static final State<JComponent> Focused = new StandardState(SynthConstants.FOCUSED);
+ static final State<JComponent> Selected = new StandardState(SynthConstants.SELECTED);
+ static final State<JComponent> Default = new StandardState(SynthConstants.DEFAULT);
private String name;
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/SynthPainterImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/SynthPainterImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -49,7 +49,7 @@
* position and size. Handles if g is a non 2D Graphics by painting via a
* BufferedImage.
*/
- private void paint(Painter p, SynthContext ctx, Graphics g, int x, int y,
+ private void paint(Painter<Object> p, SynthContext ctx, Graphics g, int x, int y,
int w, int h, AffineTransform transform) {
if (p != null) {
if (g instanceof Graphics2D){
@@ -96,7 +96,8 @@
Component c = ctx.getComponent();
Color bg = (c != null) ? c.getBackground() : null;
if (bg == null || bg.getAlpha() > 0){
- Painter backgroundPainter = style.getBackgroundPainter(ctx);
+
+ Painter<Object> backgroundPainter = style.getBackgroundPainter(ctx);
if (backgroundPainter != null) {
paint(backgroundPainter, ctx, g, x, y, w, h,transform);
}
@@ -105,7 +106,7 @@
private void paintForeground(SynthContext ctx, Graphics g, int x, int y,
int w, int h, AffineTransform transform) {
- Painter foregroundPainter = style.getForegroundPainter(ctx);
+ Painter<Object> foregroundPainter = style.getForegroundPainter(ctx);
if (foregroundPainter != null) {
paint(foregroundPainter, ctx, g, x, y, w, h,transform);
}
@@ -113,7 +114,7 @@
private void paintBorder(SynthContext ctx, Graphics g, int x, int y, int w,
int h, AffineTransform transform) {
- Painter borderPainter = style.getBorderPainter(ctx);
+ Painter<Object> borderPainter = style.getBorderPainter(ctx);
if (borderPainter != null) {
paint(borderPainter, ctx, g, x, y, w, h,transform);
}
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/TableScrollPaneCorner.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/TableScrollPaneCorner.java Wed Jul 05 19:50:57 2017 +0200
@@ -48,7 +48,8 @@
* Paint the component using the Nimbus Table Header Background Painter
*/
@Override protected void paintComponent(Graphics g) {
- Painter painter = (Painter) UIManager.get(
+ @SuppressWarnings("unchecked")
+ Painter<JComponent> painter = (Painter) UIManager.get(
"TableHeader:\"TableHeader.renderer\"[Enabled].backgroundPainter");
if (painter != null){
if (g instanceof Graphics2D){
--- a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -58,12 +58,12 @@
/**
* Used during lookup.
*/
- private BakedArrayList _tmpList;
+ private BakedArrayList<SynthStyle> _tmpList;
/**
* Maps from a List (BakedArrayList to be precise) to the merged style.
*/
- private Map<BakedArrayList, SynthStyle> _resolvedStyles;
+ private Map<BakedArrayList<SynthStyle>, SynthStyle> _resolvedStyles;
/**
* Used if there are no styles matching a widget.
@@ -72,9 +72,9 @@
DefaultSynthStyleFactory() {
- _tmpList = new BakedArrayList(5);
- _styles = new ArrayList<StyleAssociation>();
- _resolvedStyles = new HashMap<BakedArrayList, SynthStyle>();
+ _tmpList = new BakedArrayList<SynthStyle>(5);
+ _styles = new ArrayList<>();
+ _resolvedStyles = new HashMap<>();
}
public synchronized void addStyle(DefaultSynthStyle style,
@@ -100,7 +100,7 @@
* @param id ID of the Component
*/
public synchronized SynthStyle getStyle(JComponent c, Region id) {
- BakedArrayList matches = _tmpList;
+ BakedArrayList<SynthStyle> matches = _tmpList;
matches.clear();
getMatchingStyles(matches, c, id);
@@ -138,7 +138,7 @@
* Fetches any styles that match the passed into arguments into
* <code>matches</code>.
*/
- private void getMatchingStyles(List matches, JComponent c,
+ private void getMatchingStyles(List<SynthStyle> matches, JComponent c,
Region id) {
String idName = id.getLowerCaseName();
String cName = c.getName();
@@ -166,8 +166,8 @@
/**
* Caches the specified style.
*/
- private void cacheStyle(List styles, SynthStyle style) {
- BakedArrayList cachedStyles = new BakedArrayList(styles);
+ private void cacheStyle(List<SynthStyle> styles, SynthStyle style) {
+ BakedArrayList<SynthStyle> cachedStyles = new BakedArrayList<>(styles);
_resolvedStyles.put(cachedStyles, style);
}
@@ -175,7 +175,7 @@
/**
* Returns the cached style from the passed in arguments.
*/
- private SynthStyle getCachedStyle(List styles) {
+ private SynthStyle getCachedStyle(List<SynthStyle> styles) { // ??
if (styles.size() == 0) {
return null;
}
@@ -187,7 +187,7 @@
* is reverse sorted, that is the most recently added style found to
* match will be first.
*/
- private SynthStyle mergeStyles(List styles) {
+ private SynthStyle mergeStyles(List<SynthStyle> styles) {
int size = styles.size();
if (size == 0) {
--- a/jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -60,6 +60,7 @@
// we use a AppContext specific Paint9Painter. It's backed via
// a WeakRef so that it can go away if the look and feel changes.
synchronized(CACHE_KEY) {
+ @SuppressWarnings("unchecked")
WeakReference<Paint9Painter> cacheRef =
(WeakReference<Paint9Painter>)AppContext.getAppContext().
get(CACHE_KEY);
--- a/jdk/src/share/classes/javax/swing/plaf/synth/Region.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/Region.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -427,6 +427,7 @@
private static Map<String, Region> getUItoRegionMap() {
AppContext context = AppContext.getAppContext();
+ @SuppressWarnings("unchecked")
Map<String, Region> map = (Map<String, Region>) context.get(UI_TO_REGION_MAP_KEY);
if (map == null) {
map = new HashMap<String, Region>();
@@ -482,6 +483,7 @@
private static Map<Region, String> getLowerCaseNameMap() {
AppContext context = AppContext.getAppContext();
+ @SuppressWarnings("unchecked")
Map<Region, String> map = (Map<Region, String>) context.get(LOWER_CASE_NAME_MAP_KEY);
if (map == null) {
map = new HashMap<Region, String>();
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -120,7 +120,7 @@
updateStyle(comboBox);
}
- private void updateStyle(JComboBox comboBox) {
+ private void updateStyle(JComboBox<?> comboBox) {
SynthStyle oldStyle = style;
SynthContext context = getContext(comboBox, ENABLED);
@@ -220,7 +220,7 @@
// instead of doing anything special
if (!(c instanceof JComboBox)) return SynthLookAndFeel.getComponentState(c);
- JComboBox box = (JComboBox)c;
+ JComboBox<?> box = (JComboBox)c;
if (shouldActLikeButton()) {
int state = ENABLED;
if ((!c.isEnabled())) {
@@ -263,7 +263,7 @@
* {@inheritDoc}
*/
@Override
- protected ListCellRenderer createRenderer() {
+ protected ListCellRenderer<Object> createRenderer() {
return new SynthComboBoxRenderer();
}
@@ -372,7 +372,7 @@
*/
@Override
public void paintCurrentValue(Graphics g,Rectangle bounds,boolean hasFocus) {
- ListCellRenderer renderer = comboBox.getRenderer();
+ ListCellRenderer<Object> renderer = comboBox.getRenderer();
Component c;
c = renderer.getListCellRendererComponent(
@@ -710,11 +710,11 @@
*/
private static class EditorFocusHandler implements FocusListener,
PropertyChangeListener {
- private JComboBox comboBox;
+ private JComboBox<?> comboBox;
private ComboBoxEditor editor = null;
private Component editorComponent = null;
- private EditorFocusHandler(JComboBox comboBox) {
+ private EditorFocusHandler(JComboBox<?> comboBox) {
this.comboBox = comboBox;
editor = comboBox.getEditor();
if (editor != null){
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboPopup.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboPopup.java Wed Jul 05 19:50:57 2017 +0200
@@ -38,7 +38,7 @@
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
class SynthComboPopup extends BasicComboPopup {
- public SynthComboPopup( JComboBox combo ) {
+ public SynthComboPopup( JComboBox<Object> combo ) {
super(combo);
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -207,7 +207,7 @@
}
}
- @Override public Component getListCellRendererComponent(JList list, Object value,
+ @Override public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (!useListColors && (isSelected || cellHasFocus)) {
SynthLookAndFeel.setSelectedUI((SynthLabelUI)SynthLookAndFeel.
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java Wed Jul 05 19:50:57 2017 +0200
@@ -382,7 +382,7 @@
* Returns the ui that is of type <code>klass</code>, or null if
* one can not be found.
*/
- static Object getUIOfType(ComponentUI ui, Class klass) {
+ static Object getUIOfType(ComponentUI ui, Class<?> klass) {
if (klass.isInstance(ui)) {
return ui;
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java Wed Jul 05 19:50:57 2017 +0200
@@ -322,7 +322,7 @@
* If <code>value</code> is an instance of <code>type</code> it is
* returned, otherwise a SAXException is thrown.
*/
- private Object checkCast(Object value, Class type) throws SAXException {
+ private Object checkCast(Object value, Class<?> type) throws SAXException {
if (!type.isInstance(value)) {
throw new SAXException("Expected type " + type + " got " +
value.getClass());
@@ -334,7 +334,7 @@
* Returns an object created with id=key. If the object is not of
* type type, this will throw an exception.
*/
- private Object lookup(String key, Class type) throws SAXException {
+ private Object lookup(String key, Class<?> type) throws SAXException {
Object value;
if (_handler != null) {
if (_handler.hasVariable(key)) {
@@ -641,7 +641,7 @@
while (tokenizer.hasMoreTokens()) {
String typeName = tokenizer.nextToken();
int classIndex = typeName.lastIndexOf('.');
- Class typeClass;
+ Class<?> typeClass;
if (classIndex == -1) {
typeClass = ColorType.class;
@@ -783,13 +783,13 @@
}
else if (_stateInfo != null) {
if (_stateInfo.getData() == null) {
- _stateInfo.setData(new HashMap());
+ _stateInfo.setData(new HashMap<>());
}
_stateInfo.getData().put(key, value);
}
else if (_style != null) {
if (_style.getData() == null) {
- _style.setData(new HashMap());
+ _style.setData(new HashMap<>());
}
_style.getData().put(key, value);
}
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -269,7 +269,7 @@
centerY += valueHeight + 2;
centerY += trackHeight + trackInsets.top + trackInsets.bottom;
centerY += tickHeight + 2;
- JComponent label = (JComponent) slider.getLabelTable().elements().nextElement();
+ JComponent label = slider.getLabelTable().elements().nextElement();
Dimension pref = label.getPreferredSize();
return centerY + label.getBaseline(pref.width, pref.height);
}
@@ -291,7 +291,7 @@
int trackHeight = contentHeight - valueHeight;
int yPosition = yPositionForValue(value.intValue(), trackY,
trackHeight);
- JComponent label = (JComponent) slider.getLabelTable().get(value);
+ JComponent label = slider.getLabelTable().get(value);
Dimension pref = label.getPreferredSize();
return yPosition - pref.height / 2 +
label.getBaseline(pref.width, pref.height);
@@ -392,7 +392,7 @@
trackRect.x = insetCache.left;
trackRect.width = contentRect.width;
- Dictionary dictionary = slider.getLabelTable();
+ Dictionary<Integer, JComponent> dictionary = slider.getLabelTable();
if (dictionary != null) {
int minValue = slider.getMinimum();
int maxValue = slider.getMaximum();
@@ -402,9 +402,9 @@
// slider range.
int firstLblIdx = Integer.MAX_VALUE;
int lastLblIdx = Integer.MIN_VALUE;
- for (Enumeration keys = dictionary.keys();
+ for (Enumeration<Integer> keys = dictionary.keys();
keys.hasMoreElements(); ) {
- int keyInt = ((Integer)keys.nextElement()).intValue();
+ int keyInt = keys.nextElement().intValue();
if (keyInt >= minValue && keyInt < firstLblIdx) {
firstLblIdx = keyInt;
}
@@ -517,7 +517,7 @@
private int getPadForLabel(int i) {
int pad = 0;
- JComponent c = (JComponent) slider.getLabelTable().get(i);
+ JComponent c = slider.getLabelTable().get(i);
if (c != null) {
int centerX = xPositionForValue(i);
int cHalfWidth = c.getPreferredSize().width / 2;
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -240,7 +240,7 @@
//stuff a variable into the client property of this renderer indicating the sort order,
//so that different rendering can be done for the header based on sorted state.
- RowSorter rs = table == null ? null : table.getRowSorter();
+ RowSorter<?> rs = table == null ? null : table.getRowSorter();
java.util.List<? extends RowSorter.SortKey> sortKeys = rs == null ? null : rs.getSortKeys();
if (sortKeys != null && sortKeys.size() > 0 && sortKeys.get(0).getColumn() ==
table.convertColumnIndexToModel(column)) {
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -120,7 +120,7 @@
updateStyle(table);
}
- private TableCellRenderer installRendererIfPossible(Class objectClass,
+ private TableCellRenderer installRendererIfPossible(Class<?> objectClass,
TableCellRenderer renderer) {
TableCellRenderer currentRenderer = table.getDefaultRenderer(
objectClass);
@@ -792,7 +792,7 @@
return this;
}
- private void configureValue(Object value, Class columnClass) {
+ private void configureValue(Object value, Class<?> columnClass) {
if (columnClass == Object.class || columnClass == null) {
setHorizontalAlignment(JLabel.LEADING);
} else if (columnClass == Float.class || columnClass == Double.class) {
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java Wed Jul 05 19:50:57 2017 +0200
@@ -312,7 +312,7 @@
Insets insets = tree.getInsets();
TreePath initialPath = getClosestPathForLocation(tree, 0,
paintBounds.y);
- Enumeration paintingEnumerator = treeState.getVisiblePathsFrom
+ Enumeration<?> paintingEnumerator = treeState.getVisiblePathsFrom
(initialPath);
int row = treeState.getRowForPath(initialPath);
int endY = paintBounds.y + paintBounds.height;
--- a/jdk/src/share/classes/javax/swing/table/DefaultTableColumnModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/table/DefaultTableColumnModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -269,12 +269,12 @@
throw new IllegalArgumentException("Identifier is null");
}
- Enumeration enumeration = getColumns();
+ Enumeration<TableColumn> enumeration = getColumns();
TableColumn aColumn;
int index = 0;
while (enumeration.hasMoreElements()) {
- aColumn = (TableColumn)enumeration.nextElement();
+ aColumn = enumeration.nextElement();
// Compare them this way in case the column's identifier is null.
if (identifier.equals(aColumn.getIdentifier()))
return index;
@@ -728,10 +728,10 @@
* <code>totalColumnWidth</code> property.
*/
protected void recalcWidthCache() {
- Enumeration enumeration = getColumns();
+ Enumeration<TableColumn> enumeration = getColumns();
totalColumnWidth = 0;
while (enumeration.hasMoreElements()) {
- totalColumnWidth += ((TableColumn)enumeration.nextElement()).getWidth();
+ totalColumnWidth += enumeration.nextElement().getWidth();
}
}
--- a/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -70,10 +70,10 @@
* The <code>Vector</code> of <code>Vectors</code> of
* <code>Object</code> values.
*/
- protected Vector dataVector;
+ protected Vector<Vector<Object>> dataVector;
/** The <code>Vector</code> of column identifiers. */
- protected Vector columnIdentifiers;
+ protected Vector<Object> columnIdentifiers;
//
// Constructors
@@ -87,8 +87,8 @@
this(0, 0);
}
- private static Vector newVector(int size) {
- Vector v = new Vector(size);
+ private static <E> Vector<E> newVector(int size) {
+ Vector<E> v = new Vector<>(size);
v.setSize(size);
return v;
}
@@ -121,7 +121,7 @@
* @see #setDataVector
* @see #setValueAt
*/
- public DefaultTableModel(Vector columnNames, int rowCount) {
+ public DefaultTableModel(Vector<Object> columnNames, int rowCount) {
setDataVector(newVector(rowCount), columnNames);
}
@@ -156,7 +156,7 @@
* @see #getDataVector
* @see #setDataVector
*/
- public DefaultTableModel(Vector data, Vector columnNames) {
+ public DefaultTableModel(Vector<Vector<Object>> data, Vector<Object> columnNames) {
setDataVector(data, columnNames);
}
@@ -191,12 +191,12 @@
* @see #newRowsAdded
* @see #setDataVector
*/
- public Vector getDataVector() {
+ public Vector<Vector<Object>> getDataVector() {
return dataVector;
}
- private static Vector nonNullVector(Vector v) {
- return (v != null) ? v : new Vector();
+ private static <E> Vector<E> nonNullVector(Vector<E> v) {
+ return (v != null) ? v : new Vector<>();
}
/**
@@ -219,7 +219,8 @@
* @param columnIdentifiers the names of the columns
* @see #getDataVector
*/
- public void setDataVector(Vector dataVector, Vector columnIdentifiers) {
+ public void setDataVector(Vector<Vector<Object>> dataVector,
+ Vector<Object> columnIdentifiers) {
this.dataVector = nonNullVector(dataVector);
this.columnIdentifiers = nonNullVector(columnIdentifiers);
justifyRows(0, getRowCount());
@@ -264,7 +265,7 @@
for (int i = from; i < to; i++) {
if (dataVector.elementAt(i) == null) {
- dataVector.setElementAt(new Vector(), i);
+ dataVector.setElementAt(new Vector<>(), i);
}
((Vector)dataVector.elementAt(i)).setSize(getColumnCount());
}
@@ -349,7 +350,7 @@
*
* @param rowData optional data of the row being added
*/
- public void addRow(Vector rowData) {
+ public void addRow(Vector<Object> rowData) {
insertRow(getRowCount(), rowData);
}
@@ -373,7 +374,7 @@
* @param rowData optional data of the row being added
* @exception ArrayIndexOutOfBoundsException if the row was invalid
*/
- public void insertRow(int row, Vector rowData) {
+ public void insertRow(int row, Vector<Object> rowData) {
dataVector.insertElementAt(rowData, row);
justifyRows(row, row+1);
fireTableRowsInserted(row, row);
@@ -396,13 +397,13 @@
return (j == 0) ? i : gcd(j, i%j);
}
- private static void rotate(Vector v, int a, int b, int shift) {
+ private static <E> void rotate(Vector<E> v, int a, int b, int shift) {
int size = b - a;
int r = size - shift;
int g = gcd(size, r);
for(int i = 0; i < g; i++) {
int to = i;
- Object tmp = v.elementAt(a + to);
+ E tmp = v.elementAt(a + to);
for(int from = (to + r) % size; from != i; from = (to + r) % size) {
v.setElementAt(v.elementAt(a + from), a + to);
to = from;
@@ -483,7 +484,7 @@
* to zero columns
* @see #setNumRows
*/
- public void setColumnIdentifiers(Vector columnIdentifiers) {
+ public void setColumnIdentifiers(Vector<Object> columnIdentifiers) {
setDataVector(dataVector, columnIdentifiers);
}
@@ -533,7 +534,7 @@
* @param columnName the identifier of the column being added
*/
public void addColumn(Object columnName) {
- addColumn(columnName, (Vector)null);
+ addColumn(columnName, (Vector<Object>)null);
}
/**
@@ -549,7 +550,7 @@
* @param columnName the identifier of the column being added
* @param columnData optional data of the column being added
*/
- public void addColumn(Object columnName, Vector columnData) {
+ public void addColumn(Object columnName, Vector<Object> columnData) {
columnIdentifiers.addElement(columnName);
if (columnData != null) {
int columnSize = columnData.size();
@@ -559,7 +560,7 @@
justifyRows(0, getRowCount());
int newColumn = getColumnCount() - 1;
for(int i = 0; i < columnSize; i++) {
- Vector row = (Vector)dataVector.elementAt(i);
+ Vector<Object> row = dataVector.elementAt(i);
row.setElementAt(columnData.elementAt(i), newColumn);
}
}
@@ -651,7 +652,7 @@
* column was given
*/
public Object getValueAt(int row, int column) {
- Vector rowVector = (Vector)dataVector.elementAt(row);
+ Vector<Object> rowVector = dataVector.elementAt(row);
return rowVector.elementAt(column);
}
@@ -667,7 +668,7 @@
* column was given
*/
public void setValueAt(Object aValue, int row, int column) {
- Vector rowVector = (Vector)dataVector.elementAt(row);
+ Vector<Object> rowVector = dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
fireTableCellUpdated(row, column);
}
@@ -682,11 +683,11 @@
* @return the new vector; if <code>anArray</code> is <code>null</code>,
* returns <code>null</code>
*/
- protected static Vector convertToVector(Object[] anArray) {
+ protected static Vector<Object> convertToVector(Object[] anArray) {
if (anArray == null) {
return null;
}
- Vector<Object> v = new Vector<Object>(anArray.length);
+ Vector<Object> v = new Vector<>(anArray.length);
for (Object o : anArray) {
v.addElement(o);
}
@@ -699,11 +700,11 @@
* @return the new vector of vectors; if <code>anArray</code> is
* <code>null</code>, returns <code>null</code>
*/
- protected static Vector convertToVector(Object[][] anArray) {
+ protected static Vector<Vector<Object>> convertToVector(Object[][] anArray) {
if (anArray == null) {
return null;
}
- Vector<Vector> v = new Vector<Vector>(anArray.length);
+ Vector<Vector<Object>> v = new Vector<>(anArray.length);
for (Object[] o : anArray) {
v.addElement(convertToVector(o));
}
--- a/jdk/src/share/classes/javax/swing/table/TableRowSorter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/table/TableRowSorter.java Wed Jul 05 19:50:57 2017 +0200
@@ -131,7 +131,7 @@
/**
* Comparator that uses compareTo on the contents.
*/
- private static final Comparator COMPARABLE_COMPARATOR =
+ private static final Comparator<?> COMPARABLE_COMPARATOR =
new ComparableComparator();
/**
@@ -214,11 +214,11 @@
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public Comparator<?> getComparator(int column) {
- Comparator comparator = super.getComparator(column);
+ Comparator<?> comparator = super.getComparator(column);
if (comparator != null) {
return comparator;
}
- Class columnClass = getModel().getColumnClass(column);
+ Class<?> columnClass = getModel().getColumnClass(column);
if (columnClass == String.class) {
return Collator.getInstance();
}
@@ -234,11 +234,11 @@
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
protected boolean useToString(int column) {
- Comparator comparator = super.getComparator(column);
+ Comparator<?> comparator = super.getComparator(column);
if (comparator != null) {
return false;
}
- Class columnClass = getModel().getColumnClass(column);
+ Class<?> columnClass = getModel().getColumnClass(column);
if (columnClass == String.class) {
return false;
}
@@ -299,7 +299,7 @@
}
- private static class ComparableComparator implements Comparator {
+ private static class ComparableComparator implements Comparator<Object> {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable)o1).compareTo(o2);
--- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java Wed Jul 05 19:50:57 2017 +0200
@@ -2193,7 +2193,7 @@
* <code>Enumeration</code>.
* @return the children of the receiver as an <code>Enumeration</code>
*/
- public abstract Enumeration<?> children();
+ public abstract Enumeration<TreeNode> children();
// --- serialization ---------------------------------------------
@@ -2456,11 +2456,11 @@
* <code>Enumeration</code>.
* @return the children of the receiver
*/
- public Enumeration<AbstractElement> children() {
+ public Enumeration<TreeNode> children() {
if(nchildren == 0)
return null;
- Vector<AbstractElement> tempVector = new Vector<AbstractElement>(nchildren);
+ Vector<TreeNode> tempVector = new Vector<>(nchildren);
for(int counter = 0; counter < nchildren; counter++)
tempVector.addElement(children[counter]);
@@ -2610,7 +2610,8 @@
* <code>Enumeration</code>.
* @return the children of the receiver
*/
- public Enumeration<?> children() {
+ @Override
+ public Enumeration<TreeNode> children() {
return null;
}
--- a/jdk/src/share/classes/javax/swing/tree/AbstractLayoutCache.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/AbstractLayoutCache.java Wed Jul 05 19:50:57 2017 +0200
@@ -228,10 +228,10 @@
endY = bounds.height + bounds.y;
}
- Enumeration paths = getVisiblePathsFrom(firstPath);
+ Enumeration<TreePath> paths = getVisiblePathsFrom(firstPath);
if(paths != null && paths.hasMoreElements()) {
- Rectangle pBounds = getBounds((TreePath)paths.nextElement(),
+ Rectangle pBounds = getBounds(paths.nextElement(),
null);
int width;
@@ -244,7 +244,7 @@
else
width = 0;
while (pBounds != null && paths.hasMoreElements()) {
- pBounds = getBounds((TreePath)paths.nextElement(),
+ pBounds = getBounds(paths.nextElement(),
pBounds);
if (pBounds != null && pBounds.y < endY) {
width = Math.max(width, pBounds.x + pBounds.width);
--- a/jdk/src/share/classes/javax/swing/tree/DefaultMutableTreeNode.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/DefaultMutableTreeNode.java Wed Jul 05 19:50:57 2017 +0200
@@ -102,7 +102,7 @@
protected MutableTreeNode parent;
/** array of children, may be null if this node has no children */
- protected Vector children;
+ protected Vector<TreeNode> children;
/** optional user object */
transient protected Object userObject;
@@ -187,7 +187,7 @@
}
newChild.setParent(this);
if (children == null) {
- children = new Vector();
+ children = new Vector<>();
}
children.insertElementAt(newChild, childIndex);
}
@@ -243,7 +243,7 @@
if (children == null) {
throw new ArrayIndexOutOfBoundsException("node has no children");
}
- return (TreeNode)children.elementAt(index);
+ return children.elementAt(index);
}
/**
@@ -290,7 +290,7 @@
*
* @return an Enumeration of this node's children
*/
- public Enumeration children() {
+ public Enumeration<TreeNode> children() {
if (children == null) {
return EMPTY_ENUMERATION;
} else {
@@ -557,7 +557,7 @@
*/
public int getDepth() {
Object last = null;
- Enumeration enum_ = breadthFirstEnumeration();
+ Enumeration<TreeNode> enum_ = breadthFirstEnumeration();
while (enum_.hasMoreElements()) {
last = enum_.nextElement();
@@ -765,7 +765,7 @@
* @see #postorderEnumeration
* @return an enumeration for traversing the tree in preorder
*/
- public Enumeration preorderEnumeration() {
+ public Enumeration<TreeNode> preorderEnumeration() {
return new PreorderEnumeration(this);
}
@@ -782,7 +782,7 @@
* @see #preorderEnumeration
* @return an enumeration for traversing the tree in postorder
*/
- public Enumeration postorderEnumeration() {
+ public Enumeration<TreeNode> postorderEnumeration() {
return new PostorderEnumeration(this);
}
@@ -797,7 +797,7 @@
* @see #depthFirstEnumeration
* @return an enumeration for traversing the tree in breadth-first order
*/
- public Enumeration breadthFirstEnumeration() {
+ public Enumeration<TreeNode> breadthFirstEnumeration() {
return new BreadthFirstEnumeration(this);
}
@@ -814,7 +814,7 @@
* @see #postorderEnumeration
* @return an enumeration for traversing the tree in depth-first order
*/
- public Enumeration depthFirstEnumeration() {
+ public Enumeration<TreeNode> depthFirstEnumeration() {
return postorderEnumeration();
}
@@ -839,7 +839,7 @@
* @return an enumeration for following the path from an ancestor of
* this node to this one
*/
- public Enumeration pathFromAncestorEnumeration(TreeNode ancestor) {
+ public Enumeration<TreeNode> pathFromAncestorEnumeration(TreeNode ancestor) {
return new PathBetweenNodesEnumeration(ancestor, this);
}
@@ -1218,10 +1218,10 @@
int count = 0;
TreeNode node;
- Enumeration enum_ = breadthFirstEnumeration(); // order matters not
+ Enumeration<TreeNode> enum_ = breadthFirstEnumeration(); // order matters not
while (enum_.hasMoreElements()) {
- node = (TreeNode)enum_.nextElement();
+ node = enum_.nextElement();
if (node.isLeaf()) {
count++;
}
@@ -1308,7 +1308,7 @@
}
private final class PreorderEnumeration implements Enumeration<TreeNode> {
- private final Stack<Enumeration> stack = new Stack<Enumeration>();
+ private final Stack<Enumeration<TreeNode>> stack = new Stack<>();
public PreorderEnumeration(TreeNode rootNode) {
super();
@@ -1322,9 +1322,10 @@
}
public TreeNode nextElement() {
- Enumeration enumer = stack.peek();
- TreeNode node = (TreeNode)enumer.nextElement();
- Enumeration children = node.children();
+ Enumeration<TreeNode> enumer = stack.peek();
+ TreeNode node = enumer.nextElement();
+ @SuppressWarnings("unchecked")
+ Enumeration<TreeNode> children = node.children();
if (!enumer.hasMoreElements()) {
stack.pop();
@@ -1392,9 +1393,9 @@
}
public TreeNode nextElement() {
- Enumeration enumer = (Enumeration)queue.firstObject();
+ Enumeration<?> enumer = (Enumeration)queue.firstObject();
TreeNode node = (TreeNode)enumer.nextElement();
- Enumeration children = node.children();
+ Enumeration<?> children = node.children();
if (!enumer.hasMoreElements()) {
queue.dequeue();
--- a/jdk/src/share/classes/javax/swing/tree/DefaultTreeCellEditor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/DefaultTreeCellEditor.java Wed Jul 05 19:50:57 2017 +0200
@@ -573,7 +573,7 @@
throws IOException, ClassNotFoundException {
s.defaultReadObject();
- Vector values = (Vector)s.readObject();
+ Vector<?> values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
--- a/jdk/src/share/classes/javax/swing/tree/DefaultTreeModel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/DefaultTreeModel.java Wed Jul 05 19:50:57 2017 +0200
@@ -693,7 +693,7 @@
throws IOException, ClassNotFoundException {
s.defaultReadObject();
- Vector values = (Vector)s.readObject();
+ Vector<?> values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
--- a/jdk/src/share/classes/javax/swing/tree/TreeNode.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/TreeNode.java Wed Jul 05 19:50:57 2017 +0200
@@ -99,5 +99,5 @@
*
* @return the children of the receiver as an {@code Enumeration}
*/
- Enumeration children();
+ Enumeration<TreeNode> children();
}
--- a/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java Wed Jul 05 19:50:57 2017 +0200
@@ -742,7 +742,7 @@
if(!root.isExpanded())
root.expand();
else {
- Enumeration cursor = root.children();
+ Enumeration<?> cursor = root.children();
while(cursor.hasMoreElements()) {
visibleNodes.addElement(cursor.nextElement());
}
@@ -1099,7 +1099,8 @@
* If the receiver is not currently expanded, this will return an
* empty enumeration.
*/
- public Enumeration children() {
+ @Override
+ public Enumeration<TreeNode> children() {
if (!this.isExpanded()) {
return DefaultMutableTreeNode.EMPTY_ENUMERATION;
} else {
@@ -1405,7 +1406,7 @@
* <code>createIfNeeded</code> is true, the children are first
* loaded.
*/
- protected Enumeration getLoadedChildren(boolean createIfNeeded) {
+ protected Enumeration<TreeNode> getLoadedChildren(boolean createIfNeeded) {
if(!createIfNeeded || hasBeenExpanded)
return super.children();
@@ -1499,7 +1500,7 @@
}
int i = originalRow;
- Enumeration cursor = preorderEnumeration();
+ Enumeration<TreeNode> cursor = preorderEnumeration();
cursor.nextElement(); // don't add me, I'm already in
int newYOrigin;
@@ -1513,7 +1514,7 @@
TreeStateNode aNode;
if(!isFixed) {
while (cursor.hasMoreElements()) {
- aNode = (TreeStateNode)cursor.nextElement();
+ aNode = (TreeStateNode) cursor.nextElement();
if(!updateNodeSizes && !aNode.hasValidSize())
aNode.updatePreferredSize(i + 1);
aNode.setYOrigin(newYOrigin);
@@ -1523,7 +1524,7 @@
}
else {
while (cursor.hasMoreElements()) {
- aNode = (TreeStateNode)cursor.nextElement();
+ aNode = (TreeStateNode) cursor.nextElement();
visibleNodes.insertElementAt(aNode, ++i);
}
}
@@ -1559,7 +1560,7 @@
*/
protected void collapse(boolean adjustTree) {
if (isExpanded()) {
- Enumeration cursor = preorderEnumeration();
+ Enumeration<TreeNode> cursor = preorderEnumeration();
cursor.nextElement(); // don't remove me, I'm still visible
int rowsDeleted = 0;
boolean isFixed = isFixedRowHeight();
--- a/jdk/src/share/classes/javax/swing/undo/CompoundEdit.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/undo/CompoundEdit.java Wed Jul 05 19:50:57 2017 +0200
@@ -72,9 +72,9 @@
*/
public void redo() throws CannotRedoException {
super.redo();
- Enumeration cursor = edits.elements();
+ Enumeration<UndoableEdit> cursor = edits.elements();
while (cursor.hasMoreElements()) {
- ((UndoableEdit)cursor.nextElement()).redo();
+ cursor.nextElement().redo();
}
}
@@ -198,9 +198,9 @@
* Returns false if they all return false.
*/
public boolean isSignificant() {
- Enumeration cursor = edits.elements();
+ Enumeration<UndoableEdit> cursor = edits.elements();
while (cursor.hasMoreElements()) {
- if (((UndoableEdit)cursor.nextElement()).isSignificant()) {
+ if (cursor.nextElement().isSignificant()) {
return true;
}
}
--- a/jdk/src/share/classes/javax/swing/undo/StateEdit.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/undo/StateEdit.java Wed Jul 05 19:50:57 2017 +0200
@@ -170,8 +170,8 @@
* Remove redundant key/values in state hashtables.
*/
protected void removeRedundantState() {
- Vector<Object> uselessKeys = new Vector<Object>();
- Enumeration myKeys = preState.keys();
+ Vector<Object> uselessKeys = new Vector<>();
+ Enumeration<Object> myKeys = preState.keys();
// Locate redundant state
while (myKeys.hasMoreElements()) {
--- a/jdk/src/share/classes/javax/swing/undo/UndoableEditSupport.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/undo/UndoableEditSupport.java Wed Jul 05 19:50:57 2017 +0200
@@ -101,10 +101,11 @@
*/
protected void _postEdit(UndoableEdit e) {
UndoableEditEvent ev = new UndoableEditEvent(realSource, e);
- Enumeration cursor = ((Vector)listeners.clone()).elements();
+ @SuppressWarnings("unchecked")
+ Enumeration<UndoableEditListener> cursor =
+ ((Vector<UndoableEditListener>)listeners.clone()).elements();
while (cursor.hasMoreElements()) {
- ((UndoableEditListener)cursor.nextElement()).
- undoableEditHappened(ev);
+ cursor.nextElement().undoableEditHappened(ev);
}
}
--- a/jdk/src/share/classes/sun/awt/AppContext.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/AppContext.java Wed Jul 05 19:50:57 2017 +0200
@@ -331,6 +331,20 @@
while (context == null) {
threadGroup = threadGroup.getParent();
if (threadGroup == null) {
+ // We've got up to the root thread group and did not find an AppContext
+ // Try to get it from the security manager
+ SecurityManager securityManager = System.getSecurityManager();
+ if (securityManager != null) {
+ ThreadGroup smThreadGroup = securityManager.getThreadGroup();
+ if (smThreadGroup != null) {
+ /*
+ * If we get this far then it's likely that
+ * the ThreadGroup does not actually belong
+ * to the applet, so do not cache it.
+ */
+ return threadGroup2appContext.get(smThreadGroup);
+ }
+ }
return null;
}
context = threadGroup2appContext.get(threadGroup);
--- a/jdk/src/share/classes/sun/awt/SunToolkit.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/SunToolkit.java Wed Jul 05 19:50:57 2017 +0200
@@ -59,8 +59,7 @@
import java.security.AccessController;
public abstract class SunToolkit extends Toolkit
- implements WindowClosingSupport, WindowClosingListener,
- ComponentFactory, InputMethodSupport, KeyboardFocusManagerPeerProvider {
+ implements ComponentFactory, InputMethodSupport, KeyboardFocusManagerPeerProvider {
// 8014718: logging has been removed from SunToolkit
@@ -1201,42 +1200,6 @@
return getStartupLocale();
}
- // Support for window closing event notifications
- private transient WindowClosingListener windowClosingListener = null;
- /**
- * @see sun.awt.WindowClosingSupport#getWindowClosingListener
- */
- public WindowClosingListener getWindowClosingListener() {
- return windowClosingListener;
- }
- /**
- * @see sun.awt.WindowClosingSupport#setWindowClosingListener
- */
- public void setWindowClosingListener(WindowClosingListener wcl) {
- windowClosingListener = wcl;
- }
-
- /**
- * @see sun.awt.WindowClosingListener#windowClosingNotify
- */
- public RuntimeException windowClosingNotify(WindowEvent event) {
- if (windowClosingListener != null) {
- return windowClosingListener.windowClosingNotify(event);
- } else {
- return null;
- }
- }
- /**
- * @see sun.awt.WindowClosingListener#windowClosingDelivered
- */
- public RuntimeException windowClosingDelivered(WindowEvent event) {
- if (windowClosingListener != null) {
- return windowClosingListener.windowClosingDelivered(event);
- } else {
- return null;
- }
- }
-
private static DefaultMouseInfoPeer mPeer = null;
protected synchronized MouseInfoPeer getMouseInfoPeer() {
--- a/jdk/src/share/classes/sun/awt/WindowClosingListener.java Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.awt;
-
-import java.awt.event.WindowEvent;
-
-/**
- * Interface for listening to WINDOW_CLOSING events before and
- * after they are posted to the queue.
- */
-public interface WindowClosingListener {
- /**
- * Called before a WINDOW_CLOSING event gets posted to the queue.
- * @param event The WINDOW_CLOSING event that will be posted.
- * @return A RuntimeException if the result of this function
- * call needs to interrupt a blocking thread. The exception
- * returned will be thrown from that thread. This function
- * should return null otherwise.
- */
- RuntimeException windowClosingNotify(WindowEvent event);
- /**
- * Called after a WINDOW_CLOSING event gets posted to the queue.
- * @param event The WINDOW_CLOSING event that has been posted.
- * @return A RuntimeException if the result of this function
- * call needs to interrupt a blocking thread. The exception
- * returned will be thrown from that thread. This function
- * should return null otherwise.
- */
- RuntimeException windowClosingDelivered(WindowEvent event);
-}
--- a/jdk/src/share/classes/sun/awt/WindowClosingSupport.java Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.awt;
-
-/**
- * Interface for identifying and casting toolkits that support
- * WindowClosingListeners.
- */
-public interface WindowClosingSupport {
- WindowClosingListener getWindowClosingListener();
- void setWindowClosingListener(WindowClosingListener wcl);
-}
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/AbstractPerfDataBuffer.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/AbstractPerfDataBuffer.java Wed Jul 05 19:50:57 2017 +0200
@@ -175,7 +175,7 @@
});
impl = (PerfDataBufferImpl)cons.newInstance(new Object[] {
- bb, new Integer(lvmid)
+ bb, lvmid
});
} catch (ClassNotFoundException e) {
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/PerfIntegerMonitor.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/PerfIntegerMonitor.java Wed Jul 05 19:50:57 2017 +0200
@@ -67,7 +67,7 @@
* return type is guaranteed to be of type Integer.
*/
public Object getValue() {
- return new Integer(ib.get(0));
+ return ib.get(0);
}
/**
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/LocalVmManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/LocalVmManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -156,8 +156,8 @@
if (files != null) {
for (int j = 0; j < files.length; j++) {
if (files[j].isFile() && files[j].canRead()) {
- jvmSet.add(new Integer(
- PerfDataFile.getLocalVmId(files[j])));
+ jvmSet.add(
+ PerfDataFile.getLocalVmId(files[j]));
}
}
}
@@ -175,8 +175,8 @@
if (files != null) {
for (int j = 0; j < files.length; j++) {
if (files[j].isFile() && files[j].canRead()) {
- jvmSet.add(new Integer(
- PerfDataFile.getLocalVmId(files[j])));
+ jvmSet.add(
+ PerfDataFile.getLocalVmId(files[j]));
}
}
}
@@ -187,8 +187,8 @@
if (files != null) {
for (int j = 0; j < files.length; j++) {
if (files[j].isFile() && files[j].canRead()) {
- jvmSet.add(new Integer(
- PerfDataFile.getLocalVmId(files[j])));
+ jvmSet.add(
+ PerfDataFile.getLocalVmId(files[j]));
}
}
}
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/RemoteVmManager.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/rmi/RemoteVmManager.java Wed Jul 05 19:50:57 2017 +0200
@@ -106,7 +106,7 @@
Set<Integer> activeSet = new HashSet<Integer>(active.length);
for (int i = 0; i < active.length; i++) {
- activeSet.add(new Integer(active[i]));
+ activeSet.add(active[i]);
}
return activeSet;
--- a/jdk/src/share/classes/sun/management/LockInfoCompositeData.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/LockInfoCompositeData.java Wed Jul 05 19:50:57 2017 +0200
@@ -61,7 +61,7 @@
// lockInfoItemNames!
final Object[] lockInfoItemValues = {
new String(lock.getClassName()),
- new Integer(lock.getIdentityHashCode()),
+ lock.getIdentityHashCode(),
};
try {
--- a/jdk/src/share/classes/sun/management/MonitorInfoCompositeData.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/MonitorInfoCompositeData.java Wed Jul 05 19:50:57 2017 +0200
@@ -69,7 +69,7 @@
toCompositeData(ste)
: null);
} else if (item.equals(LOCKED_STACK_DEPTH)) {
- values[i] = new Integer(lock.getLockedStackDepth());
+ values[i] = lock.getLockedStackDepth();
} else {
values[i] = li.get(item);
}
--- a/jdk/src/share/classes/sun/management/StackTraceElementCompositeData.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/StackTraceElementCompositeData.java Wed Jul 05 19:50:57 2017 +0200
@@ -67,7 +67,7 @@
ste.getClassName(),
ste.getMethodName(),
ste.getFileName(),
- new Integer(ste.getLineNumber()),
+ ste.getLineNumber(),
ste.isNativeMethod(),
};
try {
--- a/jdk/src/share/classes/sun/management/jdp/JdpController.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/jdp/JdpController.java Wed Jul 05 19:50:57 2017 +0200
@@ -204,7 +204,7 @@
packet.setRmiHostname(rmiHostname);
// Set broadcast interval
- packet.setBroadcastInterval(new Integer(pause).toString());
+ packet.setBroadcastInterval(Integer.toString(pause));
// Set process id
Integer pid = getProcessId();
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemGCEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemGCEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -85,7 +85,7 @@
* Getter for the "JvmMemManagerIndex" variable.
*/
public Integer getJvmMemManagerIndex() throws SnmpStatusException {
- return new Integer(JvmMemManagerIndex);
+ return JvmMemManagerIndex;
}
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemManagerEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemManagerEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -79,7 +79,7 @@
* Getter for the "JvmMemManagerIndex" variable.
*/
public Integer getJvmMemManagerIndex() throws SnmpStatusException {
- return new Integer(JvmMemManagerIndex);
+ return JvmMemManagerIndex;
}
/**
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemMgrPoolRelEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemMgrPoolRelEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -92,14 +92,14 @@
* Getter for the "JvmMemManagerIndex" variable.
*/
public Integer getJvmMemManagerIndex() throws SnmpStatusException {
- return new Integer(JvmMemManagerIndex);
+ return JvmMemManagerIndex;
}
/**
* Getter for the "JvmMemPoolIndex" variable.
*/
public Integer getJvmMemPoolIndex() throws SnmpStatusException {
- return new Integer(JvmMemPoolIndex);
+ return JvmMemPoolIndex;
}
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemPoolEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmMemPoolEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -430,7 +430,7 @@
* Getter for the "JvmMemPoolIndex" variable.
*/
public Integer getJvmMemPoolIndex() throws SnmpStatusException {
- return new Integer(jvmMemPoolIndex);
+ return jvmMemPoolIndex;
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmOSImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmOSImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -82,7 +82,7 @@
* Getter for the "JvmRTProcessorCount" variable.
*/
public Integer getJvmOSProcessorCount() throws SnmpStatusException {
- return new Integer(getOSMBean().getAvailableProcessors());
+ return getOSMBean().getAvailableProcessors();
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTBootClassPathEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTBootClassPathEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -72,7 +72,7 @@
* Getter for the "JvmRTBootClassPathIndex" variable.
*/
public Integer getJvmRTBootClassPathIndex() throws SnmpStatusException {
- return new Integer(index);
+ return index;
}
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTClassPathEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTClassPathEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,7 +71,7 @@
* Getter for the "JvmRTClassPathIndex" variable.
*/
public Integer getJvmRTClassPathIndex() throws SnmpStatusException {
- return new Integer(index);
+ return index;
}
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTInputArgsEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTInputArgsEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,7 +71,7 @@
* Getter for the "JvmRTInputArgsIndex" variable.
*/
public Integer getJvmRTInputArgsIndex() throws SnmpStatusException {
- return new Integer(index);
+ return index;
}
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTLibraryPathEntryImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTLibraryPathEntryImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -71,7 +71,7 @@
* Getter for the "JvmRTLibraryPathIndex" variable.
*/
public Integer getJvmRTLibraryPathIndex() throws SnmpStatusException {
- return new Integer(index);
+ return index;
}
}
--- a/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRuntimeImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRuntimeImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -241,7 +241,7 @@
final String[] args = getInputArguments(JvmContextFactory.
getUserData());
- return new Integer(args.length);
+ return args.length;
}
/**
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmClassesVerboseLevel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmClassesVerboseLevel.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "verbose");
- intTable.put(new Integer(1), "silent");
- stringTable.put("verbose", new Integer(2));
- stringTable.put("silent", new Integer(1));
+ intTable.put(2, "verbose");
+ intTable.put(1, "silent");
+ stringTable.put("verbose", 2);
+ stringTable.put("silent", 1);
}
public EnumJvmClassesVerboseLevel(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmJITCompilerTimeMonitoring.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmJITCompilerTimeMonitoring.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "supported");
- intTable.put(new Integer(1), "unsupported");
- stringTable.put("supported", new Integer(2));
- stringTable.put("unsupported", new Integer(1));
+ intTable.put(2, "supported");
+ intTable.put(1, "unsupported");
+ stringTable.put("supported", 2);
+ stringTable.put("unsupported", 1);
}
public EnumJvmJITCompilerTimeMonitoring(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemManagerState.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemManagerState.java Wed Jul 05 19:50:57 2017 +0200
@@ -50,10 +50,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "valid");
- intTable.put(new Integer(1), "invalid");
- stringTable.put("valid", new Integer(2));
- stringTable.put("invalid", new Integer(1));
+ intTable.put(2, "valid");
+ intTable.put(1, "invalid");
+ stringTable.put("valid", 2);
+ stringTable.put("invalid", 1);
}
public EnumJvmMemManagerState(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolCollectThreshdSupport.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolCollectThreshdSupport.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "supported");
- intTable.put(new Integer(1), "unsupported");
- stringTable.put("supported", new Integer(2));
- stringTable.put("unsupported", new Integer(1));
+ intTable.put(2, "supported");
+ intTable.put(1, "unsupported");
+ stringTable.put("supported", 2);
+ stringTable.put("unsupported", 1);
}
public EnumJvmMemPoolCollectThreshdSupport(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolState.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolState.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "valid");
- intTable.put(new Integer(1), "invalid");
- stringTable.put("valid", new Integer(2));
- stringTable.put("invalid", new Integer(1));
+ intTable.put(2, "valid");
+ intTable.put(1, "invalid");
+ stringTable.put("valid", 2);
+ stringTable.put("invalid", 1);
}
public EnumJvmMemPoolState(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolThreshdSupport.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolThreshdSupport.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "supported");
- intTable.put(new Integer(1), "unsupported");
- stringTable.put("supported", new Integer(2));
- stringTable.put("unsupported", new Integer(1));
+ intTable.put(2, "supported");
+ intTable.put(1, "unsupported");
+ stringTable.put("supported", 2);
+ stringTable.put("unsupported", 1);
}
public EnumJvmMemPoolThreshdSupport(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolType.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemPoolType.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "heap");
- intTable.put(new Integer(1), "nonheap");
- stringTable.put("heap", new Integer(2));
- stringTable.put("nonheap", new Integer(1));
+ intTable.put(2, "heap");
+ intTable.put(1, "nonheap");
+ stringTable.put("heap", 2);
+ stringTable.put("nonheap", 1);
}
public EnumJvmMemPoolType(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemoryGCCall.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemoryGCCall.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,16 +49,16 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "supported");
- intTable.put(new Integer(5), "failed");
- intTable.put(new Integer(4), "started");
- intTable.put(new Integer(1), "unsupported");
- intTable.put(new Integer(3), "start");
- stringTable.put("supported", new Integer(2));
- stringTable.put("failed", new Integer(5));
- stringTable.put("started", new Integer(4));
- stringTable.put("unsupported", new Integer(1));
- stringTable.put("start", new Integer(3));
+ intTable.put(2, "supported");
+ intTable.put(5, "failed");
+ intTable.put(4, "started");
+ intTable.put(1, "unsupported");
+ intTable.put(3, "start");
+ stringTable.put("supported", 2);
+ stringTable.put("failed", 5);
+ stringTable.put("started", 4);
+ stringTable.put("unsupported", 1);
+ stringTable.put("start", 3);
}
public EnumJvmMemoryGCCall(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemoryGCVerboseLevel.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmMemoryGCVerboseLevel.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "verbose");
- intTable.put(new Integer(1), "silent");
- stringTable.put("verbose", new Integer(2));
- stringTable.put("silent", new Integer(1));
+ intTable.put(2, "verbose");
+ intTable.put(1, "silent");
+ stringTable.put("verbose", 2);
+ stringTable.put("silent", 1);
}
public EnumJvmMemoryGCVerboseLevel(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmRTBootClassPathSupport.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmRTBootClassPathSupport.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,10 +49,10 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(2), "supported");
- intTable.put(new Integer(1), "unsupported");
- stringTable.put("supported", new Integer(2));
- stringTable.put("unsupported", new Integer(1));
+ intTable.put(2, "supported");
+ intTable.put(1, "unsupported");
+ stringTable.put("supported", 2);
+ stringTable.put("unsupported", 1);
}
public EnumJvmRTBootClassPathSupport(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmThreadContentionMonitoring.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmThreadContentionMonitoring.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,12 +49,12 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(3), "enabled");
- intTable.put(new Integer(4), "disabled");
- intTable.put(new Integer(1), "unsupported");
- stringTable.put("enabled", new Integer(3));
- stringTable.put("disabled", new Integer(4));
- stringTable.put("unsupported", new Integer(1));
+ intTable.put(3, "enabled");
+ intTable.put(4, "disabled");
+ intTable.put(1, "unsupported");
+ stringTable.put("enabled", 3);
+ stringTable.put("disabled", 4);
+ stringTable.put("unsupported", 1);
}
public EnumJvmThreadContentionMonitoring(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmThreadCpuTimeMonitoring.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/management/snmp/jvmmib/EnumJvmThreadCpuTimeMonitoring.java Wed Jul 05 19:50:57 2017 +0200
@@ -49,12 +49,12 @@
protected static Hashtable<String, Integer> stringTable =
new Hashtable<>();
static {
- intTable.put(new Integer(3), "enabled");
- intTable.put(new Integer(4), "disabled");
- intTable.put(new Integer(1), "unsupported");
- stringTable.put("enabled", new Integer(3));
- stringTable.put("disabled", new Integer(4));
- stringTable.put("unsupported", new Integer(1));
+ intTable.put(3, "enabled");
+ intTable.put(4, "disabled");
+ intTable.put(1, "unsupported");
+ stringTable.put("enabled", 3);
+ stringTable.put("disabled", 4);
+ stringTable.put("unsupported", 1);
}
public EnumJvmThreadCpuTimeMonitoring(int valueIndex) throws IllegalArgumentException {
--- a/jdk/src/share/classes/sun/misc/ProxyGenerator.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/misc/ProxyGenerator.java Wed Jul 05 19:50:57 2017 +0200
@@ -1743,7 +1743,7 @@
* Get or assign the index for a CONSTANT_Integer entry.
*/
public short getInteger(int i) {
- return getValue(new Integer(i));
+ return getValue(i);
}
/**
--- a/jdk/src/share/classes/sun/net/NetProperties.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/net/NetProperties.java Wed Jul 05 19:50:57 2017 +0200
@@ -123,7 +123,7 @@
} catch (NumberFormatException ex) {
}
}
- return new Integer(defval);
+ return defval;
}
/**
--- a/jdk/src/share/classes/sun/nio/ch/Util.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/Util.java Wed Jul 05 19:50:57 2017 +0200
@@ -328,7 +328,7 @@
initDBBConstructor();
try {
dbb = (MappedByteBuffer)directByteBufferConstructor.newInstance(
- new Object[] { new Integer(size),
+ new Object[] { size,
addr,
fd,
unmapper });
@@ -373,7 +373,7 @@
initDBBRConstructor();
try {
dbb = (MappedByteBuffer)directByteBufferRConstructor.newInstance(
- new Object[] { new Integer(size),
+ new Object[] { size,
addr,
fd,
unmapper });
--- a/jdk/src/share/classes/sun/print/PathGraphics.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/print/PathGraphics.java Wed Jul 05 19:50:57 2017 +0200
@@ -43,6 +43,7 @@
import java.awt.Polygon;
import java.awt.Shape;
+import java.awt.geom.Path2D;
import java.text.AttributedCharacterIterator;
import java.awt.font.FontRenderContext;
@@ -457,23 +458,18 @@
*/
public void drawPolyline(int xPoints[], int yPoints[],
int nPoints) {
- float fromX;
- float fromY;
- float toX;
- float toY;
- if (nPoints > 0) {
- fromX = xPoints[0];
- fromY = yPoints[0];
+ if (nPoints == 2) {
+ draw(new Line2D.Float(xPoints[0], yPoints[0],
+ xPoints[1], yPoints[1]));
+ } else if (nPoints > 2) {
+ Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD, nPoints);
+ path.moveTo(xPoints[0], yPoints[0]);
for(int i = 1; i < nPoints; i++) {
- toX = xPoints[i];
- toY = yPoints[i];
- draw(new Line2D.Float(fromX, fromY, toX, toY));
- fromX = toX;
- fromY = toY;
+ path.lineTo(xPoints[i], yPoints[i]);
}
+ draw(path);
}
-
}
--- a/jdk/src/share/classes/sun/rmi/rmic/RMIGenerator.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/rmic/RMIGenerator.java Wed Jul 05 19:50:57 2017 +0200
@@ -63,9 +63,9 @@
private static final Hashtable<String, Integer> versionOptions = new Hashtable<>();
static {
- versionOptions.put("-v1.1", new Integer(STUB_VERSION_1_1));
- versionOptions.put("-vcompat", new Integer(STUB_VERSION_FAT));
- versionOptions.put("-v1.2", new Integer(STUB_VERSION_1_2));
+ versionOptions.put("-v1.1", STUB_VERSION_1_1);
+ versionOptions.put("-vcompat", STUB_VERSION_FAT);
+ versionOptions.put("-v1.2", STUB_VERSION_1_2);
}
/**
--- a/jdk/src/share/classes/sun/security/action/GetIntegerAction.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/action/GetIntegerAction.java Wed Jul 05 19:50:57 2017 +0200
@@ -107,7 +107,7 @@
public Integer run() {
Integer value = Integer.getInteger(theProp);
if ((value == null) && defaultSet)
- return new Integer(defaultVal);
+ return defaultVal;
return value;
}
}
--- a/jdk/src/share/classes/sun/security/ec/ECKeyPairGenerator.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/ec/ECKeyPairGenerator.java Wed Jul 05 19:50:57 2017 +0200
@@ -125,19 +125,18 @@
try {
- long[] handles = generateECKeyPair(keySize, encodedParams, seed);
+ Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);
// The 'params' object supplied above is equivalent to the native
// one so there is no need to fetch it.
-
- // handles[0] points to the native private key
- BigInteger s = new BigInteger(1, getEncodedBytes(handles[0]));
+ // keyBytes[0] is the encoding of the native private key
+ BigInteger s = new BigInteger(1, (byte[])keyBytes[0]);
PrivateKey privateKey =
new ECPrivateKeyImpl(s, (ECParameterSpec)params);
- // handles[1] points to the native public key
- ECPoint w = ECUtil.decodePoint(getEncodedBytes(handles[1]),
+ // keyBytes[1] is the encoding of the native public key
+ ECPoint w = ECUtil.decodePoint((byte[])keyBytes[1],
((ECParameterSpec)params).getCurve());
PublicKey publicKey =
new ECPublicKeyImpl(w, (ECParameterSpec)params);
@@ -162,14 +161,9 @@
}
/*
- * Generates the keypair and returns a 2-element array of handles.
- * The first handle points to the private key, the second to the public key.
+ * Generates the keypair and returns a 2-element array of encoding bytes.
+ * The first one is for the private key, the second for the public key.
*/
- private static native long[] generateECKeyPair(int keySize,
+ private static native Object[] generateECKeyPair(int keySize,
byte[] encodedParams, byte[] seed) throws GeneralSecurityException;
-
- /*
- * Extracts the encoded key data using the supplied handle.
- */
- private static native byte[] getEncodedBytes(long handle);
}
--- a/jdk/src/share/classes/sun/security/jgss/krb5/ServiceCreds.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/ServiceCreds.java Wed Jul 05 19:50:57 2017 +0200
@@ -231,7 +231,7 @@
for (int i=0; i<ekeys.length; i++) {
ekeys[i] = new EncryptionKey(
kkeys[i].getEncoded(), kkeys[i].getKeyType(),
- new Integer(kkeys[i].getVersionNumber()));
+ kkeys[i].getVersionNumber());
}
return ekeys;
}
--- a/jdk/src/share/classes/sun/security/krb5/EncryptedData.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/EncryptedData.java Wed Jul 05 19:50:57 2017 +0200
@@ -87,7 +87,7 @@
EncryptedData new_encryptedData = new EncryptedData();
new_encryptedData.eType = eType;
if (kvno != null) {
- new_encryptedData.kvno = new Integer(kvno.intValue());
+ new_encryptedData.kvno = kvno.intValue();
}
if (cipher != null) {
new_encryptedData.cipher = new byte[cipher.length];
@@ -241,7 +241,7 @@
if ((encoding.getData().peekByte() & 0x1F) == 1) {
der = encoding.getData().getDerValue();
int i = (der.getData().getBigInteger()).intValue();
- kvno = new Integer(i);
+ kvno = i;
} else {
kvno = null;
}
--- a/jdk/src/share/classes/sun/security/krb5/KrbApRep.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbApRep.java Wed Jul 05 19:50:57 2017 +0200
@@ -180,7 +180,7 @@
Integer seqno = null;
if (seqNumber != null)
- seqno = new Integer(seqNumber.current());
+ seqno = seqNumber.current();
encPart = new EncAPRepPart(ctime,
cusec,
--- a/jdk/src/share/classes/sun/security/krb5/KrbApReq.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbApReq.java Wed Jul 05 19:50:57 2017 +0200
@@ -485,7 +485,7 @@
Integer seqno = null;
if (seqNumber != null)
- seqno = new Integer(seqNumber.current());
+ seqno = seqNumber.current();
authenticator =
new Authenticator(cname,
--- a/jdk/src/share/classes/sun/security/krb5/KrbPriv.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbPriv.java Wed Jul 05 19:50:57 2017 +0200
@@ -114,10 +114,10 @@
Integer seqno = null;
if (timestamp != null)
- usec = new Integer(timestamp.getMicroSeconds());
+ usec = timestamp.getMicroSeconds();
if (seqNumber != null) {
- seqno = new Integer(seqNumber.current());
+ seqno = seqNumber.current();
seqNumber.step();
}
--- a/jdk/src/share/classes/sun/security/krb5/KrbSafe.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbSafe.java Wed Jul 05 19:50:57 2017 +0200
@@ -115,10 +115,10 @@
Integer seqno = null;
if (timestamp != null)
- usec = new Integer(timestamp.getMicroSeconds());
+ usec = timestamp.getMicroSeconds();
if (seqNumber != null) {
- seqno = new Integer(seqNumber.current());
+ seqno = seqNumber.current();
seqNumber.step();
}
--- a/jdk/src/share/classes/sun/security/krb5/internal/Authenticator.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/Authenticator.java Wed Jul 05 19:50:57 2017 +0200
@@ -149,7 +149,7 @@
if ((der.getData().peekByte() & 0x1F) == 0x07) {
subDer = der.getData().getDerValue();
if ((subDer.getTag() & (byte) 0x1F) == (byte) 0x07) {
- seqNumber = new Integer(subDer.getData().getBigInteger().intValue());
+ seqNumber = subDer.getData().getBigInteger().intValue();
}
}
} else {
--- a/jdk/src/share/classes/sun/security/krb5/internal/EncAPRepPart.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/EncAPRepPart.java Wed Jul 05 19:50:57 2017 +0200
@@ -117,7 +117,7 @@
if ((subDer.getTag() & 0x1F) != 0x03) {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
- seqNumber = new Integer(subDer.getData().getBigInteger().intValue());
+ seqNumber = subDer.getData().getBigInteger().intValue();
} else {
seqNumber = null;
}
--- a/jdk/src/share/classes/sun/security/krb5/internal/EncKrbCredPart.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/EncKrbCredPart.java Wed Jul 05 19:50:57 2017 +0200
@@ -140,7 +140,7 @@
if (der.getData().available() > 0) {
if (((byte) (der.getData().peekByte()) & (byte) 0x1F) == (byte) 0x01) {
subDer = der.getData().getDerValue();
- nonce = new Integer(subDer.getData().getBigInteger().intValue());
+ nonce = subDer.getData().getBigInteger().intValue();
}
}
if (der.getData().available() > 0) {
@@ -149,7 +149,7 @@
if (der.getData().available() > 0) {
if (((byte) (der.getData().peekByte()) & (byte) 0x1F) == (byte) 0x03) {
subDer = der.getData().getDerValue();
- usec = new Integer(subDer.getData().getBigInteger().intValue());
+ usec = subDer.getData().getBigInteger().intValue();
}
}
if (der.getData().available() > 0) {
--- a/jdk/src/share/classes/sun/security/krb5/internal/EncKrbPrivPart.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/EncKrbPrivPart.java Wed Jul 05 19:50:57 2017 +0200
@@ -115,13 +115,13 @@
timestamp = KerberosTime.parse(der.getData(), (byte) 0x01, true);
if ((der.getData().peekByte() & 0x1F) == 0x02) {
subDer = der.getData().getDerValue();
- usec = new Integer(subDer.getData().getBigInteger().intValue());
+ usec = subDer.getData().getBigInteger().intValue();
} else {
usec = null;
}
if ((der.getData().peekByte() & 0x1F) == 0x03) {
subDer = der.getData().getDerValue();
- seqNumber = new Integer(subDer.getData().getBigInteger().intValue());
+ seqNumber = subDer.getData().getBigInteger().intValue();
} else {
seqNumber = null;
}
--- a/jdk/src/share/classes/sun/security/krb5/internal/KRBError.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/KRBError.java Wed Jul 05 19:50:57 2017 +0200
@@ -335,13 +335,13 @@
cTime = KerberosTime.parse(der.getData(), (byte)0x02, true);
if ((der.getData().peekByte() & 0x1F) == 0x03) {
subDer = der.getData().getDerValue();
- cuSec = new Integer(subDer.getData().getBigInteger().intValue());
+ cuSec = subDer.getData().getBigInteger().intValue();
}
else cuSec = null;
sTime = KerberosTime.parse(der.getData(), (byte)0x04, false);
subDer = der.getData().getDerValue();
if ((subDer.getTag() & (byte)0x1F) == (byte)0x05) {
- suSec = new Integer (subDer.getData().getBigInteger().intValue());
+ suSec = subDer.getData().getBigInteger().intValue();
}
else throw new Asn1Exception(Krb5.ASN1_BAD_ID);
subDer = der.getData().getDerValue();
--- a/jdk/src/share/classes/sun/security/krb5/internal/KRBSafeBody.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/KRBSafeBody.java Wed Jul 05 19:50:57 2017 +0200
@@ -104,11 +104,11 @@
timestamp = KerberosTime.parse(encoding.getData(), (byte)0x01, true);
if ((encoding.getData().peekByte() & 0x1F) == 0x02) {
der = encoding.getData().getDerValue();
- usec = new Integer(der.getData().getBigInteger().intValue());
+ usec = der.getData().getBigInteger().intValue();
}
if ((encoding.getData().peekByte() & 0x1F) == 0x03) {
der = encoding.getData().getDerValue();
- seqNumber = new Integer(der.getData().getBigInteger().intValue());
+ seqNumber = der.getData().getBigInteger().intValue();
}
sAddress = HostAddress.parse(encoding.getData(), (byte)0x04, false);
if (encoding.getData().available() > 0)
--- a/jdk/src/share/classes/sun/security/krb5/internal/PAEncTSEnc.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/PAEncTSEnc.java Wed Jul 05 19:50:57 2017 +0200
@@ -67,7 +67,7 @@
public PAEncTSEnc() {
KerberosTime now = KerberosTime.now();
pATimeStamp = now;
- pAUSec = new Integer(now.getMicroSeconds());
+ pAUSec = now.getMicroSeconds();
}
/**
@@ -85,7 +85,7 @@
if (encoding.getData().available() > 0) {
der = encoding.getData().getDerValue();
if ((der.getTag() & 0x1F) == 0x01) {
- pAUSec = new Integer(der.getData().getBigInteger().intValue());
+ pAUSec = der.getData().getBigInteger().intValue();
}
else throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
--- a/jdk/src/share/classes/sun/security/krb5/internal/ccache/CCacheInputStream.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/ccache/CCacheInputStream.java Wed Jul 05 19:50:57 2017 +0200
@@ -94,8 +94,8 @@
taglen = read(2);
switch (tag) {
case FCC_TAG_DELTATIME:
- time_offset = new Integer(read(4));
- usec_offset = new Integer(read(4));
+ time_offset = read(4);
+ usec_offset = read(4);
break;
default:
}
@@ -186,7 +186,7 @@
read(2); /* keytype recorded twice in fvno 3 */
keyLen = read(4);
byte[] bytes = IOUtils.readFully(this, keyLen, true);
- return new EncryptionKey(bytes, keyType, new Integer(version));
+ return new EncryptionKey(bytes, keyType, version);
}
long[] readTimes() throws IOException {
--- a/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java Wed Jul 05 19:50:57 2017 +0200
@@ -297,7 +297,7 @@
if (EType.isSupported(entry.keyType)) {
key = new EncryptionKey(entry.keyblock,
entry.keyType,
- new Integer(entry.keyVersion));
+ entry.keyVersion);
keys.add(key);
if (DEBUG) {
System.out.println("Added key: " + entry.keyType +
--- a/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTabEntry.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTabEntry.java Wed Jul 05 19:50:57 2017 +0200
@@ -68,7 +68,7 @@
public EncryptionKey getKey() {
EncryptionKey key = new EncryptionKey(keyblock,
keyType,
- new Integer(keyVersion));
+ keyVersion);
return key;
}
--- a/jdk/src/share/classes/sun/security/provider/ConfigFile.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/provider/ConfigFile.java Wed Jul 05 19:50:57 2017 +0200
@@ -531,7 +531,7 @@
} else {
throw ioException(
"Configuration.Error.Line.line.expected.expect.found.value.",
- new Integer(linenum), expect, st.sval);
+ linenum, expect, st.sval);
}
break;
@@ -541,7 +541,7 @@
} else {
throw ioException(
"Configuration.Error.Line.line.expected.expect.",
- new Integer(linenum), expect, st.sval);
+ linenum, expect, st.sval);
}
break;
@@ -551,7 +551,7 @@
} else {
throw ioException(
"Configuration.Error.Line.line.expected.expect.",
- new Integer(linenum), expect, st.sval);
+ linenum, expect, st.sval);
}
break;
@@ -561,7 +561,7 @@
} else {
throw ioException(
"Configuration.Error.Line.line.expected.expect.",
- new Integer(linenum), expect, st.sval);
+ linenum, expect, st.sval);
}
break;
@@ -571,14 +571,14 @@
} else {
throw ioException(
"Configuration.Error.Line.line.expected.expect.",
- new Integer(linenum), expect, st.sval);
+ linenum, expect, st.sval);
}
break;
default:
throw ioException(
"Configuration.Error.Line.line.expected.expect.found.value.",
- new Integer(linenum), expect, st.sval);
+ linenum, expect, st.sval);
}
return value;
}
@@ -655,7 +655,7 @@
if (s == null || s.length() == 0) {
throw ioException(
"Configuration.Error.Line.line.system.property.value.expanded.to.empty.value",
- new Integer(linenum), value);
+ linenum, value);
}
return s;
}
--- a/jdk/src/share/classes/sun/security/provider/PolicyParser.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/provider/PolicyParser.java Wed Jul 05 19:50:57 2017 +0200
@@ -1405,7 +1405,7 @@
super("line " + line + ": " + msg);
MessageFormat form = new MessageFormat
(ResourcesMgr.getString("line.number.msg"));
- Object[] source = {new Integer(line), msg};
+ Object[] source = {line, msg};
i18nMessage = form.format(source);
}
@@ -1414,7 +1414,7 @@
"], found [" + actual + "]");
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("line.number.expected.expect.found.actual."));
- Object[] source = {new Integer(line), expect, actual};
+ Object[] source = {line, expect, actual};
i18nMessage = form.format(source);
}
--- a/jdk/src/share/classes/sun/security/rsa/RSACore.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/rsa/RSACore.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -50,6 +50,15 @@
*/
public final class RSACore {
+ // globally enable/disable use of blinding
+ private final static boolean ENABLE_BLINDING = true;
+
+ // cache for blinding parameters. Map<BigInteger, BlindingParameters>
+ // use a weak hashmap so that cached values are automatically cleared
+ // when the modulus is GC'ed
+ private final static Map<BigInteger, BlindingParameters>
+ blindingCache = new WeakHashMap<>();
+
private RSACore() {
// empty
}
@@ -100,12 +109,12 @@
if (key instanceof RSAPrivateCrtKey) {
return crtCrypt(msg, (RSAPrivateCrtKey)key);
} else {
- return crypt(msg, key.getModulus(), key.getPrivateExponent());
+ return priCrypt(msg, key.getModulus(), key.getPrivateExponent());
}
}
/**
- * RSA public key ops and non-CRT private key ops. Simple modPow().
+ * RSA public key ops. Simple modPow().
*/
private static byte[] crypt(byte[] msg, BigInteger n, BigInteger exp)
throws BadPaddingException {
@@ -115,22 +124,29 @@
}
/**
+ * RSA non-CRT private key operations.
+ */
+ private static byte[] priCrypt(byte[] msg, BigInteger n, BigInteger exp)
+ throws BadPaddingException {
+
+ BigInteger c = parseMsg(msg, n);
+ BlindingRandomPair brp = null;
+ BigInteger m;
+ if (ENABLE_BLINDING) {
+ brp = getBlindingRandomPair(null, exp, n);
+ c = c.multiply(brp.u).mod(n);
+ m = c.modPow(exp, n);
+ m = m.multiply(brp.v).mod(n);
+ } else {
+ m = c.modPow(exp, n);
+ }
+
+ return toByteArray(m, getByteLength(n));
+ }
+
+ /**
* RSA private key operations with CRT. Algorithm and variable naming
* are taken from PKCS#1 v2.1, section 5.1.2.
- *
- * The only difference is the addition of blinding to twart timing attacks.
- * This is described in the RSA Bulletin#2 (Jan 96) among other places.
- * This means instead of implementing RSA as
- * m = c ^ d mod n (or RSA in CRT variant)
- * we do
- * r = random(0, n-1)
- * c' = c * r^e mod n
- * m' = c' ^ d mod n (or RSA in CRT variant)
- * m = m' * r^-1 mod n (where r^-1 is the modular inverse of r mod n)
- * This works because r^(e*d) * r^-1 = r * r^-1 = 1 (all mod n)
- *
- * We do not generate new blinding parameters for each operation but reuse
- * them BLINDING_MAX_REUSE times (see definition below).
*/
private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key)
throws BadPaddingException {
@@ -141,13 +157,13 @@
BigInteger dP = key.getPrimeExponentP();
BigInteger dQ = key.getPrimeExponentQ();
BigInteger qInv = key.getCrtCoefficient();
+ BigInteger e = key.getPublicExponent();
+ BigInteger d = key.getPrivateExponent();
- BlindingParameters params;
+ BlindingRandomPair brp;
if (ENABLE_BLINDING) {
- params = getBlindingParameters(key);
- c = c.multiply(params.re).mod(n);
- } else {
- params = null;
+ brp = getBlindingRandomPair(e, d, n);
+ c = c.multiply(brp.u).mod(n);
}
// m1 = c ^ dP mod p
@@ -165,8 +181,8 @@
// m = m2 + q * h
BigInteger m = h.multiply(q).add(m2);
- if (params != null) {
- m = m.multiply(params.rInv).mod(n);
+ if (ENABLE_BLINDING) {
+ m = m.multiply(brp.v).mod(n);
}
return toByteArray(m, getByteLength(n));
@@ -208,82 +224,217 @@
return t;
}
- // globally enable/disable use of blinding
- private final static boolean ENABLE_BLINDING = true;
+ /**
+ * Parameters (u,v) for RSA Blinding. This is described in the RSA
+ * Bulletin#2 (Jan 96) and other places:
+ *
+ * ftp://ftp.rsa.com/pub/pdfs/bull-2.pdf
+ *
+ * The standard RSA Blinding decryption requires the public key exponent
+ * (e) and modulus (n), and converts ciphertext (c) to plaintext (p).
+ *
+ * Before the modular exponentiation operation, the input message should
+ * be multiplied by (u (mod n)), and afterward the result is corrected
+ * by multiplying with (v (mod n)). The system should reject messages
+ * equal to (0 (mod n)). That is:
+ *
+ * 1. Generate r between 0 and n-1, relatively prime to n.
+ * 2. Compute x = (c*u) mod n
+ * 3. Compute y = (x^d) mod n
+ * 4. Compute p = (y*v) mod n
+ *
+ * The Java APIs allows for either standard RSAPrivateKey or
+ * RSAPrivateCrtKey RSA keys.
+ *
+ * If the public exponent is available to us (e.g. RSAPrivateCrtKey),
+ * choose a random r, then let (u, v):
+ *
+ * u = r ^ e mod n
+ * v = r ^ (-1) mod n
+ *
+ * The proof follows:
+ *
+ * p = (((c * u) ^ d mod n) * v) mod n
+ * = ((c ^ d) * (u ^ d) * v) mod n
+ * = ((c ^ d) * (r ^ e) ^ d) * (r ^ (-1))) mod n
+ * = ((c ^ d) * (r ^ (e * d)) * (r ^ (-1))) mod n
+ * = ((c ^ d) * (r ^ 1) * (r ^ (-1))) mod n (see below)
+ * = (c ^ d) mod n
+ *
+ * because in RSA cryptosystem, d is the multiplicative inverse of e:
+ *
+ * (r^(e * d)) mod n
+ * = (r ^ 1) mod n
+ * = r mod n
+ *
+ * However, if the public exponent is not available (e.g. RSAPrivateKey),
+ * we mitigate the timing issue by using a similar random number blinding
+ * approach using the private key:
+ *
+ * u = r
+ * v = ((r ^ (-1)) ^ d) mod n
+ *
+ * This returns the same plaintext because:
+ *
+ * p = (((c * u) ^ d mod n) * v) mod n
+ * = ((c ^ d) * (u ^ d) * v) mod n
+ * = ((c ^ d) * (u ^ d) * ((u ^ (-1)) ^d)) mod n
+ * = (c ^ d) mod n
+ *
+ * Computing inverses mod n and random number generation is slow, so
+ * it is often not practical to generate a new random (u, v) pair for
+ * each new exponentiation. The calculation of parameters might even be
+ * subject to timing attacks. However, (u, v) pairs should not be
+ * reused since they themselves might be compromised by timing attacks,
+ * leaving the private exponent vulnerable. An efficient solution to
+ * this problem is update u and v before each modular exponentiation
+ * step by computing:
+ *
+ * u = u ^ 2
+ * v = v ^ 2
+ *
+ * The total performance cost is small.
+ */
+ private final static class BlindingRandomPair {
+ final BigInteger u;
+ final BigInteger v;
- // maximum number of times that we will use a set of blinding parameters
- // value suggested by Paul Kocher (quoted by NSS)
- private final static int BLINDING_MAX_REUSE = 50;
-
- // cache for blinding parameters. Map<BigInteger, BlindingParameters>
- // use a weak hashmap so that cached values are automatically cleared
- // when the modulus is GC'ed
- private final static Map<BigInteger, BlindingParameters> blindingCache =
- new WeakHashMap<>();
+ BlindingRandomPair(BigInteger u, BigInteger v) {
+ this.u = u;
+ this.v = v;
+ }
+ }
/**
* Set of blinding parameters for a given RSA key.
*
* The RSA modulus is usually unique, so we index by modulus in
- * blindingCache. However, to protect against the unlikely case of two
- * keys sharing the same modulus, we also store the public exponent.
- * This means we cannot cache blinding parameters for multiple keys that
- * share the same modulus, but since sharing moduli is fundamentally broken
- * an insecure, this does not matter.
+ * {@code blindingCache}. However, to protect against the unlikely
+ * case of two keys sharing the same modulus, we also store the public
+ * or the private exponent. This means we cannot cache blinding
+ * parameters for multiple keys that share the same modulus, but
+ * since sharing moduli is fundamentally broken and insecure, this
+ * does not matter.
*/
- private static final class BlindingParameters {
- // e (RSA public exponent)
- final BigInteger e;
- // r ^ e mod n
- final BigInteger re;
- // inverse of r mod n
- final BigInteger rInv;
- // how many more times this parameter object can be used
- private volatile int remainingUses;
- BlindingParameters(BigInteger e, BigInteger re, BigInteger rInv) {
+ private final static class BlindingParameters {
+ private final static BigInteger BIG_TWO = BigInteger.valueOf(2L);
+
+ // RSA public exponent
+ private final BigInteger e;
+
+ // hash code of RSA private exponent
+ private final BigInteger d;
+
+ // r ^ e mod n (CRT), or r mod n (Non-CRT)
+ private BigInteger u;
+
+ // r ^ (-1) mod n (CRT) , or ((r ^ (-1)) ^ d) mod n (Non-CRT)
+ private BigInteger v;
+
+ // e: the public exponent
+ // d: the private exponent
+ // n: the modulus
+ BlindingParameters(BigInteger e, BigInteger d, BigInteger n) {
+ this.u = null;
+ this.v = null;
this.e = e;
- this.re = re;
- this.rInv = rInv;
- // initialize remaining uses, subtract current use now
- remainingUses = BLINDING_MAX_REUSE - 1;
+ this.d = d;
+
+ int len = n.bitLength();
+ SecureRandom random = JCAUtil.getSecureRandom();
+ u = new BigInteger(len, random).mod(n);
+ // Although the possibility is very much limited that u is zero
+ // or is not relatively prime to n, we still want to be careful
+ // about the special value.
+ //
+ // Secure random generation is expensive, try to use BigInteger.ONE
+ // this time if this new generated random number is zero or is not
+ // relatively prime to n. Next time, new generated secure random
+ // number will be used instead.
+ if (u.equals(BigInteger.ZERO)) {
+ u = BigInteger.ONE; // use 1 this time
+ }
+
+ try {
+ // The call to BigInteger.modInverse() checks that u is
+ // relatively prime to n. Otherwise, ArithmeticException is
+ // thrown.
+ v = u.modInverse(n);
+ } catch (ArithmeticException ae) {
+ // if u is not relatively prime to n, use 1 this time
+ u = BigInteger.ONE;
+ v = BigInteger.ONE;
+ }
+
+ if (e != null) {
+ u = u.modPow(e, n); // e: the public exponent
+ // u: random ^ e
+ // v: random ^ (-1)
+ } else {
+ v = v.modPow(d, n); // d: the private exponent
+ // u: random
+ // v: random ^ (-d)
+ }
}
- boolean valid(BigInteger e) {
- int k = remainingUses--;
- return (k > 0) && this.e.equals(e);
+
+ // return null if need to reset the parameters
+ BlindingRandomPair getBlindingRandomPair(
+ BigInteger e, BigInteger d, BigInteger n) {
+
+ if ((this.e != null && this.e.equals(e)) ||
+ (this.d != null && this.d.equals(d))) {
+
+ BlindingRandomPair brp = null;
+ synchronized (this) {
+ if (!u.equals(BigInteger.ZERO) &&
+ !v.equals(BigInteger.ZERO)) {
+
+ brp = new BlindingRandomPair(u, v);
+ if (u.compareTo(BigInteger.ONE) <= 0 ||
+ v.compareTo(BigInteger.ONE) <= 0) {
+
+ // need to reset the random pair next time
+ u = BigInteger.ZERO;
+ v = BigInteger.ZERO;
+ } else {
+ u = u.modPow(BIG_TWO, n);
+ v = v.modPow(BIG_TWO, n);
+ }
+ } // Otherwise, need to reset the random pair.
+ }
+ return brp;
+ }
+
+ return null;
}
}
- /**
- * Return valid RSA blinding parameters for the given private key.
- * Use cached parameters if available. If not, generate new parameters
- * and cache.
- */
- private static BlindingParameters getBlindingParameters
- (RSAPrivateCrtKey key) {
- BigInteger modulus = key.getModulus();
- BigInteger e = key.getPublicExponent();
- BlindingParameters params;
- // we release the lock between get() and put()
- // that means threads might concurrently generate new blinding
- // parameters for the same modulus. this is only a slight waste
- // of cycles and seems preferable in terms of scalability
- // to locking out all threads while generating new parameters
+ private static BlindingRandomPair getBlindingRandomPair(
+ BigInteger e, BigInteger d, BigInteger n) {
+
+ BlindingParameters bps = null;
synchronized (blindingCache) {
- params = blindingCache.get(modulus);
+ bps = blindingCache.get(n);
}
- if ((params != null) && params.valid(e)) {
- return params;
+
+ if (bps == null) {
+ bps = new BlindingParameters(e, d, n);
+ synchronized (blindingCache) {
+ blindingCache.putIfAbsent(n, bps);
+ }
}
- int len = modulus.bitLength();
- SecureRandom random = JCAUtil.getSecureRandom();
- BigInteger r = new BigInteger(len, random).mod(modulus);
- BigInteger re = r.modPow(e, modulus);
- BigInteger rInv = r.modInverse(modulus);
- params = new BlindingParameters(e, re, rInv);
- synchronized (blindingCache) {
- blindingCache.put(modulus, params);
+
+ BlindingRandomPair brp = bps.getBlindingRandomPair(e, d, n);
+ if (brp == null) {
+ // need to reset the blinding parameters
+ bps = new BlindingParameters(e, d, n);
+ synchronized (blindingCache) {
+ blindingCache.replace(n, bps);
+ }
+ brp = bps.getBlindingRandomPair(e, d, n);
}
- return params;
+
+ return brp;
}
}
--- a/jdk/src/share/classes/sun/security/tools/keytool/Main.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/tools/keytool/Main.java Wed Jul 05 19:50:57 2017 +0200
@@ -1577,7 +1577,7 @@
if (verbose) {
MessageFormat form = new MessageFormat(rb.getString
("Generated.keysize.bit.keyAlgName.secret.key"));
- Object[] source = {new Integer(keysize),
+ Object[] source = {keysize,
secKey.getAlgorithm()};
System.err.println(form.format(source));
}
@@ -1672,7 +1672,7 @@
if (verbose) {
MessageFormat form = new MessageFormat(rb.getString
("Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for"));
- Object[] source = {new Integer(keysize),
+ Object[] source = {keysize,
privKey.getAlgorithm(),
chain[0].getSigAlgName(),
validity,
@@ -1833,7 +1833,7 @@
for (int i = 0; i < chain.length; i ++) {
MessageFormat form = new MessageFormat
(rb.getString("Certificate.i.1."));
- Object[] source = {new Integer((i + 1))};
+ Object[] source = {(i + 1)};
out.println(form.format(source));
if (verbose && (chain[i] instanceof X509Certificate)) {
printX509Cert((X509Certificate)(chain[i]), out);
@@ -2108,7 +2108,7 @@
("Your.keystore.contains.keyStore.size.entry")) :
new MessageFormat(rb.getString
("Your.keystore.contains.keyStore.size.entries"));
- Object[] source = {new Integer(keyStore.size())};
+ Object[] source = {keyStore.size()};
out.println(form.format(source));
out.println();
@@ -2380,7 +2380,7 @@
if (certs.length > 1) {
MessageFormat form = new MessageFormat
(rb.getString("Certificate.i.1."));
- Object[] source = {new Integer(i + 1)};
+ Object[] source = {i + 1};
out.println(form.format(source));
}
if (rfc)
--- a/jdk/src/share/classes/sun/security/util/DerIndefLenConverter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/util/DerIndefLenConverter.java Wed Jul 05 19:50:57 2017 +0200
@@ -150,7 +150,7 @@
return curLen;
int lenByte = data[dataPos++] & 0xff;
if (isIndefinite(lenByte)) {
- ndefsList.add(new Integer(dataPos));
+ ndefsList.add(dataPos);
unresolved++;
return curLen;
}
--- a/jdk/src/share/classes/sun/security/util/KeyUtil.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/util/KeyUtil.java Wed Jul 05 19:50:57 2017 +0200
@@ -272,7 +272,16 @@
"Diffie-Hellman public key is too large");
}
- // Don't bother to check against the y^q mod p if safe primes are used.
+ // y^q mod p == 1?
+ // Unable to perform this check as q is unknown in this circumstance.
+
+ // p is expected to be prime. However, it is too expensive to check
+ // that p is prime. Instead, in order to mitigate the impact of
+ // non-prime values, we check that y is not a factor of p.
+ BigInteger r = p.remainder(y);
+ if (r.equals(BigInteger.ZERO)) {
+ throw new InvalidKeyException("Invalid Diffie-Hellman parameters");
+ }
}
/**
--- a/jdk/src/share/classes/sun/security/x509/CRLReasonCodeExtension.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/x509/CRLReasonCodeExtension.java Wed Jul 05 19:50:57 2017 +0200
@@ -125,7 +125,7 @@
*/
public Integer get(String name) throws IOException {
if (name.equalsIgnoreCase(REASON)) {
- return new Integer(reasonCode);
+ return reasonCode;
} else {
throw new IOException
("Name not supported by CRLReasonCodeExtension");
--- a/jdk/src/share/classes/sun/security/x509/CertificateVersion.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/x509/CertificateVersion.java Wed Jul 05 19:50:57 2017 +0200
@@ -193,7 +193,7 @@
*/
public Integer get(String name) throws IOException {
if (name.equalsIgnoreCase(VERSION)) {
- return(new Integer(getVersion()));
+ return(getVersion());
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateVersion.");
--- a/jdk/src/share/classes/sun/security/x509/InhibitAnyPolicyExtension.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/x509/InhibitAnyPolicyExtension.java Wed Jul 05 19:50:57 2017 +0200
@@ -217,7 +217,7 @@
*/
public Integer get(String name) throws IOException {
if (name.equalsIgnoreCase(SKIP_CERTS))
- return (new Integer(skipCerts));
+ return (skipCerts);
else
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:InhibitAnyPolicy.");
--- a/jdk/src/share/classes/sun/security/x509/PolicyConstraintsExtension.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/security/x509/PolicyConstraintsExtension.java Wed Jul 05 19:50:57 2017 +0200
@@ -233,9 +233,9 @@
*/
public Integer get(String name) throws IOException {
if (name.equalsIgnoreCase(REQUIRE)) {
- return new Integer(require);
+ return require;
} else if (name.equalsIgnoreCase(INHIBIT)) {
- return new Integer(inhibit);
+ return inhibit;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:PolicyConstraints.");
--- a/jdk/src/share/classes/sun/swing/BakedArrayList.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/swing/BakedArrayList.java Wed Jul 05 19:50:57 2017 +0200
@@ -44,7 +44,7 @@
* @author Scott Violet
*/
@SuppressWarnings("serial") // JDK-implementation class
-public class BakedArrayList extends ArrayList<Object> {
+public class BakedArrayList<E> extends ArrayList<E> {
/**
* The cached hashCode.
*/
@@ -54,7 +54,7 @@
super(size);
}
- public BakedArrayList(java.util.List<?> data) {
+ public BakedArrayList(java.util.List<? extends E> data) {
this(data.size());
for (int counter = 0, max = data.size(); counter < max; counter++){
add(data.get(counter));
@@ -78,7 +78,8 @@
}
public boolean equals(Object o) {
- BakedArrayList list = (BakedArrayList)o;
+ @SuppressWarnings("unchecked")
+ BakedArrayList<E> list = (BakedArrayList)o;
int size = size();
if (list.size() != size) {
--- a/jdk/src/share/classes/sun/text/normalizer/UnicodeSet.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/text/normalizer/UnicodeSet.java Wed Jul 05 19:50:57 2017 +0200
@@ -367,6 +367,7 @@
* copied to this object
* @stable ICU 2.0
*/
+ @SuppressWarnings("unchecked") // Casting result of clone of a collection
public UnicodeSet set(UnicodeSet other) {
list = other.list.clone();
len = other.len;
--- a/jdk/src/share/classes/sun/tools/asm/Assembler.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/asm/Assembler.java Wed Jul 05 19:50:57 2017 +0200
@@ -558,7 +558,7 @@
case opc_tableswitch: {
SwitchData sw = (SwitchData)inst.value;
for (int i = sw.minValue; i <= sw.maxValue; i++) {
- TableLot.addElement(new Cover(CT_CASE, sw.whereCase(new Integer(i)), inst.pc));
+ TableLot.addElement(new Cover(CT_CASE, sw.whereCase(i), inst.pc));
count++;
}
if (!sw.getDefault()) {
--- a/jdk/src/share/classes/sun/tools/asm/Instruction.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/asm/Instruction.java Wed Jul 05 19:50:57 2017 +0200
@@ -142,7 +142,7 @@
// Don't keep the LocalVariable info around, unless we
// are actually going to generate a local variable table.
if ((value instanceof LocalVariable) && !env.debug_vars()) {
- value = new Integer(((LocalVariable)value).slot);
+ value = ((LocalVariable)value).slot;
}
break;
--- a/jdk/src/share/classes/sun/tools/java/BinaryConstantPool.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/java/BinaryConstantPool.java Wed Jul 05 19:50:57 2017 +0200
@@ -60,7 +60,7 @@
break;
case CONSTANT_INTEGER:
- cpool[i] = new Integer(in.readInt());
+ cpool[i] = in.readInt();
break;
case CONSTANT_FLOAT:
cpool[i] = new Float(in.readFloat());
@@ -76,7 +76,7 @@
case CONSTANT_STRING:
// JVM 4.4.3 CONSTANT_String_info.string_index
// or JVM 4.4.1 CONSTANT_Class_info.name_index
- cpool[i] = new Integer(in.readUnsignedShort());
+ cpool[i] =in.readUnsignedShort();
break;
case CONSTANT_FIELD:
@@ -84,7 +84,7 @@
case CONSTANT_INTERFACEMETHOD:
case CONSTANT_NAMEANDTYPE:
// JVM 4.4.2 CONSTANT_*ref_info.class_index & name_and_type_index
- cpool[i] = new Integer((in.readUnsignedShort() << 16) | in.readUnsignedShort());
+ cpool[i] = (in.readUnsignedShort() << 16) | in.readUnsignedShort();
break;
case CONSTANT_METHODHANDLE:
@@ -260,7 +260,7 @@
Integer result = (Integer)indexHashAscii.get(string);
if (result == null) {
if (MoreStuff == null) MoreStuff = new Vector();
- result = new Integer(cpool.length + MoreStuff.size());
+ result = cpool.length + MoreStuff.size();
MoreStuff.addElement(string);
indexHashAscii.put(string, result);
}
@@ -277,10 +277,10 @@
indexHashAscii = new Hashtable();
for (int i = 1; i < cpool.length; i++) {
if (types[i] == CONSTANT_UTF8) {
- indexHashAscii.put(cpool[i], new Integer(i));
+ indexHashAscii.put(cpool[i], i);
} else {
try {
- indexHashObject.put(getConstant(i, env), new Integer(i));
+ indexHashObject.put(getConstant(i, env), i);
} catch (ClassFormatError e) { }
}
}
--- a/jdk/src/share/classes/sun/tools/java/Identifier.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/java/Identifier.java Wed Jul 05 19:50:57 2017 +0200
@@ -106,7 +106,7 @@
* Set the type of the identifier.
*/
void setType(int t) {
- value = new Integer(t);
+ value = t;
//System.out.println("type(" + this + ")=" + t);
}
--- a/jdk/src/share/classes/sun/tools/javac/BatchEnvironment.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/javac/BatchEnvironment.java Wed Jul 05 19:50:57 2017 +0200
@@ -1172,7 +1172,7 @@
if (!hitErrorLimit) {
hitErrorLimit = true;
output(errorString("too.many.errors",
- new Integer(errorLimit),null,null));
+ errorLimit,null,null));
}
return;
}
--- a/jdk/src/share/classes/sun/tools/javac/Main.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/javac/Main.java Wed Jul 05 19:50:57 2017 +0200
@@ -669,18 +669,18 @@
if (env.deprecation()) {
if (ndepfiles > 1) {
env.error(0, "warn.note.deprecations",
- new Integer(ndepfiles), new Integer(ndeps));
+ ndepfiles, ndeps);
} else {
env.error(0, "warn.note.1deprecation",
- file1, new Integer(ndeps));
+ file1, ndeps);
}
} else {
if (ndepfiles > 1) {
env.error(0, "warn.note.deprecations.silent",
- new Integer(ndepfiles), new Integer(ndeps));
+ ndepfiles, ndeps);
} else {
env.error(0, "warn.note.1deprecation.silent",
- file1, new Integer(ndeps));
+ file1, ndeps);
}
}
}
--- a/jdk/src/share/classes/sun/tools/javac/SourceMember.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/javac/SourceMember.java Wed Jul 05 19:50:57 2017 +0200
@@ -885,7 +885,7 @@
// instance initializers. Code for these is generated
// in the makeVarInits() method of the class
// MethodExpression.
- asm.add(getWhere(), opc_aload, new Integer(0));
+ asm.add(getWhere(), opc_aload, 0);
e.codeValue(env, ctx, asm);
asm.add(getWhere(), opc_putfield, this);
}
--- a/jdk/src/share/classes/sun/tools/jconsole/inspector/TableSorter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/inspector/TableSorter.java Wed Jul 05 19:50:57 2017 +0200
@@ -217,17 +217,17 @@
}
}
- private Vector<?> getRow(int row) {
- return (Vector) dataVector.elementAt(row);
+ private Vector<Object> getRow(int row) {
+ return dataVector.elementAt(row);
}
@SuppressWarnings("unchecked")
- private void setRow(Vector<?> data, int row) {
+ private void setRow(Vector<Object> data, int row) {
dataVector.setElementAt(data,row);
}
private void swap(int i, int j, int column) {
- Vector<?> data = getRow(i);
+ Vector<Object> data = getRow(i);
setRow(getRow(j),i);
setRow(data,j);
--- a/jdk/src/share/classes/sun/tools/jstat/Jstat.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/jstat/Jstat.java Wed Jul 05 19:50:57 2017 +0200
@@ -158,7 +158,7 @@
// handle target termination events for targets other than ourself
HostListener terminator = new HostListener() {
public void vmStatusChanged(VmStatusChangeEvent ev) {
- Integer lvmid = new Integer(vmId.getLocalVmId());
+ Integer lvmid = vmId.getLocalVmId();
if (ev.getTerminated().contains(lvmid)) {
logger.stopLogging();
} else if (!ev.getActive().contains(lvmid)) {
--- a/jdk/src/share/classes/sun/tools/jstatd/RemoteHostImpl.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/jstatd/RemoteHostImpl.java Wed Jul 05 19:50:57 2017 +0200
@@ -62,7 +62,7 @@
public RemoteVm attachVm(int lvmid, String mode)
throws RemoteException, MonitorException {
- Integer v = new Integer(lvmid);
+ Integer v = lvmid;
RemoteVm stub = null;
StringBuilder sb = new StringBuilder();
--- a/jdk/src/share/classes/sun/tools/tree/ArrayExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/ArrayExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -92,16 +92,16 @@
*/
public void codeValue(Environment env, Context ctx, Assembler asm) {
int t = 0;
- asm.add(where, opc_ldc, new Integer(args.length));
+ asm.add(where, opc_ldc, args.length);
switch (type.getElementType().getTypeCode()) {
- case TC_BOOLEAN: asm.add(where, opc_newarray, new Integer(T_BOOLEAN)); break;
- case TC_BYTE: asm.add(where, opc_newarray, new Integer(T_BYTE)); break;
- case TC_SHORT: asm.add(where, opc_newarray, new Integer(T_SHORT)); break;
- case TC_CHAR: asm.add(where, opc_newarray, new Integer(T_CHAR)); break;
- case TC_INT: asm.add(where, opc_newarray, new Integer(T_INT)); break;
- case TC_LONG: asm.add(where, opc_newarray, new Integer(T_LONG)); break;
- case TC_FLOAT: asm.add(where, opc_newarray, new Integer(T_FLOAT)); break;
- case TC_DOUBLE: asm.add(where, opc_newarray, new Integer(T_DOUBLE)); break;
+ case TC_BOOLEAN: asm.add(where, opc_newarray, T_BOOLEAN); break;
+ case TC_BYTE: asm.add(where, opc_newarray, T_BYTE); break;
+ case TC_SHORT: asm.add(where, opc_newarray, T_SHORT); break;
+ case TC_CHAR: asm.add(where, opc_newarray, T_CHAR); break;
+ case TC_INT: asm.add(where, opc_newarray, T_INT); break;
+ case TC_LONG: asm.add(where, opc_newarray, T_LONG); break;
+ case TC_FLOAT: asm.add(where, opc_newarray, T_FLOAT); break;
+ case TC_DOUBLE: asm.add(where, opc_newarray, T_DOUBLE); break;
case TC_ARRAY:
asm.add(where, opc_anewarray, type.getElementType());
@@ -122,7 +122,7 @@
if (args[i].equalsDefault()) continue;
asm.add(where, opc_dup);
- asm.add(where, opc_ldc, new Integer(i));
+ asm.add(where, opc_ldc, i);
args[i].codeValue(env, ctx, asm);
switch (type.getElementType().getTypeCode()) {
case TC_BOOLEAN:
--- a/jdk/src/share/classes/sun/tools/tree/BinaryExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/BinaryExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -212,10 +212,10 @@
Label l2 = new Label();
codeBranch(env, ctx, asm, l1, true);
- asm.add(true, where, opc_ldc, new Integer(0));
+ asm.add(true, where, opc_ldc, 0);
asm.add(true, where, opc_goto, l2);
asm.add(l1);
- asm.add(true, where, opc_ldc, new Integer(1));
+ asm.add(true, where, opc_ldc, 1);
asm.add(l2);
} else {
left.codeValue(env, ctx, asm);
--- a/jdk/src/share/classes/sun/tools/tree/BitNotExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/BitNotExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -80,7 +80,7 @@
public void codeValue(Environment env, Context ctx, Assembler asm) {
right.codeValue(env, ctx, asm);
if (type.isType(TC_INT)) {
- asm.add(where, opc_ldc, new Integer(-1));
+ asm.add(where, opc_ldc, -1);
asm.add(where, opc_ixor);
} else {
asm.add(where, opc_ldc2_w, -1L);
--- a/jdk/src/share/classes/sun/tools/tree/BooleanExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/BooleanExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -52,7 +52,7 @@
* Get the value
*/
public Object getValue() {
- return new Integer(value ? 1 : 0);
+ return value ? 1 : 0;
}
/**
@@ -106,7 +106,7 @@
}
}
public void codeValue(Environment env, Context ctx, Assembler asm) {
- asm.add(where, opc_ldc, new Integer(value ? 1 : 0));
+ asm.add(where, opc_ldc, value ? 1 : 0);
}
/**
--- a/jdk/src/share/classes/sun/tools/tree/Expression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/Expression.java Wed Jul 05 19:50:57 2017 +0200
@@ -432,10 +432,10 @@
Label l2 = new Label();
codeBranch(env, ctx, asm, l1, true);
- asm.add(true, where, opc_ldc, new Integer(0));
+ asm.add(true, where, opc_ldc, 0);
asm.add(true, where, opc_goto, l2);
asm.add(l1);
- asm.add(true, where, opc_ldc, new Integer(1));
+ asm.add(true, where, opc_ldc, 1);
asm.add(l2);
} else {
throw new CompilerError("codeValue");
--- a/jdk/src/share/classes/sun/tools/tree/FinallyStatement.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/FinallyStatement.java Wed Jul 05 19:50:57 2017 +0200
@@ -287,8 +287,8 @@
// allocate space for the exception and return address
f1 = new LocalMember(where, thisClass, 0, Type.tObject, null);
f2 = new LocalMember(where, thisClass, 0, Type.tInt, null);
- num1 = new Integer(ctx.declare(env, f1));
- num2 = new Integer(ctx.declare(env, f2));
+ num1 = ctx.declare(env, f1);
+ num2 = ctx.declare(env, f2);
}
TryData td = new TryData();
--- a/jdk/src/share/classes/sun/tools/tree/IdentifierExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/IdentifierExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -452,7 +452,7 @@
}
void codeLoad(Environment env, Context ctx, Assembler asm) {
asm.add(where, opc_iload + type.getTypeCodeOffset(),
- new Integer(((LocalMember)field).number));
+ ((LocalMember)field).number);
}
void codeStore(Environment env, Context ctx, Assembler asm) {
LocalMember local = (LocalMember)field;
@@ -474,4 +474,4 @@
implementation.print(out);
}
}
-}
+}
\ No newline at end of file
--- a/jdk/src/share/classes/sun/tools/tree/IncDecExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/IncDecExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -112,22 +112,22 @@
private void codeIncDecOp(Assembler asm, boolean inc) {
switch (type.getTypeCode()) {
case TC_BYTE:
- asm.add(where, opc_ldc, new Integer(1));
+ asm.add(where, opc_ldc, 1);
asm.add(where, inc ? opc_iadd : opc_isub);
asm.add(where, opc_i2b);
break;
case TC_SHORT:
- asm.add(where, opc_ldc, new Integer(1));
+ asm.add(where, opc_ldc, 1);
asm.add(where, inc ? opc_iadd : opc_isub);
asm.add(where, opc_i2s);
break;
case TC_CHAR:
- asm.add(where, opc_ldc, new Integer(1));
+ asm.add(where, opc_ldc, 1);
asm.add(where, inc ? opc_iadd : opc_isub);
asm.add(where, opc_i2c);
break;
case TC_INT:
- asm.add(where, opc_ldc, new Integer(1));
+ asm.add(where, opc_ldc, 1);
asm.add(where, inc ? opc_iadd : opc_isub);
break;
case TC_LONG:
--- a/jdk/src/share/classes/sun/tools/tree/InlineNewInstanceExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/InlineNewInstanceExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -93,11 +93,11 @@
LocalMember v = (LocalMember)field.getArguments().elementAt(0);
CodeContext newctx = new CodeContext(ctx, this);
newctx.declare(env, v);
- asm.add(where, opc_astore, new Integer(v.number));
+ asm.add(where, opc_astore, v.number);
body.code(env, newctx, asm);
asm.add(newctx.breakLabel);
if (forValue) {
- asm.add(where, opc_aload, new Integer(v.number));
+ asm.add(where, opc_aload, v.number);
}
}
}
--- a/jdk/src/share/classes/sun/tools/tree/IntegerExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/IntegerExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -70,7 +70,7 @@
* Get the value
*/
public Object getValue() {
- return new Integer(value);
+ return value;
}
/**
@@ -91,6 +91,6 @@
* Code
*/
public void codeValue(Environment env, Context ctx, Assembler asm) {
- asm.add(where, opc_ldc, new Integer(value));
+ asm.add(where, opc_ldc, value);
}
}
--- a/jdk/src/share/classes/sun/tools/tree/MethodExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/MethodExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -857,7 +857,7 @@
right.code(env, ctx, asm);
}
} else if (right == null) {
- asm.add(where, opc_aload, new Integer(0));
+ asm.add(where, opc_aload, 0);
} else if (right.op == SUPER) {
// 'super.<method>(...)', 'super(...)', or '<expr>.super(...)'
/*****
--- a/jdk/src/share/classes/sun/tools/tree/NewArrayExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/NewArrayExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -133,21 +133,21 @@
switch (type.getElementType().getTypeCode()) {
case TC_BOOLEAN:
- asm.add(where, opc_newarray, new Integer(T_BOOLEAN)); break;
+ asm.add(where, opc_newarray, T_BOOLEAN); break;
case TC_BYTE:
- asm.add(where, opc_newarray, new Integer(T_BYTE)); break;
+ asm.add(where, opc_newarray, T_BYTE); break;
case TC_SHORT:
- asm.add(where, opc_newarray, new Integer(T_SHORT)); break;
+ asm.add(where, opc_newarray, T_SHORT); break;
case TC_CHAR:
- asm.add(where, opc_newarray, new Integer(T_CHAR)); break;
+ asm.add(where, opc_newarray, T_CHAR); break;
case TC_INT:
- asm.add(where, opc_newarray, new Integer(T_INT)); break;
+ asm.add(where, opc_newarray, T_INT); break;
case TC_LONG:
- asm.add(where, opc_newarray, new Integer(T_LONG)); break;
+ asm.add(where, opc_newarray, T_LONG); break;
case TC_FLOAT:
- asm.add(where, opc_newarray, new Integer(T_FLOAT)); break;
+ asm.add(where, opc_newarray, T_FLOAT); break;
case TC_DOUBLE:
- asm.add(where, opc_newarray, new Integer(T_DOUBLE)); break;
+ asm.add(where, opc_newarray, T_DOUBLE); break;
case TC_ARRAY:
asm.add(where, opc_anewarray, type.getElementType()); break;
case TC_CLASS:
--- a/jdk/src/share/classes/sun/tools/tree/NotExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/NotExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -139,7 +139,7 @@
*/
public void codeValue(Environment env, Context ctx, Assembler asm) {
right.codeValue(env, ctx, asm);
- asm.add(where, opc_ldc, new Integer(1));
+ asm.add(where, opc_ldc, 1);
asm.add(where, opc_ixor);
}
--- a/jdk/src/share/classes/sun/tools/tree/Statement.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/Statement.java Wed Jul 05 19:50:57 2017 +0200
@@ -249,7 +249,7 @@
// Save the return value in the register which should have
// been reserved.
LocalMember lf = ctx.getLocalField(idFinallyReturnValue);
- num = new Integer(lf.number);
+ num = lf.number;
asm.add(where, opc_istore + save.getTypeCodeOffset(), num);
} else {
// Pop the return value.
--- a/jdk/src/share/classes/sun/tools/tree/SynchronizedStatement.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/SynchronizedStatement.java Wed Jul 05 19:50:57 2017 +0200
@@ -125,8 +125,8 @@
LocalMember f1 = new LocalMember(where, clazz, 0, Type.tObject, null);
LocalMember f2 = new LocalMember(where, clazz, 0, Type.tInt, null);
- Integer num1 = new Integer(ctx.declare(env, f1));
- Integer num2 = new Integer(ctx.declare(env, f2));
+ Integer num1 = ctx.declare(env, f1);
+ Integer num2 = ctx.declare(env, f2);
Label endLabel = new Label();
--- a/jdk/src/share/classes/sun/tools/tree/ThisExpression.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/tools/tree/ThisExpression.java Wed Jul 05 19:50:57 2017 +0200
@@ -169,7 +169,7 @@
* Code
*/
public void codeValue(Environment env, Context ctx, Assembler asm) {
- asm.add(where, opc_aload, new Integer(field.number));
+ asm.add(where, opc_aload, field.number);
}
/**
--- a/jdk/src/share/classes/sun/util/locale/provider/DictionaryBasedBreakIterator.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/classes/sun/util/locale/provider/DictionaryBasedBreakIterator.java Wed Jul 05 19:50:57 2017 +0200
@@ -461,10 +461,10 @@
if ((currentBreakPositions.size() == 0 ||
currentBreakPositions.peek().intValue() != text.getIndex())
&& text.getIndex() != startPos) {
- currentBreakPositions.push(new Integer(text.getIndex()));
+ currentBreakPositions.push(text.getIndex());
}
getNext();
- currentBreakPositions.push(new Integer(text.getIndex()));
+ currentBreakPositions.push(text.getIndex());
}
}
--- a/jdk/src/share/javavm/export/jvm.h Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/javavm/export/jvm.h Wed Jul 05 19:50:57 2017 +0200
@@ -444,9 +444,6 @@
JNIEXPORT jboolean JNICALL
JVM_IsPrimitiveClass(JNIEnv *env, jclass cls);
-JNIEXPORT jclass JNICALL
-JVM_GetComponentType(JNIEnv *env, jclass cls);
-
JNIEXPORT jint JNICALL
JVM_GetClassModifiers(JNIEnv *env, jclass cls);
--- a/jdk/src/share/lib/security/java.security-linux Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/lib/security/java.security-linux Wed Jul 05 19:50:57 2017 +0200
@@ -209,8 +209,8 @@
org.jcp.xml.dsig.internal.,\
jdk.internal.,\
jdk.nashorn.internal.,\
- jdk.nashorn.tools.
-
+ jdk.nashorn.tools.,\
+ com.sun.activation.registries.
#
# List of comma-separated packages that start with or equal this string
@@ -255,8 +255,8 @@
org.jcp.xml.dsig.internal.,\
jdk.internal.,\
jdk.nashorn.internal.,\
- jdk.nashorn.tools.
-
+ jdk.nashorn.tools.,\
+ com.sun.activation.registries.
#
# Determines whether this properties file can be appended to
--- a/jdk/src/share/lib/security/java.security-macosx Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/lib/security/java.security-macosx Wed Jul 05 19:50:57 2017 +0200
@@ -211,6 +211,7 @@
jdk.internal.,\
jdk.nashorn.internal.,\
jdk.nashorn.tools.,\
+ com.sun.activation.registries.,\
apple.
#
@@ -257,6 +258,7 @@
jdk.internal.,\
jdk.nashorn.internal.,\
jdk.nashorn.tools.,\
+ com.sun.activation.registries.,\
apple.
#
--- a/jdk/src/share/lib/security/java.security-solaris Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/lib/security/java.security-solaris Wed Jul 05 19:50:57 2017 +0200
@@ -211,7 +211,8 @@
org.jcp.xml.dsig.internal.,\
jdk.internal.,\
jdk.nashorn.internal.,\
- jdk.nashorn.tools.
+ jdk.nashorn.tools.,\
+ com.sun.activation.registries.
#
# List of comma-separated packages that start with or equal this string
@@ -256,7 +257,8 @@
org.jcp.xml.dsig.internal.,\
jdk.internal.,\
jdk.nashorn.internal.,\
- jdk.nashorn.tools.
+ jdk.nashorn.tools.,\
+ com.sun.activation.registries.
#
# Determines whether this properties file can be appended to
--- a/jdk/src/share/lib/security/java.security-windows Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/lib/security/java.security-windows Wed Jul 05 19:50:57 2017 +0200
@@ -211,6 +211,7 @@
jdk.internal.,\
jdk.nashorn.internal.,\
jdk.nashorn.tools.,\
+ com.sun.activation.registries.,\
com.sun.java.accessibility.
#
@@ -257,6 +258,7 @@
jdk.internal.,\
jdk.nashorn.internal.,\
jdk.nashorn.tools.,\
+ com.sun.activation.registries.,\
com.sun.java.accessibility.
#
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/defines.h Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/defines.h Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -79,6 +79,7 @@
#define ERROR_RESOURCE "Cannot extract resource file"
#define ERROR_OVERFLOW "Internal buffer overflow"
#define ERROR_INTERNAL "Internal error"
+#define ERROR_INIT "cannot init class members"
#define LOGFILE_STDOUT "-"
#define LOGFILE_STDERR ""
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/jni.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/jni.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -56,6 +56,45 @@
#define THROW_IOE(x) JNU_ThrowIOException(env,x)
+#define CHECK_EXCEPTION_RETURN_VOID_THROW_IOE(CERVTI_exception, CERVTI_message) \
+ do { \
+ if ((env)->ExceptionOccurred()) { \
+ THROW_IOE(CERVTI_message); \
+ return; \
+ } \
+ if ((CERVTI_exception) == NULL) { \
+ THROW_IOE(CERVTI_message); \
+ return; \
+ } \
+ } while (JNI_FALSE)
+
+
+#define CHECK_EXCEPTION_RETURN_VALUE(CERL_exception, CERL_return_value) \
+ do { \
+ if ((env)->ExceptionOccurred()) { \
+ return CERL_return_value; \
+ } \
+ if ((CERL_exception) == NULL) { \
+ return CERL_return_value; \
+ } \
+ } while (JNI_FALSE)
+
+
+// If these useful macros aren't defined in jni_util.h then define them here
+#ifndef CHECK_NULL_RETURN
+#define CHECK_NULL_RETURN(x, y) \
+ do { \
+ if ((x) == NULL) return (y); \
+ } while (JNI_FALSE)
+#endif
+
+#ifndef CHECK_EXCEPTION_RETURN
+#define CHECK_EXCEPTION_RETURN(env, y) \
+ do { \
+ if ((*env)->ExceptionCheck(env)) return (y); \
+ } while (JNI_FALSE)
+#endif
+
static jlong read_input_via_jni(unpacker* self,
void* buf, jlong minlen, jlong maxlen);
@@ -92,9 +131,11 @@
vm->GetEnv(&envRaw, JNI_VERSION_1_1);
JNIEnv* env = (JNIEnv*) envRaw;
//fprintf(stderr, "get_unpacker() env=%p\n", env);
- if (env == null)
- return null;
+ CHECK_NULL_RETURN(env, NULL);
jobject pObj = env->CallStaticObjectMethod(NIclazz, currentInstMID);
+ // We should check upon the known non-null variable because here we want to check
+ // only for pending exceptions. If pObj is null we'll deal with it later.
+ CHECK_EXCEPTION_RETURN_VALUE(env, NULL);
//fprintf(stderr, "get_unpacker0() pObj=%p\n", pObj);
if (pObj != null) {
// Got pObj and env; now do it the easy way.
@@ -137,20 +178,20 @@
while( dbg != null) { sleep(10); }
#endif
NIclazz = (jclass) env->NewGlobalRef(clazz);
+
unpackerPtrFID = env->GetFieldID(clazz, "unpackerPtr", "J");
+ CHECK_EXCEPTION_RETURN_VOID_THROW_IOE(unpackerPtrFID, ERROR_INIT);
+
currentInstMID = env->GetStaticMethodID(clazz, "currentInstance",
"()Ljava/lang/Object;");
+ CHECK_EXCEPTION_RETURN_VOID_THROW_IOE(currentInstMID, ERROR_INIT);
+
readInputMID = env->GetMethodID(clazz, "readInputFn",
"(Ljava/nio/ByteBuffer;J)J");
- getUnpackerPtrMID = env->GetMethodID(clazz, "getUnpackerPtr", "()J");
+ CHECK_EXCEPTION_RETURN_VOID_THROW_IOE(readInputMID, ERROR_INIT);
- if (unpackerPtrFID == null ||
- currentInstMID == null ||
- readInputMID == null ||
- NIclazz == null ||
- getUnpackerPtrMID == null) {
- THROW_IOE("cannot init class members");
- }
+ getUnpackerPtrMID = env->GetMethodID(clazz, "getUnpackerPtr", "()J");
+ CHECK_EXCEPTION_RETURN_VOID_THROW_IOE(getUnpackerPtrMID, ERROR_INIT);
}
JNIEXPORT jlong JNICALL
@@ -160,9 +201,7 @@
// valid object pointers and env is intact, if not now is good time to bail.
unpacker* uPtr = get_unpacker();
//fprintf(stderr, "start(%p) uPtr=%p initializing\n", pObj, uPtr);
- if (uPtr == null) {
- return -1;
- }
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, -1);
// redirect our io to the default log file or whatever.
uPtr->redirect_stdio();
@@ -200,6 +239,7 @@
jobjectArray pParts) {
unpacker* uPtr = get_unpacker(env, pObj);
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, false);
unpacker::file* filep = uPtr->get_next_file();
if (uPtr->aborting()) {
@@ -207,32 +247,38 @@
return false;
}
- if (filep == null) {
- return false; // end of the sequence
- }
+ CHECK_NULL_RETURN(filep, false);
assert(filep == &uPtr->cur_file);
int pidx = 0, iidx = 0;
jintArray pIntParts = (jintArray) env->GetObjectArrayElement(pParts, pidx++);
+ CHECK_EXCEPTION_RETURN_VALUE(pIntParts, false);
jint* intParts = env->GetIntArrayElements(pIntParts, null);
intParts[iidx++] = (jint)( (julong)filep->size >> 32 );
intParts[iidx++] = (jint)( (julong)filep->size >> 0 );
intParts[iidx++] = filep->modtime;
intParts[iidx++] = filep->deflate_hint() ? 1 : 0;
env->ReleaseIntArrayElements(pIntParts, intParts, JNI_COMMIT);
-
- env->SetObjectArrayElement(pParts, pidx++, env->NewStringUTF(filep->name));
-
+ jstring filename = env->NewStringUTF(filep->name);
+ CHECK_EXCEPTION_RETURN_VALUE(filename, false);
+ env->SetObjectArrayElement(pParts, pidx++, filename);
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, false);
jobject pDataBuf = null;
- if (filep->data[0].len > 0)
+ if (filep->data[0].len > 0) {
pDataBuf = env->NewDirectByteBuffer(filep->data[0].ptr,
filep->data[0].len);
+ CHECK_EXCEPTION_RETURN_VALUE(pDataBuf, false);
+ }
env->SetObjectArrayElement(pParts, pidx++, pDataBuf);
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, false);
pDataBuf = null;
- if (filep->data[1].len > 0)
+ if (filep->data[1].len > 0) {
pDataBuf = env->NewDirectByteBuffer(filep->data[1].ptr,
filep->data[1].len);
+ CHECK_EXCEPTION_RETURN_VALUE(pDataBuf, false);
+ }
env->SetObjectArrayElement(pParts, pidx++, pDataBuf);
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, false);
return true;
}
@@ -241,6 +287,7 @@
JNIEXPORT jobject JNICALL
Java_com_sun_java_util_jar_pack_NativeUnpack_getUnusedInput(JNIEnv *env, jobject pObj) {
unpacker* uPtr = get_unpacker(env, pObj);
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, NULL);
unpacker::file* filep = &uPtr->cur_file;
if (uPtr->aborting()) {
@@ -263,7 +310,7 @@
JNIEXPORT jlong JNICALL
Java_com_sun_java_util_jar_pack_NativeUnpack_finish(JNIEnv *env, jobject pObj) {
unpacker* uPtr = get_unpacker(env, pObj, false);
- if (uPtr == null) return 0;
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, NULL);
size_t consumed = uPtr->input_consumed();
free_unpacker(env, pObj, uPtr);
return consumed;
@@ -274,7 +321,9 @@
jstring pProp, jstring pValue) {
unpacker* uPtr = get_unpacker(env, pObj);
const char* prop = env->GetStringUTFChars(pProp, JNI_FALSE);
+ CHECK_EXCEPTION_RETURN_VALUE(prop, false);
const char* value = env->GetStringUTFChars(pValue, JNI_FALSE);
+ CHECK_EXCEPTION_RETURN_VALUE(value, false);
jboolean retval = uPtr->set_option(prop, value);
env->ReleaseStringUTFChars(pProp, prop);
env->ReleaseStringUTFChars(pValue, value);
@@ -286,9 +335,11 @@
jstring pProp) {
unpacker* uPtr = get_unpacker(env, pObj);
+ CHECK_EXCEPTION_RETURN_VALUE(uPtr, NULL);
const char* prop = env->GetStringUTFChars(pProp, JNI_FALSE);
+ CHECK_EXCEPTION_RETURN_VALUE(prop, NULL);
const char* value = uPtr->get_option(prop);
+ CHECK_EXCEPTION_RETURN_VALUE(value, NULL);
env->ReleaseStringUTFChars(pProp, prop);
- if (value == null) return null;
return env->NewStringUTF(value);
}
--- a/jdk/src/share/native/java/lang/Class.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/java/lang/Class.c Wed Jul 05 19:50:57 2017 +0200
@@ -60,7 +60,6 @@
{"setSigners", "([" OBJ ")V", (void *)&JVM_SetClassSigners},
{"isArray", "()Z", (void *)&JVM_IsArrayClass},
{"isPrimitive", "()Z", (void *)&JVM_IsPrimitiveClass},
- {"getComponentType", "()" CLS, (void *)&JVM_GetComponentType},
{"getModifiers", "()I", (void *)&JVM_GetClassModifiers},
{"getDeclaredFields0","(Z)[" FLD, (void *)&JVM_GetClassDeclaredFields},
{"getDeclaredMethods0","(Z)[" MHD, (void *)&JVM_GetClassDeclaredMethods},
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c Wed Jul 05 19:50:57 2017 +0200
@@ -373,14 +373,14 @@
/* Parse the source image */
- if ((status = awt_parseImage(env, jsrc, &srcImageP, FALSE)) <= 0) {
+ if (awt_parseImage(env, jsrc, &srcImageP, FALSE) <= 0) {
/* Can't handle any custom images */
free(dkern);
return 0;
}
/* Parse the destination image */
- if ((status = awt_parseImage(env, jdst, &dstImageP, FALSE)) <= 0) {
+ if (awt_parseImage(env, jdst, &dstImageP, FALSE) <= 0) {
/* Can't handle any custom images */
awt_freeParsedImage(srcImageP, TRUE);
free(dkern);
@@ -627,7 +627,7 @@
}
/* Parse the source raster */
- if ((status = awt_parseRaster(env, jsrc, srcRasterP)) <= 0) {
+ if (awt_parseRaster(env, jsrc, srcRasterP) <= 0) {
/* Can't handle any custom rasters */
free(srcRasterP);
free(dstRasterP);
@@ -636,7 +636,7 @@
}
/* Parse the destination raster */
- if ((status = awt_parseRaster(env, jdst, dstRasterP)) <= 0) {
+ if (awt_parseRaster(env, jdst, dstRasterP) <= 0) {
/* Can't handle any custom images */
awt_freeParsedRaster(srcRasterP, TRUE);
free(dstRasterP);
@@ -839,13 +839,13 @@
(*env)->ReleasePrimitiveArrayCritical(env, jmatrix, matrix, JNI_ABORT);
/* Parse the source image */
- if ((status = awt_parseImage(env, jsrc, &srcImageP, FALSE)) <= 0) {
+ if (awt_parseImage(env, jsrc, &srcImageP, FALSE) <= 0) {
/* Can't handle any custom images */
return 0;
}
/* Parse the destination image */
- if ((status = awt_parseImage(env, jdst, &dstImageP, FALSE)) <= 0) {
+ if (awt_parseImage(env, jdst, &dstImageP, FALSE) <= 0) {
/* Can't handle any custom images */
awt_freeParsedImage(srcImageP, TRUE);
return 0;
@@ -1059,7 +1059,7 @@
(*env)->ReleasePrimitiveArrayCritical(env, jmatrix, matrix, JNI_ABORT);
/* Parse the source raster */
- if ((status = awt_parseRaster(env, jsrc, srcRasterP)) <= 0) {
+ if (awt_parseRaster(env, jsrc, srcRasterP) <= 0) {
/* Can't handle any custom rasters */
free(srcRasterP);
free(dstRasterP);
@@ -1067,7 +1067,7 @@
}
/* Parse the destination raster */
- if ((status = awt_parseRaster(env, jdst, dstRasterP)) <= 0) {
+ if (awt_parseRaster(env, jdst, dstRasterP) <= 0) {
/* Can't handle any custom images */
awt_freeParsedRaster(srcRasterP, TRUE);
free(dstRasterP);
@@ -1306,13 +1306,13 @@
if (s_timeIt) (*start_timer)(3600);
/* Parse the source image */
- if ((status = awt_parseImage(env, jsrc, &srcImageP, FALSE)) <= 0) {
+ if (awt_parseImage(env, jsrc, &srcImageP, FALSE) <= 0) {
/* Can't handle any custom images */
return 0;
}
/* Parse the destination image */
- if ((status = awt_parseImage(env, jdst, &dstImageP, FALSE)) <= 0) {
+ if (awt_parseImage(env, jdst, &dstImageP, FALSE) <= 0) {
/* Can't handle any custom images */
awt_freeParsedImage(srcImageP, TRUE);
return 0;
@@ -1554,14 +1554,14 @@
}
/* Parse the source raster - reject custom images */
- if ((status = awt_parseRaster(env, jsrc, srcRasterP)) <= 0) {
+ if (awt_parseRaster(env, jsrc, srcRasterP) <= 0) {
free(srcRasterP);
free(dstRasterP);
return 0;
}
/* Parse the destination image - reject custom images */
- if ((status = awt_parseRaster(env, jdst, dstRasterP)) <= 0) {
+ if (awt_parseRaster(env, jdst, dstRasterP) <= 0) {
awt_freeParsedRaster(srcRasterP, TRUE);
free(dstRasterP);
return 0;
--- a/jdk/src/share/native/sun/awt/splashscreen/java_awt_SplashScreen.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/java_awt_SplashScreen.c Wed Jul 05 19:50:57 2017 +0200
@@ -220,3 +220,18 @@
(*env)->ReleaseByteArrayElements(env, data, pBytes, JNI_ABORT);
return rc ? JNI_TRUE : JNI_FALSE;
}
+
+/*
+ * Class: java_awt_SplashScreen
+ * Method: _getScaleFactor
+ * Signature: (J)F
+ */
+JNIEXPORT jfloat JNICALL Java_java_awt_SplashScreen__1getScaleFactor
+(JNIEnv *env, jclass thisClass, jlong jsplash)
+{
+ Splash *splash = (Splash *) jlong_to_ptr(jsplash);
+ if (!splash) {
+ return 1;
+ }
+ return splash->scaleFactor;
+}
\ No newline at end of file
--- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_impl.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_impl.c Wed Jul 05 19:50:57 2017 +0200
@@ -59,6 +59,7 @@
memset(splash, 0, sizeof(Splash));
splash->currentFrame = -1;
+ splash->scaleFactor = 1;
initFormat(&splash->imageFormat, QUAD_RED_MASK, QUAD_GREEN_MASK,
QUAD_BLUE_MASK, QUAD_ALPHA_MASK);
SplashInitPlatform(splash);
@@ -101,6 +102,13 @@
SplashSetFileJarName(NULL, NULL);
}
+SPLASHEXPORT void
+SplashSetScaleFactor(float scaleFactor)
+{
+ Splash *splash = SplashGetInstance();
+ splash->scaleFactor = scaleFactor;
+}
+
void
SplashDone(Splash * splash)
{
--- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_impl.h Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_impl.h Wed Jul 05 19:50:57 2017 +0200
@@ -35,6 +35,9 @@
SPLASHEXPORT void SplashInit(void);
SPLASHEXPORT void SplashClose(void);
+SPLASHEXPORT void SplashSetScaleFactor(float);
+SPLASHEXPORT char* SplashGetScaledImageName(const char*, const char*, float*);
+
SPLASHEXPORT void
SplashSetFileJarName(const char* fileName, const char* jarName);
@@ -79,6 +82,7 @@
int fileNameLen;
char* jarName; /* stored in 16-bit unicode (jchars) */
int jarNameLen;
+ float scaleFactor;
#if defined(WITH_WIN32)
BOOL isLayered;
HWND hWnd;
@@ -115,6 +119,8 @@
unsigned SplashTime();
char* SplashConvertStringAlloc(const char* in, int *size);
+char* SplashGetScaledImageName(const char* jarName,
+ const char* fileName, float *scaleFactor);
void SplashLock(Splash * splash);
void SplashUnlock(Splash * splash);
@@ -138,6 +144,7 @@
void SplashUpdateScreenData(Splash * splash);
void SplashCleanup(Splash * splash);
+void SplashSetScaleFactor(float scaleFactor);
typedef struct SplashStream {
--- a/jdk/src/share/native/sun/font/DrawGlyphList.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/font/DrawGlyphList.c Wed Jul 05 19:50:57 2017 +0200
@@ -52,7 +52,8 @@
GlyphBlitVector* setupBlitVector(JNIEnv *env, jobject glyphlist) {
- int g, bytesNeeded;
+ int g;
+ size_t bytesNeeded;
jlong *imagePtrs;
jfloat* positions = NULL;
GlyphInfo *ginfo;
@@ -71,6 +72,9 @@
bytesNeeded = sizeof(GlyphBlitVector)+sizeof(ImageRef)*len;
gbv = (GlyphBlitVector*)malloc(bytesNeeded);
+ if (gbv == NULL) {
+ return NULL;
+ }
gbv->numGlyphs = len;
gbv->glyphs = (ImageRef*)((unsigned char*)gbv+sizeof(GlyphBlitVector));
@@ -479,7 +483,8 @@
*/
GlyphBlitVector* setupLCDBlitVector(JNIEnv *env, jobject glyphlist) {
- int g, bytesNeeded;
+ int g;
+ size_t bytesNeeded;
jlong *imagePtrs;
jfloat* positions = NULL;
GlyphInfo *ginfo;
@@ -500,6 +505,9 @@
bytesNeeded = sizeof(GlyphBlitVector)+sizeof(ImageRef)*len;
gbv = (GlyphBlitVector*)malloc(bytesNeeded);
+ if (gbv == NULL) {
+ return NULL;
+ }
gbv->numGlyphs = len;
gbv->glyphs = (ImageRef*)((unsigned char*)gbv+sizeof(GlyphBlitVector));
--- a/jdk/src/share/native/sun/font/freetypeScaler.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/font/freetypeScaler.c Wed Jul 05 19:50:57 2017 +0200
@@ -177,18 +177,10 @@
if (numBytes > FILEDATACACHESIZE) {
bBuffer = (*env)->NewDirectByteBuffer(env, destBuffer, numBytes);
if (bBuffer != NULL) {
- /* Loop until the read succeeds (or EOF).
- * This should improve robustness in the event of a problem in
- * the I/O system. If we find that we ever end up spinning here
- * we are going to have to do some serious work to recover.
- * Just returning without reading the data will cause a crash.
- */
- while (bread == 0) {
- bread = (*env)->CallIntMethod(env,
- scalerInfo->font2D,
- sunFontIDs.ttReadBlockMID,
- bBuffer, offset, numBytes);
- }
+ bread = (*env)->CallIntMethod(env,
+ scalerInfo->font2D,
+ sunFontIDs.ttReadBlockMID,
+ bBuffer, offset, numBytes);
return bread;
} else {
/* We probably hit bug bug 4845371. For reasons that
@@ -224,19 +216,10 @@
(offset + FILEDATACACHESIZE > scalerInfo->fileSize) ?
scalerInfo->fileSize - offset : FILEDATACACHESIZE;
bBuffer = scalerInfo->directBuffer;
- /* Loop until all the read succeeds (or EOF).
- * This should improve robustness in the event of a problem in
- * the I/O system. If we find that we ever end up spinning here
- * we are going to have to do some serious work to recover.
- * Just returning without reading the data will cause a crash.
- */
- while (bread == 0) {
- bread = (*env)->CallIntMethod(env, scalerInfo->font2D,
- sunFontIDs.ttReadBlockMID,
- bBuffer, offset,
- scalerInfo->fontDataLength);
- }
-
+ bread = (*env)->CallIntMethod(env, scalerInfo->font2D,
+ sunFontIDs.ttReadBlockMID,
+ bBuffer, offset,
+ scalerInfo->fontDataLength);
memcpy(destBuffer, scalerInfo->fontData, numBytes);
return numBytes;
}
--- a/jdk/src/share/native/sun/security/ec/ECC_JNI.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/share/native/sun/security/ec/ECC_JNI.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -66,22 +66,39 @@
free(ecparams);
}
+jbyteArray getEncodedBytes(JNIEnv *env, SECItem *hSECItem)
+{
+ SECItem *s = (SECItem *)hSECItem;
+
+ jbyteArray jEncodedBytes = env->NewByteArray(s->len);
+ if (jEncodedBytes == NULL) {
+ return NULL;
+ }
+ // Copy bytes from a native SECItem buffer to Java byte array
+ env->SetByteArrayRegion(jEncodedBytes, 0, s->len, (jbyte *)s->data);
+ if (env->ExceptionCheck()) { // should never happen
+ return NULL;
+ }
+ return jEncodedBytes;
+}
+
/*
* Class: sun_security_ec_ECKeyPairGenerator
* Method: generateECKeyPair
- * Signature: (I[B[B)[J
+ * Signature: (I[B[B)[[B
*/
-JNIEXPORT jlongArray
+JNIEXPORT jobjectArray
JNICALL Java_sun_security_ec_ECKeyPairGenerator_generateECKeyPair
(JNIEnv *env, jclass clazz, jint keySize, jbyteArray encodedParams, jbyteArray seed)
{
- ECPrivateKey *privKey = NULL; /* contains both public and private values */
+ ECPrivateKey *privKey = NULL; // contains both public and private values
ECParams *ecparams = NULL;
SECKEYECParams params_item;
jint jSeedLength;
jbyte* pSeedBuffer = NULL;
- jlongArray result = NULL;
- jlong* resultElements = NULL;
+ jobjectArray result = NULL;
+ jclass baCls = NULL;
+ jbyteArray jba;
// Initialize the ECParams struct
params_item.len = env->GetArrayLength(encodedParams);
@@ -111,71 +128,62 @@
}
jboolean isCopy;
- result = env->NewLongArray(2);
+ baCls = env->FindClass("[B");
+ if (baCls == NULL) {
+ goto cleanup;
+ }
+ result = env->NewObjectArray(2, baCls, NULL);
if (result == NULL) {
goto cleanup;
}
+ jba = getEncodedBytes(env, &(privKey->privateValue));
+ if (jba == NULL) {
+ result = NULL;
+ goto cleanup;
+ }
+ env->SetObjectArrayElement(result, 0, jba); // big integer
+ if (env->ExceptionCheck()) { // should never happen
+ result = NULL;
+ goto cleanup;
+ }
- resultElements = env->GetLongArrayElements(result, &isCopy);
- if (resultElements == NULL) {
+ jba = getEncodedBytes(env, &(privKey->publicValue));
+ if (jba == NULL) {
+ result = NULL;
goto cleanup;
}
-
- resultElements[0] = (jlong) &(privKey->privateValue); // private big integer
- resultElements[1] = (jlong) &(privKey->publicValue); // encoded ec point
-
- // If the array is a copy then we must write back our changes
- if (isCopy == JNI_TRUE) {
- env->ReleaseLongArrayElements(result, resultElements, 0);
+ env->SetObjectArrayElement(result, 1, jba); // encoded ec point
+ if (env->ExceptionCheck()) { // should never happen
+ result = NULL;
+ goto cleanup;
}
cleanup:
{
- if (params_item.data)
+ if (params_item.data) {
env->ReleaseByteArrayElements(encodedParams,
(jbyte *) params_item.data, JNI_ABORT);
-
- if (ecparams)
+ }
+ if (ecparams) {
FreeECParams(ecparams, true);
-
+ }
if (privKey) {
FreeECParams(&privKey->ecParams, false);
SECITEM_FreeItem(&privKey->version, B_FALSE);
- // Don't free privKey->privateValue and privKey->publicValue
+ SECITEM_FreeItem(&privKey->privateValue, B_FALSE);
+ SECITEM_FreeItem(&privKey->publicValue, B_FALSE);
+ free(privKey);
}
- if (pSeedBuffer)
+ if (pSeedBuffer) {
delete [] pSeedBuffer;
+ }
}
return result;
}
/*
- * Class: sun_security_ec_ECKeyPairGenerator
- * Method: getEncodedBytes
- * Signature: (J)[B
- */
-JNIEXPORT jbyteArray
-JNICALL Java_sun_security_ec_ECKeyPairGenerator_getEncodedBytes
- (JNIEnv *env, jclass clazz, jlong hSECItem)
-{
- SECItem *s = (SECItem *)hSECItem;
- jbyteArray jEncodedBytes = env->NewByteArray(s->len);
- if (jEncodedBytes == NULL) {
- return NULL;
- }
-
- // Copy bytes from a native SECItem buffer to Java byte array
- env->SetByteArrayRegion(jEncodedBytes, 0, s->len, (jbyte *)s->data);
-
- // Use B_FALSE to free only the SECItem->data
- SECITEM_FreeItem(s, B_FALSE);
-
- return jEncodedBytes;
-}
-
-/*
* Class: sun_security_ec_ECDSASignature
* Method: signDigest
* Signature: ([B[B[B[B)[B
@@ -258,21 +266,26 @@
cleanup:
{
- if (params_item.data)
+ if (params_item.data) {
env->ReleaseByteArrayElements(encodedParams,
(jbyte *) params_item.data, JNI_ABORT);
-
- if (pDigestBuffer)
+ }
+ if (privKey.privateValue.data) {
+ env->ReleaseByteArrayElements(privateKey,
+ (jbyte *) privKey.privateValue.data, JNI_ABORT);
+ }
+ if (pDigestBuffer) {
delete [] pDigestBuffer;
-
- if (pSignedDigestBuffer)
+ }
+ if (pSignedDigestBuffer) {
delete [] pSignedDigestBuffer;
-
- if (pSeedBuffer)
+ }
+ if (pSeedBuffer) {
delete [] pSeedBuffer;
-
- if (ecparams)
+ }
+ if (ecparams) {
FreeECParams(ecparams, true);
+ }
}
return jSignedDigest;
--- a/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java Wed Jul 05 19:50:57 2017 +0200
@@ -45,6 +45,10 @@
return false;
}
+ public static boolean isXPStyleEnabled() {
+ return false;
+ }
+
public static void paintBackground(int[] buffer, String widget,
int part, int state, int x, int y, int w, int h, int stride) {
}
--- a/jdk/src/solaris/classes/sun/font/FcFontConfiguration.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/classes/sun/font/FcFontConfiguration.java Wed Jul 05 19:50:57 2017 +0200
@@ -170,7 +170,7 @@
@Override
protected void initReorderMap() {
- reorderMap = new HashMap();
+ reorderMap = new HashMap<>();
}
@Override
--- a/jdk/src/solaris/classes/sun/font/XMap.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/classes/sun/font/XMap.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -37,7 +37,7 @@
class XMap {
- private static HashMap xMappers = new HashMap();
+ private static HashMap<String, XMap> xMappers = new HashMap<>();
/* ConvertedGlyphs has unicode code points as indexes and values
* are platform-encoded multi-bytes chars packed into java chars.
@@ -49,7 +49,7 @@
char[] convertedGlyphs;
static synchronized XMap getXMapper(String encoding) {
- XMap mapper = (XMap)xMappers.get(encoding);
+ XMap mapper = xMappers.get(encoding);
if (mapper == null) {
mapper = getXMapperInternal(encoding);
xMappers.put(encoding, mapper);
--- a/jdk/src/solaris/classes/sun/font/XRGlyphCache.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/classes/sun/font/XRGlyphCache.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -190,20 +190,23 @@
for (XRGlyphCacheEntry cacheEntry : glyphList) {
if (cacheEntry.isGrayscale(containsLCDGlyphs)) {
if (grayGlyphs == null) {
- grayGlyphs = new ArrayList<XRGlyphCacheEntry>(glyphList.size());
+ grayGlyphs = new ArrayList<>(glyphList.size());
}
cacheEntry.setGlyphSet(grayGlyphSet);
grayGlyphs.add(cacheEntry);
} else {
if (lcdGlyphs == null) {
- lcdGlyphs = new ArrayList<XRGlyphCacheEntry>(glyphList.size());
+ lcdGlyphs = new ArrayList<>(glyphList.size());
}
cacheEntry.setGlyphSet(lcdGlyphSet);
lcdGlyphs.add(cacheEntry);
}
}
-
- return new List[] { grayGlyphs, lcdGlyphs };
+ // Arrays and generics don't play well together
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ List<XRGlyphCacheEntry>[] tmp =
+ (List<XRGlyphCacheEntry>[]) (new List[] { grayGlyphs, lcdGlyphs });
+ return tmp;
}
/**
--- a/jdk/src/solaris/classes/sun/print/CUPSPrinter.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/classes/sun/print/CUPSPrinter.java Wed Jul 05 19:50:57 2017 +0200
@@ -140,6 +140,9 @@
return cupsCustomMediaSNames;
}
+ public int getDefaultMediaIndex() {
+ return ((pageSizes.length >1) ? (int)(pageSizes[pageSizes.length -1]) : 0);
+ }
/**
* Returns array of MediaPrintableArea derived from PPD.
@@ -201,8 +204,15 @@
// add this new custom msn to MediaSize array
if ((width > 0.0) && (length > 0.0)) {
+ try {
new MediaSize(width, length,
Size2DSyntax.INCH, msn);
+ } catch (IllegalArgumentException e) {
+ /* PDF printer in Linux for Ledger paper causes
+ "IllegalArgumentException: X dimension > Y dimension".
+ We rotate based on IPP spec. */
+ new MediaSize(length, width, Size2DSyntax.INCH, msn);
+ }
}
}
--- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java Wed Jul 05 19:50:57 2017 +0200
@@ -413,6 +413,7 @@
mediaSizeNames = cps.getMediaSizeNames();
mediaTrays = cps.getMediaTrays();
customMediaSizeNames = cps.getCustomMediaSizeNames();
+ defaultMediaIndex = cps.getDefaultMediaIndex();
urlConnection.disconnect();
init = true;
return;
@@ -1427,7 +1428,9 @@
return JobSheets.STANDARD;
}
} else if (category == Media.class) {
- defaultMediaIndex = 0;
+ if (defaultMediaIndex == -1) {
+ defaultMediaIndex = 0;
+ }
if (mediaSizeNames.length == 0) {
String defaultCountry = Locale.getDefault().getCountry();
if (defaultCountry != null &&
@@ -1443,17 +1446,7 @@
if (attribClass != null) {
String name = attribClass.getStringValue();
if (isCupsPrinter) {
- for (int i=0; i< customMediaSizeNames.length; i++) {
- //REMIND: get default from PPD. In native _getMedia,
- // move default (ppd_option_t->defchoice) to index 0.
- // In the meantime, use indexOf because PPD name
- // may be different from the IPP attribute name.
- if (customMediaSizeNames[i].toString().indexOf(name)
- != -1) {
- defaultMediaIndex = i;
- return mediaSizeNames[defaultMediaIndex];
- }
- }
+ return mediaSizeNames[defaultMediaIndex];
} else {
for (int i=0; i< mediaSizeNames.length; i++) {
if (mediaSizeNames[i].toString().indexOf(name) != -1) {
--- a/jdk/src/solaris/native/sun/awt/CUPSfuncs.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/CUPSfuncs.c Wed Jul 05 19:50:57 2017 +0200
@@ -349,7 +349,8 @@
// create array of dimensions - (num_choices * 6)
//to cover length & height
DPRINTF( "CUPSfuncs::option->num_choices %d\n", option->num_choices)
- sizeArray = (*env)->NewFloatArray(env, option->num_choices*6);
+ // +1 is for storing the default media index
+ sizeArray = (*env)->NewFloatArray(env, option->num_choices*6+1);
if (sizeArray == NULL) {
unlink(filename);
j2d_ppdClose(ppd);
@@ -369,6 +370,10 @@
}
for (i = 0; i<option->num_choices; i++) {
choice = (option->choices)+i;
+ // get the index of the default page
+ if (!strcmp(choice->choice, option->defchoice)) {
+ dims[option->num_choices*6] = (float)i;
+ }
size = j2d_ppdPageSize(ppd, choice->choice);
if (size != NULL) {
// paper width and height
--- a/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c Wed Jul 05 19:50:57 2017 +0200
@@ -794,3 +794,11 @@
SplashReconfigure(Splash * splash) {
sendctl(splash, SPLASHCTL_RECONFIGURE);
}
+
+SPLASHEXPORT char*
+SplashGetScaledImageName(const char* jarName, const char* fileName,
+ float *scaleFactor)
+{
+ *scaleFactor = 1;
+ return NULL;
+}
--- a/jdk/src/windows/bin/java_md.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/bin/java_md.c Wed Jul 05 19:50:57 2017 +0200
@@ -1306,6 +1306,14 @@
/* save path length */
jrePathLen = JLI_StrLen(libraryPath);
+ if (jrePathLen + JLI_StrLen("\\bin\\verify.dll") >= MAXPATHLEN) {
+ /* jre path is too long, the library path will not fit there;
+ * report and abort preloading
+ */
+ JLI_ReportErrorMessage(JRE_ERROR11);
+ break;
+ }
+
/* load msvcrt 1st */
LoadMSVCRT();
--- a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java Wed Jul 05 19:50:57 2017 +0200
@@ -583,11 +583,18 @@
// Needs to be accessible to Win32ShellFolderManager2
static String getFileSystemPath(final int csidl) throws IOException, InterruptedException {
- return invoke(new Callable<String>() {
+ String path = invoke(new Callable<String>() {
public String call() throws IOException {
return getFileSystemPath0(csidl);
}
}, IOException.class);
+ if (path != null) {
+ SecurityManager security = System.getSecurityManager();
+ if (security != null) {
+ security.checkRead(path);
+ }
+ }
+ return path;
}
// NOTE: this method uses COM and must be called on the 'COM thread'. See ComInvoker for the details
--- a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java Wed Jul 05 19:50:57 2017 +0200
@@ -136,6 +136,8 @@
if (desktop == null) {
try {
desktop = new Win32ShellFolder2(DESKTOP);
+ } catch (SecurityException e) {
+ // Ignore error
} catch (IOException e) {
// Ignore error
} catch (InterruptedException e) {
@@ -149,6 +151,8 @@
if (drives == null) {
try {
drives = new Win32ShellFolder2(DRIVES);
+ } catch (SecurityException e) {
+ // Ignore error
} catch (IOException e) {
// Ignore error
} catch (InterruptedException e) {
@@ -165,6 +169,8 @@
if (path != null) {
recent = createShellFolder(getDesktop(), new File(path));
}
+ } catch (SecurityException e) {
+ // Ignore error
} catch (InterruptedException e) {
// Ignore error
} catch (IOException e) {
@@ -178,6 +184,8 @@
if (network == null) {
try {
network = new Win32ShellFolder2(NETWORK);
+ } catch (SecurityException e) {
+ // Ignore error
} catch (IOException e) {
// Ignore error
} catch (InterruptedException e) {
@@ -201,6 +209,8 @@
personal.setIsPersonal();
}
}
+ } catch (SecurityException e) {
+ // Ignore error
} catch (InterruptedException e) {
// Ignore error
} catch (IOException e) {
--- a/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java Wed Jul 05 19:50:57 2017 +0200
@@ -60,22 +60,22 @@
new ReentrantReadWriteLock();
private static final Lock readLock = readWriteLock.readLock();
private static final Lock writeLock = readWriteLock.writeLock();
+ private static volatile boolean valid = false;
+
+ static volatile boolean xpStyleEnabled;
static void flush() {
- writeLock.lock();
- try {
- // Close old themes.
- for (Long value : widgetToTheme.values()) {
- closeTheme(value.longValue());
- }
- widgetToTheme.clear();
- } finally {
- writeLock.unlock();
- }
+ // Could be called on Toolkit thread, so do not try to acquire locks
+ // to avoid deadlock with theme initialization
+ valid = false;
}
public static native boolean isThemed();
+ public static boolean isXPStyleEnabled() {
+ return xpStyleEnabled;
+ }
+
// this should be called only with writeLock held
private static Long getThemeImpl(String widget) {
Long theme = widgetToTheme.get(widget);
@@ -98,6 +98,24 @@
// returns theme value
// this method should be invoked with readLock locked
private static Long getTheme(String widget) {
+ if (!valid) {
+ readLock.unlock();
+ writeLock.lock();
+ try {
+ if (!valid) {
+ // Close old themes.
+ for (Long value : widgetToTheme.values()) {
+ closeTheme(value);
+ }
+ widgetToTheme.clear();
+ valid = true;
+ }
+ } finally {
+ readLock.lock();
+ writeLock.unlock();
+ }
+ }
+
// mostly copied from the javadoc for ReentrantReadWriteLock
Long theme = widgetToTheme.get(widget);
if (theme == null) {
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java Wed Jul 05 19:50:57 2017 +0200
@@ -36,8 +36,10 @@
import java.beans.PropertyChangeListener;
import java.security.AccessController;
import java.security.PrivilegedAction;
+import sun.awt.AppContext;
import sun.awt.AWTAutoShutdown;
import sun.awt.AWTPermissions;
+import sun.awt.AppContext;
import sun.awt.LightweightFrame;
import sun.awt.SunToolkit;
import sun.awt.util.ThreadGroupUtils;
@@ -72,6 +74,9 @@
private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WToolkit");
+ // Desktop property which specifies whether XP visual styles are in effect
+ public static final String XPSTYLE_THEME_ACTIVE = "win.xpstyle.themeActive";
+
static GraphicsConfiguration config;
// System clipboard.
@@ -895,7 +900,7 @@
private synchronized void lazilyInitWProps() {
if (wprops == null) {
wprops = new WDesktopProperties(this);
- updateProperties();
+ updateProperties(wprops.getProperties());
}
}
@@ -930,21 +935,36 @@
* Windows doesn't always send WM_SETTINGCHANGE when it should.
*/
private void windowsSettingChange() {
- EventQueue.invokeLater(new Runnable() {
- @Override
- public void run() {
- updateProperties();
- }
- });
- }
-
- private synchronized void updateProperties() {
- if (null == wprops) {
- // wprops has not been initialized, so we have nothing to update
+ // JDK-8039383: Have to update the value of XPSTYLE_THEME_ACTIVE property
+ // as soon as possible to prevent NPE and other errors because theme data
+ // has become unavailable.
+ final Map<String, Object> props = getWProps();
+ if (props == null) {
+ // props has not been initialized, so we have nothing to update
return;
}
- Map<String, Object> props = wprops.getProperties();
+ updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE));
+
+ if (AppContext.getAppContext() == null) {
+ // We cannot post the update to any EventQueue. Listeners will
+ // be called on EDTs by DesktopPropertyChangeSupport
+ updateProperties(props);
+ } else {
+ // Cannot update on Toolkit thread.
+ // DesktopPropertyChangeSupport will call listeners on Toolkit
+ // thread if it has AppContext (standalone mode)
+ EventQueue.invokeLater(() -> updateProperties(props));
+ }
+ }
+
+ private synchronized void updateProperties(final Map<String, Object> props) {
+ if (null == props) {
+ return;
+ }
+
+ updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE));
+
for (String propName : props.keySet()) {
Object val = props.get(propName);
if (log.isLoggable(PlatformLogger.Level.FINER)) {
@@ -954,6 +974,14 @@
}
}
+ private synchronized Map<String, Object> getWProps() {
+ return (wprops != null) ? wprops.getProperties() : null;
+ }
+
+ private void updateXPStyleEnabled(final Object dskProp) {
+ ThemeReader.xpStyleEnabled = Boolean.TRUE.equals(dskProp);
+ }
+
@Override
public synchronized void addPropertyChangeListener(String name, PropertyChangeListener pcl) {
if (name == null) {
--- a/jdk/src/windows/classes/sun/awt/windows/WingDings.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WingDings.java Wed Jul 05 19:50:57 2017 +0200
@@ -29,7 +29,7 @@
import java.nio.CharBuffer;
import java.nio.charset.*;
-final class WingDings extends Charset {
+public final class WingDings extends Charset {
public WingDings () {
super("WingDings", null);
}
--- a/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c Wed Jul 05 19:50:57 2017 +0200
@@ -467,7 +467,7 @@
*/
JNIEXPORT void JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_socketSetIntOption
(JNIEnv *env, jclass clazz, jint fd , jint cmd, jint value) {
- int level, opt;
+ int level = 0, opt = 0;
if (NET_MapSocketOption(cmd, &level, &opt) < 0) {
JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
@@ -487,7 +487,7 @@
*/
JNIEXPORT jint JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_socketGetIntOption
(JNIEnv *env, jclass clazz, jint fd, jint cmd) {
- int level, opt, result=0;
+ int level = 0, opt = 0, result=0;
int result_len = sizeof(result);
if (NET_MapSocketOption(cmd, &level, &opt) < 0) {
--- a/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c Wed Jul 05 19:50:57 2017 +0200
@@ -367,8 +367,8 @@
JNIEXPORT void JNICALL Java_java_net_DualStackPlainSocketImpl_setIntOption
(JNIEnv *env, jclass clazz, jint fd, jint cmd, jint value) {
- int level, opt;
- struct linger linger;
+ int level = 0, opt = 0;
+ struct linger linger = {0, 0};
char *parg;
int arglen;
@@ -407,9 +407,9 @@
JNIEXPORT jint JNICALL Java_java_net_DualStackPlainSocketImpl_getIntOption
(JNIEnv *env, jclass clazz, jint fd, jint cmd) {
- int level, opt;
+ int level = 0, opt = 0;
int result=0;
- struct linger linger;
+ struct linger linger = {0, 0};
char *arg;
int arglen;
--- a/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c Wed Jul 05 19:50:57 2017 +0200
@@ -335,6 +335,8 @@
SOCKETADDRESS rmtaddr;
int addrlen = sizeof(rmtaddr);
+ memset((char *)&rmtaddr, 0, sizeof(rmtaddr));
+
/*
* A no-op if this OS doesn't support it.
*/
@@ -431,9 +433,11 @@
int ipv6_supported = ipv6_available();
SOCKETADDRESS lcladdr;
- int lcladdrlen;
+ int lcladdrlen = sizeof(lcladdr);
int address;
+ memset((char *)&lcladdr, 0, sizeof(lcladdr));
+
family = getInetAddress_family(env, addressObj);
if (family == IPv6 && !ipv6_supported) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
@@ -614,7 +618,7 @@
}
fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
- memset(&addr, 0, len);
+ memset((char *)&addr, 0, len);
connect(fd, (struct sockaddr *)&addr, len);
/*
@@ -622,7 +626,7 @@
* to disable ICMP port unreachable handling here.
*/
if (xp_or_later) {
- DWORD x1, x2; /* ignored result codes */
+ DWORD x1 = 0, x2 = 0; /* ignored result codes */
int t = FALSE;
WSAIoctl(fd,SIO_UDP_CONNRESET,&t,sizeof(t),&x1,sizeof(x1),&x2,0,0);
}
@@ -652,8 +656,9 @@
SOCKETADDRESS rmtaddr;
SOCKETADDRESS *addrp = &rmtaddr;
- int addrlen;
+ int addrlen = 0;
+ memset((char *)&rmtaddr, 0, sizeof(rmtaddr));
if (IS_NULL(packet)) {
JNU_ThrowNullPointerException(env, "null packet");
@@ -1412,7 +1417,7 @@
} else if (n < 0) {
NET_ThrowCurrent(env, "Datagram receive failed");
} else {
- int port;
+ int port = 0;
jobject packetAddress;
/*
@@ -1791,11 +1796,11 @@
jint opt,jobject value) {
int fd=-1, fd1=-1;
- int levelv4, levelv6, optnamev4, optnamev6, optlen;
+ int levelv4 = 0, levelv6 = 0, optnamev4 = 0, optnamev6 = 0, optlen = 0;
union {
int i;
char c;
- } optval;
+ } optval = { 0 };
int ipv6_supported = ipv6_available();
fd = getFD(env, this);
@@ -2162,7 +2167,7 @@
int level, optname, optlen;
union {
int i;
- } optval;
+ } optval = {0};
int ipv6_supported = ipv6_available();
fd = getFD(env, this);
@@ -2413,12 +2418,15 @@
struct ipv6_mreq mname6;
struct in_addr in;
- DWORD ifindex;
+ DWORD ifindex = 0;
int len, family;
int ipv6_supported = ipv6_available();
int cmd ;
+ memset((char *)&in, 0, sizeof(in));
+ memset((char *)&name, 0, sizeof(name));
+
if (IS_NULL(fdObj) && IS_NULL(fd1Obj)) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
"Socket closed");
--- a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c Wed Jul 05 19:50:57 2017 +0200
@@ -207,6 +207,7 @@
/* The result of the connection */
int connect_res;
+ memset((char *)&him, 0, sizeof(him));
if (!IS_NULL(fdObj)) {
fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
@@ -399,7 +400,7 @@
/* fdObj is the FileDescriptor field on this */
jobject fdObj, fd1Obj;
/* fd is an int field on fdObj */
- int fd, fd1, len;
+ int fd, fd1, len = 0;
int ipv6_supported = ipv6_available();
/* family is an int field of iaObj */
@@ -837,12 +838,13 @@
jint cmd, jboolean on,
jobject value) {
int fd, fd1;
- int level, optname, optlen;
+ int level = 0, optname = 0, optlen = 0;
union {
int i;
struct linger ling;
} optval;
+ memset((char *)&optval, 0, sizeof(optval));
/*
* Get SOCKET and check that it hasn't been closed
*/
@@ -1003,17 +1005,17 @@
jint opt, jobject iaContainerObj) {
int fd, fd1;
- int level, optname, optlen;
+ int level = 0, optname = 0, optlen = 0;
union {
int i;
struct linger ling;
} optval;
-
/*
* Get SOCKET and check it hasn't been closed
*/
fd = getFD(env, this);
fd1 = getFD1(env, this);
+ memset((char *)&optval, 0, sizeof(optval));
if (fd < 0 && fd1 < 0) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed");
@@ -1037,6 +1039,7 @@
jfieldID iaFieldID;
len = sizeof(him);
+ memset((char *)&him, 0, len);
if (fd == -1) {
/* must be an IPV6 only socket. Case where both sockets are != -1
--- a/jdk/src/windows/native/java/net/net_util_md.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/java/net/net_util_md.c Wed Jul 05 19:50:57 2017 +0200
@@ -386,8 +386,8 @@
NET_SetSockOpt(int s, int level, int optname, const void *optval,
int optlen)
{
- int rv;
- int parg;
+ int rv = 0;
+ int parg = 0;
int plen = sizeof(parg);
if (level == IPPROTO_IP && optname == IP_TOS) {
@@ -478,7 +478,7 @@
* Sets SO_ECLUSIVEADDRUSE if SO_REUSEADDR is not already set.
*/
void setExclusiveBind(int fd) {
- int parg;
+ int parg = 0;
int plen = sizeof(parg);
int rv = 0;
rv = NET_GetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&parg, &plen);
@@ -499,7 +499,7 @@
JNIEXPORT int JNICALL
NET_Bind(int s, struct sockaddr *him, int len)
{
- int rv;
+ int rv = 0;
rv = bind(s, him, len);
if (rv == SOCKET_ERROR) {
@@ -529,8 +529,8 @@
JNIEXPORT int JNICALL
NET_SocketClose(int fd) {
- struct linger l;
- int ret;
+ struct linger l = {0, 0};
+ int ret = 0;
int len = sizeof (l);
if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, &len) == 0) {
if (l.l_onoff == 0) {
--- a/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c Wed Jul 05 19:50:57 2017 +0200
@@ -563,3 +563,11 @@
{
PostMessage(splash->hWnd, WM_SPLASHRECONFIGURE, 0, 0);
}
+
+SPLASHEXPORT char*
+SplashGetScaledImageName(const char* jarName, const char* fileName,
+ float *scaleFactor)
+{
+ *scaleFactor = 1;
+ return NULL;
+}
--- a/jdk/src/windows/native/sun/windows/awt_Component.cpp Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Component.cpp Wed Jul 05 19:50:57 2017 +0200
@@ -492,7 +492,12 @@
* member is referred in the GetClassName method of AwtLabel class.
* So m_peerObject member must be set here.
*/
- m_peerObject = env->NewGlobalRef(peer);
+ if (m_peerObject == NULL) {
+ m_peerObject = env->NewGlobalRef(peer);
+ } else {
+ assert(env->IsSameObject(m_peerObject, peer));
+ }
+
RegisterClass();
jobject target = env->GetObjectField(peer, AwtObject::targetID);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Focus/SortingFPT/JDK8048887.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ @test
+ @bug 8048887
+ @summary Tests SortingFTP for an exception caused by the tim-sort algo.
+ @author anton.tarasov: area=awt.focus
+ @run main JDK8040632
+*/
+
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
+import java.awt.Dimension;
+import java.awt.Color;
+import java.awt.GridBagLayout;
+import java.awt.GridBagConstraints;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class JDK8048887 {
+
+ static volatile boolean passed = true;
+
+ public static void main(String[] args) {
+ JDK8048887 app = new JDK8048887();
+ app.start();
+ }
+
+ public void start() {
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ SwingUtilities.invokeLater(() -> {
+ // Catch the original exception which sounds like:
+ // java.lang.IllegalArgumentException: Comparison method violates its general contract!
+ Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+ public void uncaughtException(Thread t, Throwable e) {
+ e.printStackTrace();
+ if (e instanceof IllegalArgumentException) {
+ passed = false;
+ latch.countDown();
+ }
+ }
+ });
+
+ TestDialog d = new TestDialog();
+ // It's expected that the dialog is focused on start.
+ // The listener is called after the FTP completes processing and the bug is reproduced or not.
+ d.addWindowFocusListener(new WindowAdapter() {
+ public void windowGainedFocus(WindowEvent e) {
+ latch.countDown();
+ }
+ });
+ d.setVisible(true);
+ });
+
+ try {
+ latch.await(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ if (passed)
+ System.out.println("Test passed.");
+ else
+ throw new RuntimeException("Test failed!");
+ }
+}
+
+class TestDialog extends JFrame {
+
+ // The layout of the components reproduces the transitivity issue
+ // with SortingFocusTraversalPolicy relying on the tim-sort algo.
+
+ private static int[] Xs = new int[] {71, 23, 62, 4, 79, 39, 34, 9, 84, 58, 30, 34, 38, 15, 69, 10, 44, 95, 70, 54,
+ 44, 62, 77, 64, 70, 83, 31, 48, 96, 54, 40, 3, 60, 58, 3, 20, 94, 54, 26, 19, 48, 47, 12, 70, 86, 43, 71, 97, 19,
+ 69, 90, 22, 43, 76, 10, 60, 29, 49, 9, 9, 15, 73, 85, 80, 81, 35, 87, 43, 17, 57, 38, 44, 29, 86, 96, 15, 57, 26,
+ 27, 78, 26, 87, 43, 6, 4, 16, 57, 99, 32, 86, 96, 5, 50, 69, 12, 4, 36, 84, 71, 60, 22, 46, 11, 44, 87, 3, 23, 14,
+ 43, 25, 32, 44, 11, 18, 77, 2, 51, 87, 88, 53, 69, 37, 14, 10, 25, 73, 39, 33, 91, 51, 96, 9, 74, 66, 70, 42, 72,
+ 7, 82, 40, 91, 33, 83, 54, 33, 50, 83, 1, 81, 32, 66, 11, 75, 56, 53, 45, 1, 69, 46, 31, 79, 58, 12, 20, 92, 49,
+ 50, 90, 33, 8, 43, 93, 72, 78, 9, 56, 84, 60, 30, 39, 33, 88, 84, 56, 49, 47, 4, 90, 57, 6, 23, 96, 37, 88, 22, 79,
+ 35, 80, 45, 55};
+
+ public TestDialog() {
+ JPanel panel = new JPanel(new GridBagLayout());
+ GridBagConstraints gbc = new GridBagConstraints();
+ for (int i=0; i < Xs.length; i++) {
+ gbc.gridx = Xs[i];
+ gbc.gridy = 100 - gbc.gridx;
+ panel.add(new MyComponent(), gbc);
+ }
+ getRootPane().getContentPane().add(panel);
+ pack();
+ }
+
+ public static class MyComponent extends JPanel {
+ private final static Dimension SIZE = new Dimension(1,1);
+
+ public MyComponent() {
+ setBackground(Color.BLACK);
+ setOpaque(true);
+ }
+
+ @Override
+ public Dimension getPreferredSize() {
+ return SIZE;
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Frame/DisposeParentGC/DisposeParentGC.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+import java.util.ArrayList;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary Display a dialog with a parent, the dialog contains all awt components
+ * added to it & each components are setted with different cursors types.
+ * Dispose the parent & collect GC. Garbage collection should happen
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main/othervm -Xmx20m DisposeParentGC
+ */
+
+public class DisposeParentGC {
+ Frame parentFrame;
+ ExtendedRobot robot;
+
+ ArrayList<PhantomReference<Dialog>> refs = new ArrayList<PhantomReference<Dialog>>();
+ ReferenceQueue<Dialog> que = new ReferenceQueue<>();
+
+ public static void main(String []args) throws Exception {
+ new DisposeParentGC().doTest();
+ }
+
+ DisposeParentGC() throws Exception {
+ robot = new ExtendedRobot();
+ EventQueue.invokeAndWait(this::initGui);
+ }
+
+ void initGui(){
+ parentFrame = new Frame("Parent Frame");
+ parentFrame.setLayout(new FlowLayout());
+
+ for (int i = 1; i <= 3; i++)
+ createDialog(i);
+
+ parentFrame.setLocation(250, 20);
+ parentFrame.pack();
+ parentFrame.setVisible(true);
+ }
+
+ public void doTest() throws Exception{
+ robot.waitForIdle();
+
+ parentFrame.dispose();
+ robot.waitForIdle();
+
+ Vector garbage = new Vector();
+ while (true) {
+ try {
+ garbage.add(new byte[1000]);
+ } catch (OutOfMemoryError er) {
+ break;
+ }
+ }
+ garbage = null;
+
+ int count = 1;
+ for (; count <= 3; count++)
+ if(que.remove(5000) == null)
+ break;
+
+ if (count < 3)
+ throw new RuntimeException("Count = "+count+". GC didn't collect the objects after the parent is disposed!");
+ }
+
+ public void createDialog(int number) {
+ Dialog child = new Dialog(parentFrame);
+ child.setTitle("Dialog " + number);
+ child.setLayout(new FlowLayout());
+ child.setLocation(20, 140 * number);
+
+ Button button = new Button("Press Me") ;
+ TextArea textArea = new TextArea(5,5);
+ TextField textField = new TextField(10);
+ Choice choice = new Choice();
+ choice.add("One");
+ choice.add("Two");
+ choice.add("Three");
+ choice.add("Four");
+ choice.add("Five");
+ List list = new List();
+ list.add("One");
+ list.add("Two");
+ list.add("Three");
+ list.add("Four");
+ list.add("Five");
+ Checkbox checkBox = new Checkbox("Hai");
+ Scrollbar scrollBar = new Scrollbar(Scrollbar.VERTICAL,0,1,0,200);
+ CheckboxGroup checkboxGroup = new CheckboxGroup();
+ Checkbox radioButton = new Checkbox("Hello" ,true, checkboxGroup);
+ Canvas canvas = new Canvas();
+ Label label = new Label("I am label!");
+ Cursor customCursor = null;
+
+ child.setLayout(new FlowLayout());
+ canvas.setSize(100,100);
+ canvas.setBackground(Color.red);
+
+ button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
+ label.setCursor(new Cursor(Cursor.TEXT_CURSOR));
+ choice.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ list.setCursor(new Cursor(Cursor.HAND_CURSOR));
+ checkBox.setCursor(new Cursor(Cursor.MOVE_CURSOR));
+ radioButton.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
+ scrollBar.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
+ canvas.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR));
+ textField.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+
+ /* create a custom cursor */
+ Toolkit toolkit = Toolkit.getDefaultToolkit();
+ Dimension d = toolkit.getBestCursorSize(32,32);
+ int color = toolkit.getMaximumCursorColors();
+
+ if(!d.equals(new Dimension(0,0)) && color != 0 )
+ customCursor = toolkit.createCustomCursor(new BufferedImage( 16, 16, BufferedImage.TYPE_INT_RGB ), new Point(10, 10), "custom cursor.");
+ else
+ System.err.println("Platform doesn't support to create a custom cursor.");
+
+ textArea.setCursor(customCursor);
+ child.add(label);
+ child.add(button);
+ child.add(choice);
+ child.add(list);
+ child.add(checkBox);
+ child.add(radioButton);
+ child.add(scrollBar);
+ child.add(canvas);
+ child.add(textArea);
+ child.add(textField);
+ child.add(button);
+ child.revalidate();
+
+ child.pack();
+ child.setVisible(true);
+ refs.add(new PhantomReference<Dialog>(child, que));
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Frame/FramesGC/FramesGC.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+import java.util.ArrayList;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary Verify that disposed frames are collected with GC
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main/othervm -Xmx20m FramesGC
+ */
+
+
+public class FramesGC {
+
+ ExtendedRobot robot;
+ ArrayList<PhantomReference<Frame>> refs = new ArrayList<PhantomReference<Frame>>();
+ ReferenceQueue<Frame> que = new ReferenceQueue<Frame>();
+
+ public static void main(String []args) throws Exception {
+ new FramesGC().doTest();
+ }
+
+ FramesGC() throws Exception{
+ robot = new ExtendedRobot();
+ }
+
+ void doTest() throws Exception {
+ for( int i = 1; i <= 3; i++) {
+ final int j = i;
+ EventQueue.invokeAndWait(() -> {
+ createFrame(j);
+ });
+ }
+ robot.waitForIdle();
+
+ for (Frame f : Frame.getFrames())
+ f.dispose();
+
+ robot.waitForIdle();
+
+ Vector garbage = new Vector();
+ while (true) {
+ try {
+ garbage.add(new byte[1000]);
+ } catch (OutOfMemoryError er) {
+ break;
+ }
+ }
+ garbage = null;
+
+ int count = 1;
+ for(; count <= 3; count++)
+ if(que.remove(5000) == null)
+ break;
+
+ System.out.println("Total no of instances eligible for GC = " + count);
+ if(count < 3)
+ throw new RuntimeException("Count = "+count+". Test failed!");
+
+ }
+
+ void createFrame(int i){
+ Frame frame = new Frame("Frame " + i);
+
+ Button button=new Button("Press Me");
+ TextArea textArea=new TextArea(5,5);
+ TextField textField=new TextField(10);
+ Choice choice=new Choice();
+ choice.add("One");
+ choice.add("Two");
+ choice.add("Three");
+ choice.add("Four");
+ choice.add("Five");
+ List list = new List();
+ list.add("One");
+ list.add("Two");
+ list.add("Three");
+ list.add("Four");
+ list.add("Five");
+ Checkbox checkBox= new Checkbox("Hai");
+ Scrollbar scrollBar=new Scrollbar(Scrollbar.VERTICAL,0,1,0,200);
+ CheckboxGroup checkboxGroup=new CheckboxGroup();
+ Checkbox radioButton=new Checkbox("Hello" ,true, checkboxGroup);
+ Canvas canvas=new Canvas();
+ canvas.setSize(100, 100);
+ canvas.setBackground(java.awt.Color.red);
+ Label label=new Label("I am label.!");
+ Cursor customCursor=null;
+
+ frame.setLayout(new java.awt.FlowLayout());
+
+ button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
+ label.setCursor(new Cursor(Cursor.TEXT_CURSOR));
+ choice.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ list.setCursor(new Cursor(Cursor.HAND_CURSOR));
+ checkBox.setCursor(new Cursor(Cursor.MOVE_CURSOR));
+ radioButton.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
+ scrollBar.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
+ canvas.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR));
+ textField.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+
+ /* create a custom cursor */
+ Toolkit toolkit = Toolkit.getDefaultToolkit();
+ Dimension d = toolkit.getBestCursorSize(32,32);
+ int color = toolkit.getMaximumCursorColors();
+
+ if(!d.equals(new Dimension(0,0)) && color != 0 )
+ customCursor = toolkit.createCustomCursor(new BufferedImage( 16, 16, BufferedImage.TYPE_INT_RGB ), new Point(10, 10), "custom cursor.");
+ else
+ System.err.println("Platform doesn't support to create a custom cursor.");
+
+ textArea.setCursor(customCursor);
+ frame.add(label);
+ frame.add(button);
+ frame.add(choice);
+ frame.add(list);
+ frame.add(checkBox);
+ frame.add(radioButton);
+ frame.add(scrollBar);
+ frame.add(canvas);
+ frame.add(textArea);
+ frame.add(textField);
+ frame.add(button);
+
+ frame.setLocation(20, 140 * i);
+ frame.pack();
+ frame.setVisible(true);
+ refs.add(new PhantomReference<Frame>(frame, que));
+ }
+
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Graphics2D/DrawString/DrawStringCrash.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8043508
+ * @summary Drawing a very long string crashes VM
+ */
+
+import java.awt.*;
+import java.awt.image.*;
+
+public class DrawStringCrash {
+
+ public static void main(String[] args) {
+ StringBuffer sb = new StringBuffer();
+ String s = "abcdefghijklmnopqrstuzwxyz";
+ for (int x = 0; x < 100000 ; x++) {
+ sb.append(s);
+ }
+ // Now have a string which uses approx 5Mb memory
+ // Loop again drawing doubling each time until
+ // we reach 8 billion chars or get OOME which means we can't
+ // go any further.
+ // Often there is no crash because Java OOM happens
+ // long before native heap runs out.
+ long maxLen = 8L * 1024 * 1024 * 1024;
+ int len = sb.length();
+
+ BufferedImage bi =
+ new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
+ Graphics2D g2d = bi.createGraphics();
+ while (len < maxLen) {
+ try {
+ g2d.drawString(s, 20, 20);
+ } catch (OutOfMemoryError e) {
+ return;
+ }
+ sb.append(sb);
+ len *= 2;
+ }
+ return;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/List/ListGarbageCollectionTest/AwtListGarbageCollectionTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8040076
+ * @summary AwtList not garbage collected
+ * @run main/othervm -Xmx100m AwtListGarbageCollectionTest
+ */
+
+import java.awt.*;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.lang.ref.WeakReference;
+
+public class AwtListGarbageCollectionTest {
+ public static void main(String[] args) {
+ Frame frame = new Frame("List leak test");
+ try {
+ test(frame);
+ } finally {
+ frame.dispose();
+ }
+ }
+
+ private static void test(Frame frame) {
+ WeakReference<List> weakListRef = null;
+ try {
+ frame.setSize(300, 200);
+ frame.setVisible(true);
+
+ List strongListRef = new List();
+ frame.add(strongListRef);
+ strongListRef.setMultipleMode(true);
+ frame.remove(strongListRef);
+ weakListRef = new WeakReference<List>(strongListRef);
+ strongListRef = null;
+
+ //make out of memory to force gc
+ String veryLongString = new String(new char[100]);
+ while (true) {
+ veryLongString += veryLongString;
+ }
+ } catch (OutOfMemoryError e) {
+ if (weakListRef == null) {
+ throw new RuntimeException("Weak list ref wasn't created");
+ } else if (weakListRef.get() != null) {
+ throw new RuntimeException("List wasn't garbage collected");
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.Color;
+import java.awt.Dialog;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Panel;
+import java.awt.Rectangle;
+import java.awt.Robot;
+import java.awt.SplashScreen;
+import java.awt.Window;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import javax.imageio.ImageIO;
+import sun.java2d.SunGraphics2D;
+
+/**
+ * @test
+ * @bug 8043869
+ * @author Alexander Scherbatiy
+ * @summary [macosx] java -splash does not honor 2x hi dpi notation for retina
+ * support
+ * @run main MultiResolutionSplashTest GENERATE_IMAGES
+ * @run main/othervm -splash:splash1.png MultiResolutionSplashTest TEST_SPLASH 0
+ * @run main/othervm -splash:splash2 MultiResolutionSplashTest TEST_SPLASH 1
+ * @run main/othervm -splash:splash3. MultiResolutionSplashTest TEST_SPLASH 2
+ */
+public class MultiResolutionSplashTest {
+
+ private static final int IMAGE_WIDTH = 300;
+ private static final int IMAGE_HEIGHT = 200;
+
+ private static final ImageInfo[] tests = {
+ new ImageInfo("splash1.png", "splash1@2x.png", Color.BLUE, Color.GREEN),
+ new ImageInfo("splash2", "splash2@2x", Color.WHITE, Color.BLACK),
+ new ImageInfo("splash3.", "splash3@2x.", Color.YELLOW, Color.RED)
+ };
+
+ public static void main(String[] args) throws Exception {
+
+ String test = args[0];
+
+ switch (test) {
+ case "GENERATE_IMAGES":
+ generateImages();
+ break;
+ case "TEST_SPLASH":
+ int index = Integer.parseInt(args[1]);
+ testSplash(tests[index]);
+ break;
+ default:
+ throw new RuntimeException("Unknown test: " + test);
+ }
+ }
+
+ static void testSplash(ImageInfo test) throws Exception {
+ SplashScreen splashScreen = SplashScreen.getSplashScreen();
+
+ if (splashScreen == null) {
+ throw new RuntimeException("Splash screen is not shown!");
+ }
+
+ Graphics2D g = splashScreen.createGraphics();
+ Rectangle splashBounds = splashScreen.getBounds();
+ int screenX = (int) splashBounds.getCenterX();
+ int screenY = (int) splashBounds.getCenterY();
+
+ Robot robot = new Robot();
+ Color splashScreenColor = robot.getPixelColor(screenX, screenY);
+
+ float scaleFactor = getScaleFactor();
+ Color testColor = (1 < scaleFactor) ? test.color2x : test.color1x;
+
+ if (!testColor.equals(splashScreenColor)) {
+ throw new RuntimeException(
+ "Image with wrong resolution is used for splash screen!");
+ }
+ }
+
+ static float getScaleFactor() {
+
+ final Dialog dialog = new Dialog((Window) null);
+ dialog.setSize(100, 100);
+ dialog.setModal(true);
+ final float[] scaleFactors = new float[1];
+ Panel panel = new Panel() {
+
+ @Override
+ public void paint(Graphics g) {
+ float scaleFactor = 1;
+ if (g instanceof SunGraphics2D) {
+ scaleFactor = ((SunGraphics2D) g).surfaceData.getDefaultScale();
+ }
+ scaleFactors[0] = scaleFactor;
+ dialog.setVisible(false);
+ }
+ };
+
+ dialog.add(panel);
+ dialog.setVisible(true);
+ dialog.dispose();
+
+ return scaleFactors[0];
+ }
+
+ static void generateImages() throws Exception {
+ for (ImageInfo test : tests) {
+ generateImage(test.name1x, test.color1x, 1);
+ generateImage(test.name2x, test.color2x, 2);
+ }
+ }
+
+ static void generateImage(String name, Color color, int scale) throws Exception {
+ File file = new File(name);
+ if (file.exists()) {
+ return;
+ }
+ BufferedImage image = new BufferedImage(scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT,
+ BufferedImage.TYPE_INT_RGB);
+ Graphics g = image.getGraphics();
+ g.setColor(color);
+ g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT);
+ ImageIO.write(image, "png", file);
+ }
+
+ static class ImageInfo {
+
+ final String name1x;
+ final String name2x;
+ final Color color1x;
+ final Color color2x;
+
+ public ImageInfo(String name1x, String name2x, Color color1x, Color color2x) {
+ this.name1x = name1x;
+ this.name2x = name2x;
+ this.color1x = color1x;
+ this.color2x = color2x;
+ }
+ }
+}
--- a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/FocusAWTTest.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/FocusAWTTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -35,6 +35,19 @@
* @bug 8013450
* @summary Check if the window events (Focus and Activation) are triggered correctly
* when clicked on visible and clipped areas.
+ *
+ * Test Description: Check if PERPIXEL_TRANSPARENT Translucency type is supported
+ * by the current platform. Proceed if it is supported. Apply different
+ * types of shapes on a Window. Make it appear with a known background.
+ * Check if mouse events which result in window-activated events are
+ * triggered only within the window's shape and not outside. Repeat this
+ * for Window, Dialog and Frame.
+ * Expected Result: If PERPIXEL_TRANSPARENT Translucency type is supported, window should
+ * gain focus and should trigger activated events only when it is clicked on the
+ * visible areas. Events should be delivered to the background window if clicked
+ * on the clipped areas.
+ *
+ * @author mrkam
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library ../../../../lib/testlibrary
* @build Common ExtendedRobot
@@ -149,6 +162,7 @@
window.setVisible(true);
}
+ @Override
public void doTest() throws Exception {
super.doTest();
final Point wls = new Point();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/SetShape.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
+import java.awt.geom.*;
+
+/*
+ * @test
+ * @summary Check if a window set with shape appears in the expected shape
+ *
+ * Test Description: Check if PERPIXEL_TRANSPARENT Translucency type is supported
+ * by the current platform. Proceed if it is supported. Apply different
+ * types of shapes on a Window. Make it appear with a known background. Use
+ * get pixel color to check whether it appears as expected. Repeat this for
+ * Window, Dialog and Frame.
+ * Expected Result: If PERPIXEL_TRANSPARENT Translucency type is supported, the
+ * window should appear with the expected shape.
+ *
+ * @author mrkam
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build Common ExtendedRobot
+ * @run main SetShape
+ */
+
+public class SetShape extends Common {
+
+ static int[][] pointsToCheck;
+ static Shape shape;
+
+ public static void main(String[] args) throws Exception {
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) {
+ for (int i = 0; i < 6; i++) {
+ System.out.println("Checking shape "+i);
+ Area area;
+ GeneralPath path;
+ switch (i) {
+ case 0:
+ path = new GeneralPath();
+ path.moveTo(0, 40);
+ path.lineTo(40, 0);
+ path.lineTo(110, 0);
+ path.lineTo(150, 40);
+ path.lineTo(150, 110);
+ path.lineTo(110, 150);
+ path.lineTo(40, 150);
+ path.lineTo(0, 110);
+ path.closePath();
+ shape = path;
+ pointsToCheck = new int[][]{
+ // inside shape
+ {230, 240}, {286, 332}, {314, 267}, {220, 327}, {223, 246},
+ {229, 274}, {335, 257}, {231, 278}, {317, 299}, {266, 236},
+ // outside shape
+ {340, 353}, {373, 320}, {330, 220}, {384, 300}, {349, 406},
+ {213, 355}, {361, 260}, {399, 251}, {201, 374}, {199, 257}
+ };
+ break;
+ case 1:
+ area = new Area();
+ area.add(new Area(new Rectangle2D.Float(50, 0, 100, 150)));
+ area.add(new Area(new Rectangle2D.Float(0, 50, 200, 50)));
+ area.add(new Area(new Ellipse2D.Float(0, 0, 100, 100)));
+ area.add(new Area(new Ellipse2D.Float(0, 50, 100, 100)));
+ area.add(new Area(new Ellipse2D.Float(100, 0, 100, 100)));
+ area.add(new Area(new Ellipse2D.Float(100, 50, 100, 100)));
+ shape = area;
+ pointsToCheck = new int[][]{
+ // inside shape
+ {306, 314}, {296, 266}, {276, 335}, {380, 253}, {224, 333},
+ {396, 305}, {365, 278}, {214, 331}, {289, 349}, {367, 345},
+ // outside shape
+ {365, 424}, {391, 391}, {346, 413}, {261, 398}, {348, 399},
+ {282, 400}, {386, 215}, {399, 369}, {213, 401}, {387, 215}
+ };
+ break;
+ case 2:
+ path = new GeneralPath();
+ path.moveTo(100, 0);
+ double angle = -Math.PI / 2;
+ double angle_step = Math.PI * 2 / 8;
+ for (int c = 0; c < 8; c++, angle += angle_step) {
+ path.lineTo(100 + 100 * Math.cos(angle), 100 + 100 * Math.sin(angle));
+ path.lineTo(100 + 40 * Math.cos(angle + angle_step / 2), 100 + 40 * Math.sin(angle + angle_step / 2));
+ }
+ path.closePath();
+ shape = path;
+ pointsToCheck = new int[][]{
+ // inside shape
+ {246, 257}, {300, 314}, {255, 347}, {291, 364}, {287, 320},
+ {319, 276}, {269, 345}, {325, 291}, {289, 271}, {273, 339},
+ // outside shape
+ {373, 267}, {269, 229}, {390, 326}, {204, 216}, {379, 408},
+ {375, 330}, {296, 213}, {367, 340}, {376, 409}, {378, 308}
+ };
+ break;
+ case 3:
+ area = new Area();
+ area.add(new Area(new Rectangle2D.Float(-15, 85, 230, 30)));
+ area.transform(AffineTransform.getRotateInstance(-Math.PI / 4, 100, 100));
+ shape = area;
+ pointsToCheck = new int[][]{
+ // inside shape
+ {240, 366}, {254, 338}, {342, 244}, {264, 344}, {343, 240},
+ {292, 303}, {225, 374}, {263, 348}, {329, 290}, {278, 327},
+ // outside shape
+ {353, 289}, {334, 377}, {391, 354}, {266, 358}, {280, 364},
+ {232, 225}, {327, 309}, {375, 208}, {397, 292}, {204, 335}
+ };
+ break;
+ case 4:
+ area = new Area();
+ area.add(new Area(new Arc2D.Float(0, -100, 400, 400, 155, 50, Arc2D.PIE)));
+ area.subtract(new Area(new Ellipse2D.Float(70, 115, 20, 20)));
+ area.subtract(new Area(new Ellipse2D.Float(30, 90, 18, 18)));
+ area.subtract(new Area(new Ellipse2D.Float(17, 50, 30, 30)));
+ area.subtract(new Area(new Ellipse2D.Float(26, 124, 26, 26)));
+ area.subtract(new Area(new Ellipse2D.Float(100, 85, 25, 25)));
+ area.subtract(new Area(new Ellipse2D.Float(135, 100, 14, 14)));
+ shape = area;
+ pointsToCheck = new int[][]{
+ // inside shape
+ {225, 286}, {296, 276}, {318, 269}, {211, 357}, {295, 327},
+ {207, 300}, {322, 265}, {319, 262}, {259, 294}, {261, 250},
+ // outside shape
+ {322, 303}, {330, 367}, {302, 395}, {227, 251}, {263, 382},
+ {228, 383}, {280, 366}, {294, 248}, {316, 349}, {313, 294}
+ };
+ break;
+ case 5:
+ area = new Area();
+ area.add(new Area(new Rectangle2D.Float(0, 0, 90, 90)));
+ area.add(new Area(new Rectangle2D.Float(100, 0, 100, 200)));
+ area.add(new Area(new Ellipse2D.Float(0, 100, 100, 100)));
+ shape = area;
+ pointsToCheck = new int[][]{
+ // inside shape
+ {275, 345}, {358, 327}, {373, 374}, {273, 331}, {251, 234},
+ {285, 356}, {360, 287}, {319, 343}, {232, 210}, {323, 323},
+ // outside shape
+ {219, 291}, {270, 302}, {296, 383}, {298, 203}, {228, 293},
+ {276, 300}, {292, 294}, {293, 216}, {298, 331}, {228, 295}
+ };
+ break;
+ default:
+ break;
+ }
+
+ for (Class<Window> windowClass : WINDOWS_TO_TEST) {
+ new SetShape(windowClass).doTest();
+ }
+ }
+ }
+ }
+
+ public SetShape(Class windowClass) throws Exception {
+ super(windowClass);
+ }
+
+ @Override
+ public void initGUI() {
+ if (windowClass.equals(Frame.class)) {
+ window = new Frame();
+ ((Frame) window).setUndecorated(true);
+ } else if (windowClass.equals(Dialog.class)) {
+ window = new Dialog(background);
+ ((Dialog) window).setUndecorated(true);
+ } else {
+ window = new Window(background);
+ }
+ window.setBackground(FG_COLOR);
+ window.addComponentListener(new ComponentAdapter() {
+ @Override
+ public void componentResized(ComponentEvent e) {
+ window.setShape(shape);
+ }
+ });
+ window.setSize(200, 200);
+ window.setLocation(2*dl, 2*dl);
+ window.setVisible(true);
+
+ System.out.println("Checking " + window.getClass().getName() + "...");
+ }
+
+ @Override
+ public void doTest() throws Exception {
+ robot.waitForIdle();
+
+ final int COUNT_TARGET = 10;
+ for(int i = 0; i < COUNT_TARGET * 2; i++) {
+ int x = pointsToCheck[i][0];
+ int y = pointsToCheck[i][1];
+ boolean inside = i < COUNT_TARGET;
+ Color c = robot.getPixelColor(x, y);
+ System.out.println("checking " + x + ", " + y + ", color = " + c);
+ boolean matchToForeground = FG_COLOR.equals(c);
+
+ if (!inside && matchToForeground || inside && !matchToForeground) {
+ System.err.println("Checking for transparency failed: point: " +
+ x + ", " + y +
+ ", color = " + c + (inside ? " is not of " : " is of un") +
+ "expected foreground color " + FG_COLOR);
+ final Frame[] f = new Frame[1];
+ EventQueue.invokeAndWait(() -> {
+ f[0] = new Frame();
+ f[0].setUndecorated(true);
+ f[0].setBackground(Color.YELLOW);
+ f[0].setPreferredSize(new Dimension(2, 2));
+ f[0].pack();
+ f[0].setVisible(true);
+ });
+ robot.delay(1000);
+ EventQueue.invokeAndWait(() -> {
+ f[0].setLocation(x, y);
+ });
+ robot.delay(1000);
+ }
+ }
+ EventQueue.invokeAndWait(window::dispose);
+ EventQueue.invokeAndWait(background::dispose);
+
+ robot.waitForIdle();
+ }
+
+ @Override
+ public void applyShape() { window.setShape(shape); }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/SetShapeAndClick.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.geom.Area;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Rectangle2D;
+
+/*
+ * @test
+ * @summary Check if a window set with shape clips the contents
+ *
+ * Test Description: Check if PERPIXEL_TRANSPARENT Translucency type is supported
+ * by the current platform. Proceed if it is supported. Apply different types
+ * of shapes on a Window which contains some awt components. Shape should be
+ * applied in such a way that some components are partially clipped off. Check
+ * if the components appear only partially and events work correctly for those
+ * components - i.e. events occur only on the areas which appear and do not
+ * occur on the clipped off areas. Events should be checked by clicking on the
+ * visible and clipped regions. Repeat this for Window, Dialog and Frame.
+ * Expected Result: If PERPIXEL_TRANSPARENT Translucency type is supported, clicking
+ * on clipped region should deliver the event to the background (it should be
+ * another Window behind the test window)
+ *
+ * @author mrkam
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build Common ExtendedRobot
+ * @run main SetShapeAndClick
+ */
+
+public class SetShapeAndClick extends Common {
+
+ Component south, center, north;
+ volatile int clicked;
+
+ public static void main(String[] args) throws Exception {
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT))
+ for (Class<Window> windowClass: WINDOWS_TO_TEST)
+ new SetShapeAndClick(windowClass).doTest();
+ }
+
+ public SetShapeAndClick(Class windowClass) throws Exception {
+ super(windowClass);
+ }
+
+ @Override
+ public void initBackgroundFrame() {
+ super.initBackgroundFrame();
+ background.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 0;
+ }
+ });
+ }
+
+ @Override
+ public void initGUI() {
+ if (windowClass.equals(Frame.class)) {
+ window = new Frame();
+ ((Frame) window).setUndecorated(true);
+ } else if (windowClass.equals(Dialog.class)) {
+ window = new Dialog(background);
+ ((Dialog) window).setUndecorated(true);
+ } else {
+ window = new Window(background);
+ }
+
+ window.setLocation(2 * dl, 2 * dl);
+ window.setPreferredSize(new Dimension(200, 200));
+ window.setLayout(new BorderLayout());
+
+ window.addComponentListener(new ComponentAdapter() {
+ public void componentResized(ComponentEvent e) {
+ applyShape();
+ }
+ });
+
+ south = new Label("South");
+ south.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 3;
+ }
+ });
+ window.add(south, BorderLayout.SOUTH);
+
+ center = new List(5);
+ center.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 2;
+ }
+ });
+ window.add(center, BorderLayout.CENTER);
+
+ north = new TextField("North");
+ north.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 1;
+ }
+ });
+ window.add(north, BorderLayout.NORTH);
+
+ window.pack();
+ window.setVisible(true);
+ window.toFront();
+
+ System.out.println("Checking " + window.getClass().getName() + "...");
+ }
+
+ @Override
+ public void doTest() throws Exception {
+
+ robot.waitForIdle();
+
+ Point wls = window.getLocationOnScreen();
+ Point ls;
+ int y;
+ ls = north.getLocationOnScreen();
+ checkClick(ls.x + north.getWidth() / 3, ls.y + north.getHeight() / 2, 1);
+
+ ls = center.getLocationOnScreen();
+ checkClick(ls.x + center.getWidth() * 3 / 4, ls.y + center.getHeight() * 3 / 4, 2);
+
+ ls = south.getLocationOnScreen();
+ checkClick(ls.x + south.getWidth() * 2 / 3, ls.y + south.getHeight() / 2, 3);
+
+ ls = center.getLocationOnScreen();
+ checkClick(ls.x + center.getWidth() / 4, ls.y + center.getHeight() / 4, 2);
+
+ ls = north.getLocationOnScreen();
+ y = ls.y + north.getHeight() / 2;
+ checkClick(wls.x + 200 - (y - wls.y), y, 0);
+
+ EventQueue.invokeAndWait(window::toFront);
+ robot.waitForIdle();
+
+ ls = center.getLocationOnScreen();
+ y = ls.y + center.getHeight() / 2;
+ checkClick(wls.x + 200 - (y - wls.y), y, 0);
+
+ EventQueue.invokeAndWait(window::toFront);
+ robot.waitForIdle();
+
+ ls = south.getLocationOnScreen();
+ y = ls.y + south.getHeight() / 2;
+ checkClick(wls.x + 200 - (y - wls.y), y, 0);
+
+ EventQueue.invokeAndWait(window::dispose);
+ EventQueue.invokeAndWait(background::dispose);
+
+ robot.waitForIdle();
+ }
+
+ @Override
+ public void applyShape() {
+ Area shape = new Area(new Rectangle2D.Float(0, 0, 200, 200));
+ GeneralPath gp;
+ gp = new GeneralPath();
+ gp.moveTo(190, 0);
+ gp.lineTo(200, 0);
+ gp.lineTo(200, 10);
+ gp.lineTo(10, 200);
+ gp.lineTo(0, 200);
+ gp.lineTo(0, 190);
+ gp.closePath();
+ shape.subtract(new Area(gp));
+
+ window.setShape(shape);
+ }
+
+ void checkClick(int x, int y, int flag) throws Exception {
+
+ System.out.println("Trying to click point " + x + ", " + y + ", looking for " + flag + " flag to trigger.");
+
+ clicked = 0;
+ robot.mouseMove(x, y);
+ robot.click();
+
+ for (int i = 0; i < 100; i++)
+ if ((clicked & (1 << flag)) == 0)
+ robot.delay(50);
+ else
+ break;
+
+ if ((clicked & (1 << flag)) == 0)
+ throw new RuntimeException("FAIL: Flag " + flag + " is not triggered for point " + x + ", " + y + "!");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/SetShapeDynamicallyAndClick.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.geom.Area;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Rectangle2D;
+
+/*
+ * @test
+ * @summary Check if dynamically setting a shape works
+ *
+ * Test Description: Check if PERPIXEL_TRANSPARENT Translucency type is supported
+ * by the current platform. Proceed if it is supported. Show a window which
+ * contains some components and apply a shape for the Window when the window
+ * is visible. Shape should be applied in such a way that some components
+ * are partially clipped off. Check if the components appear only partially
+ * and events work correctly for those components - ie, events occur only on
+ * the areas which appear and do not occur on the clipped off areas. Events
+ * should be checked by clicking on the visible and clipped regions. Repeat
+ * this for Window, Dialog and Frame.
+ * Expected Result: If PERPIXEL_TRANSPARENT translucency type is supported,
+ * clicking on clipped region should deliver the event to the background (it
+ * should be another Window behind the test window)
+ *
+ * @author mrkam
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build Common ExtendedRobot
+ * @run main SetShapeDynamicallyAndClick
+ */
+
+public class SetShapeDynamicallyAndClick extends Common {
+
+ Component south, center, north;
+ volatile int clicked;
+
+ public static void main(String[] args) throws Exception {
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT))
+ for (Class<Window> windowClass: WINDOWS_TO_TEST)
+ new SetShapeDynamicallyAndClick(windowClass).doTest();
+ }
+
+ public SetShapeDynamicallyAndClick(Class windowClass) throws Exception {
+ super(windowClass);
+ }
+
+ @Override
+ public void initBackgroundFrame() {
+ super.initBackgroundFrame();
+ background.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 0;
+ }
+ });
+ }
+
+ @Override
+ public void initGUI() {
+ if (windowClass.equals(Frame.class)) {
+ window = new Frame();
+ ((Frame) window).setUndecorated(true);
+ } else if (windowClass.equals(Dialog.class)) {
+ window = new Dialog(background);
+ ((Dialog) window).setUndecorated(true);
+ } else {
+ window = new Window(background);
+ }
+
+ window.setLocation(2 * dl, 2 * dl);
+ window.setPreferredSize(new Dimension(200, 200));
+ window.setLayout(new BorderLayout());
+
+ south = new Label("South");
+ south.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 3;
+ }
+ });
+ window.add(south, BorderLayout.SOUTH);
+
+ center = new List(5);
+ center.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 2;
+ }
+ });
+ window.add(center, BorderLayout.CENTER);
+
+ north = new TextField("North");
+ north.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 1;
+ }
+ });
+ window.add(north, BorderLayout.NORTH);
+
+ window.pack();
+ window.setVisible(true);
+ window.toFront();
+
+ System.out.println("Checking " + window.getClass().getName() + "...");
+ }
+
+ @Override
+ public void doTest() throws Exception {
+
+ robot.waitForIdle();
+
+ Point wls = window.getLocationOnScreen();
+ Point ls;
+ int y;
+
+ EventQueue.invokeAndWait(this::applyShape);
+
+ robot.waitForIdle();
+
+ ls = north.getLocationOnScreen();
+ checkClick(ls.x + north.getWidth() / 3, ls.y + north.getHeight() / 2, 1);
+
+ ls = center.getLocationOnScreen();
+ checkClick(ls.x + center.getWidth() * 3 / 4, ls.y + center.getHeight() * 3 / 4, 2);
+
+ ls = south.getLocationOnScreen();
+ checkClick(ls.x + south.getWidth() * 2 / 3, ls.y + south.getHeight() / 2, 3);
+
+ ls = center.getLocationOnScreen();
+ checkClick(ls.x + center.getWidth() / 4, ls.y + center.getHeight() / 4, 2);
+
+ ls = north.getLocationOnScreen();
+ y = ls.y + north.getHeight() / 2;
+ checkClick(wls.x + 200 - (y - wls.y), y, 0);
+
+ EventQueue.invokeAndWait(window::toFront);
+ robot.waitForIdle();
+
+ ls = center.getLocationOnScreen();
+ y = ls.y + center.getHeight() / 2;
+ checkClick(wls.x + 200 - (y - wls.y), y, 0);
+
+ EventQueue.invokeAndWait(window::toFront);
+ robot.waitForIdle();
+
+ ls = south.getLocationOnScreen();
+ y = ls.y + south.getHeight() / 2;
+ checkClick(wls.x + 200 - (y - wls.y), y, 0);
+
+ EventQueue.invokeAndWait(window::dispose);
+ EventQueue.invokeAndWait(background::dispose);
+
+ robot.waitForIdle();
+ }
+
+ @Override
+ public void applyShape() {
+ Area shape = new Area(new Rectangle2D.Float(0, 0, 200, 200));
+ GeneralPath gp;
+ gp = new GeneralPath();
+ gp.moveTo(190, 0);
+ gp.lineTo(200, 0);
+ gp.lineTo(200, 10);
+ gp.lineTo(10, 200);
+ gp.lineTo(0, 200);
+ gp.lineTo(0, 190);
+ gp.closePath();
+ shape.subtract(new Area(gp));
+
+ window.setShape(shape);
+ }
+
+ void checkClick(int x, int y, int flag) throws Exception {
+
+ System.out.println("Trying to click point " + x + ", " + y + ", looking for " + flag + " flag to trigger.");
+
+ clicked = 0;
+ robot.mouseMove(x, y);
+ robot.click();
+
+ for (int i = 0; i < 100; i++)
+ if ((clicked & (1 << flag)) == 0)
+ robot.delay(50);
+ else
+ break;
+
+ if ((clicked & (1 << flag)) == 0)
+ throw new RuntimeException("FAIL: Flag " + flag + " is not triggered for point " + x + ", " + y + "!");
+ }
+}
--- a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Shaped.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Shaped.java Wed Jul 05 19:50:57 2017 +0200
@@ -26,8 +26,22 @@
/*
* @test
- * @summary Check if dynamically shaped window is moved and resized
- * by robot correctly
+ * @summary Check if dynamically shaped window is dragged and resized
+ * by mouse correctly
+ *
+ * Test Description: Check if specified translucency types PERPIXEL_TRANSPARENT
+ * is supported on the current platform. Proceed if it is supported.
+ * Create a window apply shape in componentResized listener. The shape
+ * should match the window size. Drag and resize the window using AWT Robot
+ * and verify that shape is correctly applied both with pixels checking and
+ * clicks. Make the window appear on top of a known background. Repeat this
+ * for Window, Dialog, Frame,
+ * Expected Result: If PERPIXEL_TRANSPARENT translucency type is supported,
+ * the window should appear with the expected shape. Clicks should come
+ * to visible parts of shaped window only and to background for clipped
+ * parts.
+ *
+ * @author mrkam
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library ../../../../lib/testlibrary
* @build Common ExtendedRobot
@@ -45,8 +59,11 @@
public Shaped(Class windowClass) throws Exception{
super(windowClass);
}
+
+ @Override
public void applyShape(){ applyDynamicShape(); }
+ @Override
public void doTest() throws Exception{
super.doTest();
--- a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedByAPI.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedByAPI.java Wed Jul 05 19:50:57 2017 +0200
@@ -26,8 +26,21 @@
/*
* @test
- * @summary Check if dynamically shaped window is moved and resized
- * using API correctly
+ * @summary Check if dynamically shaped window is moved and resized by
+ * API correctly.
+ *
+ * Test Description: Check if PERPIXEL_TRANSPARENT translucency type is
+ * supported on the current platform. Proceed if it is supported. Create
+ * a window and apply shape in componentResized listener. The shape should
+ * match the window size. Drag and resize the window using API and verify
+ * that shape is correctly applied both with pixels checking and clicks.
+ * Make the window appear on top of a known background. Repeat this for
+ * Window, Dialog, Frame.
+ * Expected Result: If PERPIXEL_TRANSPARENT translucency type is supported, the
+ * window should appear with the expected shape. Clicks should come to visible
+ * parts of shaped window only and to background for clipped parts.
+ *
+ * @author mrkam
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library ../../../../lib/testlibrary
* @run main ShapedByAPI
@@ -44,8 +57,11 @@
public ShapedByAPI(Class windowClass) throws Exception{
super(windowClass);
}
+
+ @Override
public void applyShape(){ applyDynamicShape(); }
+ @Override
public void doTest() throws Exception{
super.doTest();
--- a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java Wed Jul 05 19:50:57 2017 +0200
@@ -27,6 +27,20 @@
* @test
* @summary Check if a translucent shaped window is dragged and
* resized correctly.
+ *
+ * Test Description: Check if TRANSLUCENT and PERPIXEL_TRANSPARENT translucency
+ * types are supported on the current platform. Proceed if it is supported.
+ * Create and apply opacity of 0.3 and apply shape in componentResized
+ * listener. Drag and resize the window using AWT Robot and verify that
+ * shape and translucency are correctly applied both with pixels checking
+ * and clicks. Make the window appear on top of a known background. Repeat
+ * this for Window, Dialog, Frame.
+ * Expected Result: If TRANSLUCENT and PERPIXEL_TRANSPARENT translucency types are
+ * supported, the window should appear with the expected shape and translucency.
+ * Clicks should come to visible parts of shaped window only and to background
+ * for clipped parts.
+ *
+ * @author mrkam
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library ../../../../lib/testlibrary
* @build Common ExtendedRobot
@@ -46,8 +60,10 @@
super(windowClass, 0.3f);
}
+ @Override
public void applyShape(){ applyDynamicShape(); }
+ @Override
public void doTest() throws Exception{
super.doTest();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucentWindowClick.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import java.awt.geom.Area;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Rectangle2D;
+import java.util.BitSet;
+
+/*
+ * @test
+ * @summary Check if a translucent shaped window trigger events correctly.
+ *
+ * Test Description: Check if TRANSLUCENT and PERPIXEL_TRANSPARENT traslucency
+ * types are supported on the current platform. Proceed if both are
+ * supported. Create a window with some components in it and a shape
+ * applied. Apply the shape such that some components are partially
+ * clipped. Set an opacity value less than 1. Check if the components
+ * behave correctly on mouse and key events. Do this test for awt Window.
+ * Expected Result: Mouse and key events must work correctly. Only that portion
+ * of a component within the shape should trigger events. Key events
+ * should be tested for focus events and TextField/TextArea.
+ *
+ * @author mrkam
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build Common ExtendedRobot
+ * @run main ShapedTranslucentWindowClick
+ */
+
+public class ShapedTranslucentWindowClick extends Common {
+
+ Component south, center, north;
+
+ volatile BitSet backgroundFlags = new BitSet(11);
+ volatile BitSet southFlags = new BitSet(11);
+ volatile BitSet centerFlags = new BitSet(11);
+ volatile BitSet northFlags = new BitSet(11);
+ static BitSet reference = BitSet.valueOf(new long[] {2047}); // 111 1111 1111
+
+ public static void main(String[] ignored) throws Exception{
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT) &&
+ checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT))
+ new ShapedTranslucentWindowClick(Window.class).doTest();
+ }
+
+ public ShapedTranslucentWindowClick(Class windowClass) throws Exception {
+ super(windowClass);
+ addListeners(south, southFlags);
+ addListeners(center, centerFlags);
+ addListeners(north, northFlags);
+ addListeners(background, backgroundFlags);
+ }
+
+ @Override
+ public void initGUI() {
+
+ window = new Window(background);
+ south = new Button("South Button");
+ center = new TextArea("Center Text Area");
+ north = new TextField("North Text Field");
+
+ window.setLocation(250, 250);
+ window.setPreferredSize(new Dimension(200, 200));
+ window.setOpacity(0.7f);
+ applyShape();
+ window.setLayout(new BorderLayout());
+
+ window.add(south, BorderLayout.SOUTH);
+ window.add(center, BorderLayout.CENTER);
+ window.add(north, BorderLayout.NORTH);
+
+ window.pack();
+ window.setVisible(true);
+ window.toFront();
+
+ System.out.println("Checking " + window.getClass().getName() + "...");
+ }
+
+ @Override
+ public void doTest() throws Exception {
+
+ robot.waitForIdle();
+ robot.mouseMove(background.getLocationOnScreen().x+50, background.getLocationOnScreen().y+50);
+ robot.waitForIdle();
+ robot.click();
+
+ Point wls = window.getLocationOnScreen();
+ Point ls;
+ int y;
+
+ robot.waitForIdle();
+
+ ls = north.getLocationOnScreen();
+ checkClickAndType(ls.x + north.getWidth() / 3, ls.y + north.getHeight() / 2, northFlags);
+
+ ls = center.getLocationOnScreen();
+ checkClickAndType(ls.x + center.getWidth() / 4, ls.y + center.getHeight() / 4, centerFlags);
+
+ ls = center.getLocationOnScreen();
+ checkClickAndType(ls.x + center.getWidth() * 3 / 4, ls.y + center.getHeight() * 3 / 4, centerFlags);
+
+ ls = south.getLocationOnScreen();
+ checkClickAndType(ls.x + south.getWidth() * 2 / 3, ls.y + south.getHeight() / 2, southFlags);
+
+ ls = north.getLocationOnScreen();
+ y = ls.y + north.getHeight() / 2;
+ checkClickAndType(wls.x + 200 - (y - wls.y), y, backgroundFlags);
+
+ EventQueue.invokeAndWait(window::toFront);
+ robot.waitForIdle();
+
+ ls = center.getLocationOnScreen();
+ y = ls.y + center.getHeight() / 2;
+ checkClickAndType(wls.x + 200 - (y - wls.y), y, backgroundFlags);
+
+ EventQueue.invokeAndWait(window::toFront);
+ robot.waitForIdle();
+
+ ls = south.getLocationOnScreen();
+ y = ls.y + south.getHeight() / 2;
+ checkClickAndType(wls.x + 200 - (y - wls.y), y, backgroundFlags);
+
+ EventQueue.invokeAndWait(window::dispose);
+ EventQueue.invokeAndWait(background::dispose);
+
+ robot.waitForIdle();
+ }
+
+ @Override
+ public void applyShape() {
+ Area shape = new Area(new Rectangle2D.Float(0, 0, 200, 200));
+ GeneralPath gp;
+ gp = new GeneralPath();
+ gp.moveTo(190, 0);
+ gp.lineTo(200, 0);
+ gp.lineTo(200, 10);
+ gp.lineTo(10, 200);
+ gp.lineTo(0, 200);
+ gp.lineTo(0, 190);
+ gp.closePath();
+ shape.subtract(new Area(gp));
+
+ window.setShape(shape);
+ }
+
+ void checkClickAndType(int x, int y, BitSet bits){
+ bits.clear(0, 10);
+
+ robot.mouseMove(x, y);
+ robot.click();
+ robot.dragAndDrop(MouseInfo.getPointerInfo().getLocation(), new Point(x+5, y));
+ robot.mouseWheel(1);
+ robot.waitForIdle();
+
+ robot.type('a');
+
+ robot.mouseMove(350, 50);
+ robot.waitForIdle();
+
+ //robot.delay(20*1000);
+ if (!bits.equals(reference)){
+ for( int i = 0; i < 11; i++)
+ System.err.print(( bits.get(i) ? 1 : 0 ) + ", ");
+ System.err.println();
+ throw new RuntimeException("Bit mask is not fully set: "+bits);
+ }
+ }
+
+ static void addListeners(Component component, BitSet bits) {
+ component.addMouseListener(new MouseListener() {
+ public void mouseClicked(MouseEvent e) { bits.set(0);}
+ public void mousePressed(MouseEvent e) { bits.set(1); }
+ public void mouseReleased(MouseEvent e) { bits.set(2); }
+ public void mouseEntered(MouseEvent e) { bits.set(3); }
+ public void mouseExited(MouseEvent e) { bits.set(4); }
+ });
+ component.addMouseMotionListener(new MouseMotionListener() {
+ public void mouseDragged(MouseEvent e) { bits.set(5); }
+ public void mouseMoved(MouseEvent e) { bits.set(6); }
+ });
+ component.addMouseWheelListener((e) -> bits.set(7));
+ component.addKeyListener(new KeyListener() {
+ public void keyTyped(KeyEvent e) { bits.set(8); }
+ public void keyPressed(KeyEvent e) { bits.set(9); }
+ public void keyReleased(KeyEvent e) { bits.set(10); }
+ });
+ };
+}
--- a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java Wed Jul 05 19:50:57 2017 +0200
@@ -26,8 +26,21 @@
/*
* @test
- * @summary Check if statically shaped window is dragged and resized
- * correctly.
+ * @summary Check if statically shaped window is dragged and resized correctly.
+ *
+ * Test Description: Check if PERPIXEL_TRANSPARENT translucency type is supported
+ * on the current platform. Proceed if it is supported. Create a window
+ * and apply some shape at window creation. The shape should be bigger than
+ * window. Drag and resize the window using AWT Robot and verify that shape
+ * is correctly applied both with pixels checking and clicks. Make the
+ * window appear on top of a known background. Repeat this for Window, Dialog,
+ * Frame.
+ * Expected Result: If specified translucency type PERPIXEL_TRANSPARENT is supported,
+ * the window should appear with the expected shape clipped to the window
+ * size. Clicks should come to visible parts of shaped window only and to
+ * background for clipped parts.
+ *
+ * @author mrkam
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library ../../../../lib/testlibrary
* @build Common ExtendedRobot
@@ -44,8 +57,11 @@
}
public StaticallyShaped(Class windowClass) throws Exception{ super(windowClass); }
+
+ @Override
public void applyShape(){ applyStaticShape(); }
+ @Override
public void doTest() throws Exception{
super.doTest();
--- a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Translucent.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Translucent.java Wed Jul 05 19:50:57 2017 +0200
@@ -26,7 +26,19 @@
/*
* @test
* @summary Check if translucent window is dragged and resized
- correctly.
+ * correctly.
+ *
+ * Test Description: Check if TRANSLUCENT translucency type is supported
+ * on the current platform. Proceed if they are supported. Create
+ * a window and apply opacity of 0.3. Drag and resize the window
+ * using AWT Robot and verify that translucency is not affected.
+ * Make the window appear on top of a known background. Repeat this
+ * for Window, Dialog, Frame.
+ * Expected Result: If TRANSLUCENT translucency type is supported, the
+ * window should show the background. Dragging and resizing
+ * shouldn't affect the translucency.
+ *
+ * @author mrkam
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library ../../../../lib/testlibrary
* @build Common ExtendedRobot
@@ -35,8 +47,7 @@
public class Translucent extends Common {
public static void main(String[] args) throws Exception {
- if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT) &&
- checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT))
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT))
for (Class<Window> windowClass: WINDOWS_TO_TEST){
new Translucent(windowClass).doTest();
}
@@ -46,8 +57,10 @@
super(windowClass, 0.3f);
}
+ @Override
public void applyShape(){ }
+ @Override
public void doTest() throws Exception{
super.doTest();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/TranslucentChoice.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+
+/*
+ * @test
+ * @summary Check if a Choice present in a window set with opacity less than 1.0
+ * shows a translucent drop down
+ *
+ * Test Description: Check if TRANSLUCENT Translucency type is supported on the
+ * current platform. Proceed if supported. Show a window which contains an
+ * awt Choice and set with opacity less than 1.0. Another Window having a
+ * canvas component drawn with an image can be used as the background for
+ * the test window. Click on the ComboBox to show the drop down. Check if
+ * the drop down appears translucent. Repeat this for Window, Dialog and
+ * Frame.
+ * Expected Result: If TRANSLUCENT Translucency type is supported, the drop down
+ * should appear translucent.
+ *
+ * @author mrkam
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build Common ExtendedRobot
+ * @run main TranslucentChoice
+ */
+
+public class TranslucentChoice extends Common {
+
+ Choice south;
+ Component center;
+ Component north;
+ volatile int clicked;
+
+ public static void main(String[] ignored) throws Exception {
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT))
+ for (Class<Window> windowClass: WINDOWS_TO_TEST){
+ new TranslucentChoice(windowClass).doTest();
+ }
+ }
+
+ public TranslucentChoice(Class windowClass) throws Exception {
+ super(windowClass);
+ }
+
+ @Override
+ public void initBackgroundFrame() {
+ super.initBackgroundFrame();
+ background.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 0;
+ }
+ });
+ }
+
+ @Override
+ public void initGUI() {
+ if (windowClass.equals(Frame.class)) {
+ window = new Frame();
+ ((Frame) window).setUndecorated(true);
+ } else if (windowClass.equals(Dialog.class)) {
+ window = new Dialog(background);
+ ((Dialog) window).setUndecorated(true);
+ } else {
+ window = new Window(background);
+ }
+
+ window.setBackground(FG_COLOR);
+ north = new Button("north");
+ window.add(north, BorderLayout.NORTH);
+
+ center = new List(5);
+ window.add(center, BorderLayout.CENTER);
+
+ Choice choice = new Choice();
+ for(int i = 0; i < 20; i++) {
+ choice.add("item " + i);
+ }
+ south = choice;
+
+ south.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ clicked |= 1 << 1;
+ }
+ });
+
+ window.add(south, BorderLayout.SOUTH);
+ window.setAlwaysOnTop(true);
+ window.setOpacity(0.3f);
+ window.setLocation(2 * dl, 2 * dl);
+ window.setSize(255, 255);
+ window.pack();
+ window.setVisible(true);
+
+ System.out.println("Checking " + window.getClass().getName() + "...");
+ }
+
+ @Override
+ public void doTest() throws Exception {
+
+ Point ls = window.getLocationOnScreen();
+ clicked = 0;
+ checkClick(ls.x + window.getWidth() / 2, ls.y - 5, 0);
+
+ robot.waitForIdle(2000);
+
+ ls = south.getLocationOnScreen();
+
+ Point p1 = new Point((int) (ls.x + south.getWidth() * 0.75), ls.y + south.getHeight() * 3);
+ Point p2 = new Point((int) (ls.x + south.getWidth() * 0.75), ls.y - south.getHeight() * 2);
+ Color c1 = robot.getPixelColor(p1.x, p1.y);
+ Color c2 = robot.getPixelColor(p2.x, p2.y);
+
+ checkClick(ls.x + south.getWidth() / 2, ls.y + south.getHeight() / 2, 1);
+
+ robot.waitForIdle(2000);
+
+ Color c1b = robot.getPixelColor(p1.x, p1.y);
+ Color c2b = robot.getPixelColor(p2.x, p2.y);
+
+ if (!aproximatelyEquals(c1, c1b) && !aproximatelyEquals(south.getBackground(), c1b))
+ throw new RuntimeException("Check for opaque drop down failed. Before click: " + c1 + ", after click: " + c1b + ", expected is " + south.getBackground());
+
+ if (!aproximatelyEquals(c2,c2b) && !aproximatelyEquals(south.getBackground(), c2b))
+ throw new RuntimeException("Check for opaque drop down failed. Before click: " + c2 + ", after click: " + c2b + ", expected is " + south.getBackground());
+
+ EventQueue.invokeAndWait(() -> {
+ background.dispose();
+ window.dispose();
+ });
+
+ robot.waitForIdle();
+ }
+
+ boolean aproximatelyEquals(Color c1, Color c2) {
+ return ((Math.abs(c1.getRed()-c2.getRed())/256.0 +
+ Math.abs(c1.getGreen()-c2.getGreen())/256.0 +
+ Math.abs(c1.getBlue()-c2.getBlue())/256.0)) / 3 < 0.02;
+ }
+
+ @Override
+ public void applyShape() { }
+
+
+ void checkClick(int x, int y, int flag) throws Exception {
+
+ System.out.println("Trying to click point " + x + ", " + y + ", looking for " + flag + " flag to trigger.");
+
+ clicked = 0;
+ robot.mouseMove(x, y);
+ robot.click();
+
+ for (int i = 0; i < 100; i++)
+ if ((clicked & (1 << flag)) == 0)
+ robot.delay(50);
+ else
+ break;
+
+ if ((clicked & (1 << flag)) == 0)
+ throw new RuntimeException("FAIL: Flag " + flag + " is not triggered for point " + x + ", " + y + "!");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/TranslucentWindowClick.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.awt.*;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+
+/*
+ * @test
+ * @summary Check if components present in a window set with opacity less than 1.0
+ * triggers events correctly
+ *
+ * Test Description: Check if TRANSLUCENT Translucency type is supported on the
+ * current platform. Proceed if supported. Show a window which contains some
+ * components and set with opacity less than 1.0. Another Window having a
+ * canvas component drawn with an image can be used as the background for the
+ * test window. Click on the components present in the window and check if
+ * events trigger correctly.
+ * Expected Result: The components should trigger events correctly
+ *
+ * @author mrkam
+ * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
+ * @library ../../../../lib/testlibrary
+ * @build Common ExtendedRobot
+ * @run main TranslucentWindowClick
+ */
+public class TranslucentWindowClick extends Common {
+
+ private Component south;
+ private Component center;
+ private Component north;
+
+ volatile int clicked;
+
+ public static void main(String[] args) throws Exception{
+ if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT))
+ new TranslucentWindowClick(Window.class).doTest();
+ }
+
+ public TranslucentWindowClick(Class windowClass) throws Exception {
+ super(windowClass);
+ }
+
+ @Override
+ public void initGUI() {
+ if (windowClass.equals(Frame.class)) {
+ window = new Frame();
+ ((Frame) window).setUndecorated(true);
+ } else if (windowClass.equals(Dialog.class)) {
+ window = new Dialog(background);
+ ((Dialog) window).setUndecorated(true);
+ } else {
+ window = new Window(background);
+ }
+
+ window.setPreferredSize(new Dimension(200, 200));
+ window.setLocation(2 * dl, 2 * dl);
+ window.setLayout(new BorderLayout());
+ window.setBackground(FG_COLOR);
+
+ south = new Button("South");
+ south.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) { clicked |= 1 << 2; }
+ });
+ window.add(south, BorderLayout.SOUTH);
+
+ center = new List(5);
+ center.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) { clicked |= 1 << 1; }
+ });
+ window.add(center, BorderLayout.CENTER);
+
+ north = new TextField("North");
+ north.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) { clicked |= 1 << 0; }
+ });
+ window.add(north, BorderLayout.NORTH);
+ window.setOpacity(0.2f);
+ window.pack();
+ window.setVisible(true);
+
+ System.out.println("Checking " + window.getClass().getName() + "...");
+ }
+
+ @Override
+ public void doTest() throws Exception {
+ Point ls;
+ robot.waitForIdle();
+
+ ls = north.getLocationOnScreen();
+ checkClick(ls.x + north.getWidth() / 3, ls.y + north.getHeight() / 2, 0);
+
+ ls = center.getLocationOnScreen();
+ checkClick(ls.x + center.getWidth() / 4, ls.y + center.getHeight() / 4, 1);
+
+ ls = center.getLocationOnScreen();
+ checkClick(ls.x + center.getWidth() * 3 / 4, ls.y + center.getHeight() * 3 / 4, 1);
+
+ ls = south.getLocationOnScreen();
+ checkClick(ls.x + south.getWidth() * 2 / 3, ls.y + south.getHeight() / 2, 2);
+
+ EventQueue.invokeAndWait(() -> {
+ background.dispose();
+ window.dispose();
+ });
+
+ robot.waitForIdle();
+ }
+
+ @Override
+ public void applyShape() { }
+
+ void checkClick(int x, int y, int flag) throws Exception {
+
+ System.out.println("Trying to click point " + x + ", " + y + ", looking for " + flag + " flag to trigger.");
+
+ clicked = 0;
+ robot.mouseMove(x, y);
+ robot.click();
+
+ for (int i = 0; i < 100; i++)
+ if ((clicked & (1 << flag)) == 0)
+ robot.delay(50);
+ else
+ break;
+
+ if ((clicked & (1 << flag)) == 0)
+ throw new RuntimeException("FAIL: Flag " + flag + " is not triggered for point " + x + ", " + y + "!");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/Clipboard/BasicClipboardTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.*;
+
+/*
+ * @test
+ * @summary To test the basic Clipboard functions
+ * @author Kanishk Jethi (kanishk.jethi@sun.com) area=Clipboard
+ * @run main BasicClipboardTest
+ */
+
+public class BasicClipboardTest implements ClipboardOwner {
+
+ StringSelection strSelect = new StringSelection("Transferable String Selection");
+ StringSelection strCheck;
+ String clipName = "Test Clipboard";
+ Clipboard clip = new Clipboard(clipName);
+ DataFlavor dataFlavor, testDataFlavor ;
+ DataFlavor dataFlavorArray[];
+ Object testObject;
+ String strTest = null;
+
+ public static void main (String[] args) throws Exception {
+ new BasicClipboardTest().doTest();
+ }
+
+ public void doTest() throws Exception {
+ dataFlavor = new DataFlavor(DataFlavor.javaRemoteObjectMimeType, null, this.getClass().getClassLoader());
+ // test for null return of selectBestTextFlavor if input is null or
+ // of zero length
+ testDataFlavor = DataFlavor.selectBestTextFlavor(dataFlavorArray);
+ if (testDataFlavor != null)
+ throw new RuntimeException("\n***Error in selectBestTextFlavor");
+
+ dataFlavorArray = new DataFlavor[0];
+
+ testDataFlavor = DataFlavor.selectBestTextFlavor(dataFlavorArray);
+ if (testDataFlavor != null)
+ throw new RuntimeException("\n***Error in selectBestTextFlavor");
+
+ // test for null return when there are no text flavors in array
+ dataFlavorArray = new DataFlavor[1];
+ dataFlavorArray[0] = new DataFlavor(DataFlavor.javaSerializedObjectMimeType + ";class=java.io.Serializable");
+
+ testDataFlavor = DataFlavor.selectBestTextFlavor(dataFlavorArray);
+ if (testDataFlavor != null)
+ throw new RuntimeException("\n***Error in selectBestTextFlavor");
+
+ if (clip.getName() != clipName)
+ throw new RuntimeException("\n*** Error in Clipboard.getName()");
+
+ // set the owner of the clipboard to null to check branch coverage
+ // of the setContents method
+ clip.setContents(null, null);
+
+ //set the owner of the clipboard to something valid to check branch
+ //coverage of the setContents method
+ clip.setContents(null, new BasicClipboardTest());
+
+ //set the owner of the clipboard to this to check branch coverage
+ // of the setContents method
+ clip.setContents(null, this);
+
+ //set the contents of the clipboard
+ clip.setContents(strSelect, this);
+
+ //get the contents of the clipboard
+ strCheck = (StringSelection)clip.getContents(this);
+ if (!strCheck.equals(strSelect))
+ throw new RuntimeException("\n***The contents of the clipboard are "
+ + "not the same as those that were set");
+
+ //Check if getReaderForText throws IAE when the Transferable has
+ //null TransferData
+ dataFlavor = DataFlavor.stringFlavor;
+ strSelect = new StringSelection(null);
+ try {
+ testObject = dataFlavor.getReaderForText(strSelect);
+ throw new RuntimeException("\n***Error in getReaderForText. An IAE should have been thrown");
+ } catch (IllegalArgumentException iae) {
+ // do nothing as this is expected
+ }
+
+ //Check getParameter
+ dataFlavor.setHumanPresentableName("String Flavor");
+ if (!(dataFlavor.getParameter("humanPresentableName")).equals("String Flavor"))
+ throw new RuntimeException("\n***Error in getParameter");
+
+ //Check equals
+ try {
+ if (dataFlavor.isMimeTypeEqual(strTest))
+ throw new RuntimeException("\n***Error in DataFlavor.equals(String s)");
+ } catch (NullPointerException e) {
+ //do nothing as it is expected
+ }
+
+ if (!(dataFlavor.isMimeTypeEqual(dataFlavor.getMimeType())))
+ throw new RuntimeException("\n***Error in DataFlavor.equals(String s)");
+
+ //Check isMimeTypeSerializedObject
+ if (!dataFlavorArray[0].isMimeTypeSerializedObject())
+ throw new RuntimeException("\n***Error in isMimeTypeSerializedObject()");
+ System.out.println(dataFlavorArray[0].getDefaultRepresentationClass());
+ System.out.println(dataFlavorArray[0].getDefaultRepresentationClassAsString());
+ //Check isFlavorRemoteObjectType
+ if (dataFlavor.isFlavorRemoteObjectType())
+ System.out.println("The DataFlavor is a remote object type");
+
+ //Check clone()
+ testDataFlavor = (DataFlavor)dataFlavor.clone();
+ }
+
+ public void lostOwnership (Clipboard clipboard, Transferable contents) { }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/Clipboard/GetContentsInterruptedTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.ClipboardOwner;
+import java.awt.datatransfer.StringSelection;
+import java.awt.datatransfer.Transferable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+
+/*
+ * @test
+ * @bug 4532299 4648733
+ * @summary Tests that getting clipboard contents on the interrupted thread will
+ * not cause deadlock.Also check that lostOwnership event occurs while
+ * cross-JVM interaction
+ * @author Kanishk Jethi
+ * @run main GetContentsInterruptedTest
+ */
+
+public class GetContentsInterruptedTest implements ClipboardOwner {
+
+ final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+ final Transferable transferable = new StringSelection("TEXT");
+ private final Object o = new Object();
+
+ public static void main(String args[]) throws Exception {
+ if (System.getProperty("os.name").startsWith("Mac")) {
+ System.out.println("This tests should not be run on OS X. " +
+ "See CR 7124344 for more info");
+ } else {
+ boolean subTestFlag = false;
+ for (String arg : args) {
+ if (arg.indexOf("SubTest") != -1)
+ subTestFlag = true;
+ }
+
+ if (!subTestFlag) {
+ new GetContentsInterruptedTest().performTest();
+ } else {
+ new GetContentsInterruptedTest().execute();
+ }
+ }
+ }
+
+ private void performTest() throws Exception {
+ int retCode;
+ String javaPath = System.getProperty("java.home", "");
+ String javaClasspath = System.getProperty("java.class.path", ".");
+ String command = javaPath + File.separator + "bin" +
+ File.separator + "java -classpath " + javaClasspath +
+ " GetContentsInterruptedTest SubTest";
+ System.out.println(command);
+ boolean processExit = false;
+
+ clipboard.setContents(transferable, this);
+ Process process = Runtime.getRuntime().exec(command);
+ synchronized (o) {
+ o.wait(10000);
+ }
+
+ try {
+ retCode = process.exitValue();
+ processExit = true;
+ }catch (IllegalThreadStateException e){
+ throw new RuntimeException(e);
+ }
+ System.out.println("[RESULT] : " +
+ "The sub process has cleanly exited : PASS");
+
+ System.out.println("[RESULT] : Child returned: " + retCode );
+
+ InputStream errorStream = process.getErrorStream();
+ System.out.println("========= Child process stderr ========");
+ dumpStream(errorStream);
+ System.out.println("=======================================");
+
+ InputStream processInputStream = process.getInputStream();
+ System.out.println("========= Child process output ========");
+ dumpStream(processInputStream);
+ System.out.println("=======================================");
+
+ if (!processExit) {
+ process.destroy();
+ throw new RuntimeException("[RESULT] : " +
+ "The sub process has not exited : FAIL");
+ }
+ }
+
+ /*
+ * execute is run through another instance of this class.
+ * it acquires the systemClipboard through another JVM.
+ */
+ public void execute() {
+ System.out.println("Hello world");
+ final ClipboardOwner clipboardOwner = new ClipboardOwner() {
+ public void lostOwnership(Clipboard clipboard, Transferable contents) {
+ System.exit(0);
+ }
+ };
+ clipboard.setContents(transferable, clipboardOwner);
+ synchronized (o) {
+ try {
+ o.wait();
+ } catch (InterruptedException ie) {
+ ie.printStackTrace();
+ }
+ }
+ }
+
+ public void dumpStream(InputStream in) throws IOException {
+ String tempString;
+ int count = in.available();
+ while (count > 0) {
+ byte[] b = new byte[count];
+ in.read(b);
+ tempString = new String(b);
+ if (tempString.indexOf("Exception") != -1 )
+ throw new RuntimeException("[RESULT] :" +
+ " Exception in child process : FAIL");
+ System.out.println(tempString);
+ count = in.available();
+ }
+ }
+
+ public void lostOwnership(Clipboard clip, Transferable contents) {
+ new Thread(() -> {
+ try {
+ Thread.sleep(3000);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ clipboard.getContents(null);
+ Thread.currentThread().interrupt();
+ clipboard.getContents(null);
+ clipboard.setContents(transferable, null);
+ }).start();
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/ImageTransfer/ImageTransferTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To check Whether java.awt.Image can be transferred through the
+ * system clipboard
+ * @author Jitender(jitender.singh@eng.sun.com) area=AWT
+ * @author dmitriy.ermashov@oracle.com
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main ImageTransferTest
+ */
+
+public class ImageTransferTest {
+
+ TestFrame frame1, frame2;
+ Image image1, image2;
+ DataFlavor imageFlavor;
+
+ public static void main(String[] args) throws Exception {
+ new ImageTransferTest().doTest();
+ }
+
+ class TestFrame extends Frame {
+ boolean show;
+ Image img;
+ public TestFrame(boolean show, Image img){
+ this.show = show;
+ this.img = img;
+ }
+
+ public void paint( Graphics g ){
+ if (show)
+ g.drawImage( this.img, 30, 30, this );
+ }
+ }
+
+ class TransferableObject implements Transferable, ClipboardOwner {
+
+ Object data;
+ DataFlavor[] dfs;
+
+ public TransferableObject(Object data) throws Exception {
+ Vector v = new Vector();
+ imageFlavor = new DataFlavor("image/x-java-Image;class=java.awt.Image");
+ imageFlavor.setHumanPresentableName("Java Image Flavor Object");
+
+ if( data instanceof java.awt.Image )
+ v.addElement(imageFlavor);
+
+ dfs = new DataFlavor[v.size()];
+ v.copyInto(dfs);
+
+ for (int j = 0; j < dfs.length; j++)
+ System.out.println(" in constructor flavor : " + dfs[j]);
+
+ this.data = data;
+ }
+
+ public Object getTransferData(DataFlavor flavor)
+ throws UnsupportedFlavorException,IOException {
+
+ System.out.println(" **************");
+ System.out.println(" The flavor passed to retrive the data :-" + flavor);
+ System.out.println(" The flavors supported");
+ for (int j = 0; j < dfs.length; j++)
+ System.out.println(" jitu flavor : " + dfs[j]);
+
+ System.out.println(" **************");
+
+ if(!isDataFlavorSupported(flavor))
+ throw new UnsupportedFlavorException(flavor);
+
+ if(imageFlavor.equals(flavor)){
+ if( data instanceof java.awt.Image )
+ return data;
+ }
+ return null;
+
+ }
+
+ public DataFlavor[] getTransferDataFlavors() { return dfs; }
+
+ public boolean isDataFlavorSupported(DataFlavor flavor) {
+ for (int i = 0 ; i < dfs.length; i++)
+ if (dfs[i].match(flavor)) return true;
+ return false;
+ }
+
+ public void lostOwnership(Clipboard clip,Transferable contents) {
+ System.out.println(" LostOwnership is invoked");
+ }
+ }
+
+ ImageTransferTest() throws Exception {
+ BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
+ Graphics g = img.createGraphics();
+ g.setColor(Color.WHITE);
+ g.fillRect(0, 0, 100, 100);
+ g.setColor(Color.RED);
+ g.fillRect(20, 20, 60, 60);
+ g.dispose();
+
+ image1 = img;
+ frame1 = new TestFrame(true, image1);
+ frame2 = new TestFrame(false, null);
+
+ System.out.println("Inside contrucor...");
+
+ imageFlavor = new DataFlavor("image/x-java-Image;class=java.awt.Image");
+ imageFlavor.setHumanPresentableName("Java Image Flavor Object");
+
+ frame1.setBounds(10,350,200,200);
+ frame2.setBounds(250,350,200,200);
+ frame1.setVisible(true);
+ frame2.setVisible(true);
+ frame1.repaint();
+ }
+
+ public void compareImages() {
+ if (image2 == image1)
+ System.out.println("Pasted Image is same as that one copied !");
+ else
+ if (image2 != image1)
+ throw new RuntimeException("Image retreived from the Clipboard is not the same " +
+ "image that was set to the Clipboard");
+ }
+
+
+ public void doTest() throws Exception {
+ ExtendedRobot robot = new ExtendedRobot();
+ robot.waitForIdle(2000);
+ TransferableObject imagedata = new TransferableObject(image1);
+
+ Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
+ System.out.println("copying image...");
+ if (imagedata != null) {
+ clip.setContents(imagedata, imagedata);
+ } else {
+ System.out.println("Transferable object is null");
+ }
+
+ Transferable content = clip.getContents(this);
+ if (content != null && (content.isDataFlavorSupported(imageFlavor))) {
+ System.out.println("jitu after paste" + content);
+ image2 = (Image) content.getTransferData(imageFlavor);
+ } else {
+ System.out.println("Contents of the clipboard is null");
+ }
+
+ frame2.img = image2;
+ frame2.show = true;
+ frame2.repaint();
+
+ robot.waitForIdle(2000);
+
+ compareImages();
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/Independence/IndependenceAWTTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.awt.event.*;
+import java.util.Properties;
+
+/*
+ * @test
+ * @summary To make sure that System & Primary clipboards should behave independently
+ * @author Jitender(jitender.singh@eng.sun.com) area=AWT
+ * @author dmitriy.ermashov@oracle.com
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main IndependenceAWTTest
+ */
+
+public class IndependenceAWTTest {
+
+ Frame frame;
+ Panel panel;
+ TextField tf1, tf2, tf3;
+ Clipboard sClip, pClip;
+
+ public static void main (String[] args) throws Exception {
+ new IndependenceAWTTest().doTest();
+ }
+
+ public IndependenceAWTTest() {
+
+ frame = new Frame();
+ frame.setSize(200, 200);
+
+ // This textfield will be used to update the contents of clipboards
+ tf1 = new TextField();
+ tf1.addFocusListener(new FocusAdapter() {
+ public void focusGained(FocusEvent fe) {
+ tf1.setText("Clipboards_Independance_Testing");
+ }
+ });
+
+ // TextFields to get the contents of clipboard
+ tf2 = new TextField();
+ tf3 = new TextField();
+
+ panel = new Panel();
+ panel.setLayout(new BorderLayout());
+
+ panel.add(tf2, BorderLayout.NORTH);
+ panel.add(tf3, BorderLayout.SOUTH);
+
+ frame.add(tf1, BorderLayout.NORTH);
+ frame.add(panel, BorderLayout.CENTER);
+
+ frame.setVisible(true);
+ tf1.requestFocus();
+ }
+
+ public void checkSecurity() {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm == null) {
+ System.out.println("security manager is not there");
+ getPrimaryClipboard();
+ } else {
+ sm.checkPermission(new AWTPermission("accessClipboard"));
+ getPrimaryClipboard();
+ }
+ }
+
+ // Get System Selection i.e. Primary Clipboard
+ private void getPrimaryClipboard() {
+ Properties ps = System.getProperties();
+ String operSys = ps.getProperty("os.name");
+ try {
+ pClip = Toolkit.getDefaultToolkit().getSystemSelection();
+ if (pClip == null)
+ if ((operSys.substring(0,3)).equalsIgnoreCase("Win") || operSys.toLowerCase().contains("os x"))
+ System.out.println(operSys + "Operating system does not support system selection ");
+ else
+ throw new RuntimeException("Method getSystemSelection() is returning null on X11 platform");
+ } catch(HeadlessException e) {
+ System.out.println("Headless exception thrown " + e);
+ }
+ }
+
+ // Method to get the contents of both of the clipboards
+ public void getClipboardsContent() throws Exception {
+ sClip = Toolkit.getDefaultToolkit().getSystemClipboard();
+ Transferable tp;
+ Transferable ts;
+
+ StringSelection content = new StringSelection(tf1.getText());
+ sClip.setContents(content,content);
+
+ tp = pClip.getContents(this);
+ ts = sClip.getContents(this);
+
+ // Paste the contents of System clipboard on textfield tf2 while the paste the contents of
+ // of primary clipboard on textfiled tf3
+ if ((ts != null) && (ts.isDataFlavorSupported(DataFlavor.stringFlavor))) {
+ tf2.setBackground(Color.white);
+ tf2.setForeground(Color.black);
+ tf2.setText((String) ts.getTransferData(DataFlavor.stringFlavor));
+ }
+
+ if ((tp != null) && (tp.isDataFlavorSupported(DataFlavor.stringFlavor))) {
+ tf3.setBackground(Color.white);
+ tf3.setForeground(Color.black);
+ tf3.setText((String) tp.getTransferData(DataFlavor.stringFlavor));
+ }
+ }
+
+ // Method to compare the Contents return by system & primary clipboard
+ public void compareText (boolean mustEqual) {
+ if ((tf2.getText()).equals(tf3.getText())) {
+ if (mustEqual)
+ System.out.println("Selected text & clipboard contents are same\n");
+ else
+ throw new RuntimeException("Selected text & clipboard contents are same\n");
+ } else {
+ if (mustEqual)
+ throw new RuntimeException("Selected text & clipboard contents differs\n");
+ else
+ System.out.println("Selected text & clipboard contents differs\n");
+ }
+ }
+
+ public void doTest() throws Exception {
+ checkSecurity();
+ ExtendedRobot robot = new ExtendedRobot();
+ robot.waitForIdle(1000);
+ frame.setLocation(100, 100);
+ robot.waitForIdle(1000);
+
+ if (pClip != null) {
+ Point ttf1Center = tf1.getLocationOnScreen();
+ ttf1Center.translate(tf1.getWidth()/2, tf1.getHeight()/2);
+
+ robot.glide(new Point(0, 0), ttf1Center);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardsContent();
+ compareText(true);
+
+ //Change the text selection to update the contents of primary clipboard
+ robot.mouseMove(ttf1Center);
+ robot.mousePress(MouseEvent.BUTTON1_MASK);
+ robot.delay(200);
+ robot.mouseMove(ttf1Center.x + 15, ttf1Center.y);
+ robot.mouseRelease(MouseEvent.BUTTON1_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardsContent();
+ compareText(false);
+ }
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/Independence/IndependenceSwingTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,195 @@
+/*
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.StringSelection;
+import java.awt.datatransfer.Transferable;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.InputEvent;
+import java.awt.event.MouseEvent;
+import java.util.Properties;
+
+/*
+ * @test
+ * @summary To make sure that System & Primary clipboards should behave independently
+ * @author Jitender(jitender.singh@eng.sun.com) area=AWT
+ * @author dmitriy.ermashov@oracle.com
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main IndependenceSwingTest
+ */
+
+public class IndependenceSwingTest {
+
+ JFrame frame;
+ JPanel panel;
+ JTextField tf1, tf2, tf3;
+ Clipboard sClip, pClip;
+
+ public static void main (String[] args) throws Exception {
+ new IndependenceSwingTest().doTest();
+ }
+
+ public IndependenceSwingTest() {
+
+ frame = new JFrame();
+ frame.setSize(200, 200);
+
+ // This textfield will be used to update the contents of clipboards
+ tf1 = new JTextField();
+ tf1.addFocusListener(new FocusAdapter() {
+ public void focusGained(FocusEvent fe) {
+ tf1.setText("Clipboards_Independance_Testing");
+ }
+ });
+
+ // TextFields to get the contents of clipboard
+ tf2 = new JTextField();
+ tf3 = new JTextField();
+
+ panel = new JPanel();
+ panel.setLayout(new BorderLayout());
+
+ panel.add(tf2, BorderLayout.NORTH);
+ panel.add(tf3, BorderLayout.SOUTH);
+
+ frame.add(tf1, BorderLayout.NORTH);
+ frame.add(panel, BorderLayout.CENTER);
+
+ frame.setVisible(true);
+ tf1.requestFocus();
+ }
+
+ public void checkSecurity() {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm == null) {
+ System.out.println("security manager is not there");
+ getPrimaryClipboard();
+ } else {
+ sm.checkPermission(new AWTPermission("accessClipboard"));
+ getPrimaryClipboard();
+ }
+ }
+
+ // Get System Selection i.e. Primary Clipboard
+ private void getPrimaryClipboard() {
+ Properties ps = System.getProperties();
+ String operSys = ps.getProperty("os.name");
+ try {
+ pClip = Toolkit.getDefaultToolkit().getSystemSelection();
+ if (pClip == null)
+ if ((operSys.substring(0,3)).equalsIgnoreCase("Win") || operSys.toLowerCase().contains("os x"))
+ System.out.println(operSys + "Operating system does not support system selection ");
+ else
+ throw new RuntimeException("Method getSystemSelection() is returning null on X11 platform");
+ } catch(HeadlessException e) {
+ System.out.println("Headless exception thrown " + e);
+ }
+ }
+
+ // Method to get the contents of both of the clipboards
+ public void getClipboardsContent() throws Exception {
+ sClip = Toolkit.getDefaultToolkit().getSystemClipboard();
+ Transferable tp;
+ Transferable ts;
+
+ StringSelection content = new StringSelection(tf1.getText());
+ sClip.setContents(content,content);
+
+ tp = pClip.getContents(this);
+ ts = sClip.getContents(this);
+
+ // Paste the contents of System clipboard on textfield tf2 while the paste the contents of
+ // of primary clipboard on textfiled tf3
+ if ((ts != null) && (ts.isDataFlavorSupported(DataFlavor.stringFlavor))) {
+ tf2.setBackground(Color.white);
+ tf2.setForeground(Color.black);
+ tf2.setText((String) ts.getTransferData(DataFlavor.stringFlavor));
+ }
+
+ if ((tp != null) && (tp.isDataFlavorSupported(DataFlavor.stringFlavor))) {
+ tf3.setBackground(Color.white);
+ tf3.setForeground(Color.black);
+ tf3.setText((String) tp.getTransferData(DataFlavor.stringFlavor));
+ }
+ }
+
+ // Method to compare the Contents return by system & primary clipboard
+ public void compareText (boolean mustEqual) {
+ if ((tf2.getText()).equals(tf3.getText())) {
+ if (mustEqual)
+ System.out.println("Selected text & clipboard contents are same\n");
+ else
+ throw new RuntimeException("Selected text & clipboard contents are same\n");
+ } else {
+ if (mustEqual)
+ throw new RuntimeException("Selected text & clipboard contents differs\n");
+ else
+ System.out.println("Selected text & clipboard contents differs\n");
+ }
+ }
+
+ public void doTest() throws Exception {
+ checkSecurity();
+ ExtendedRobot robot = new ExtendedRobot();
+ robot.waitForIdle(1000);
+ frame.setLocation(100, 100);
+ robot.waitForIdle(1000);
+
+ if (pClip != null) {
+ Point ttf1Center = tf1.getLocationOnScreen();
+ ttf1Center.translate(tf1.getWidth()/2, tf1.getHeight()/2);
+
+ robot.glide(new Point(0, 0), ttf1Center);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardsContent();
+ compareText(true);
+
+ //Change the text selection to update the contents of primary clipboard
+ robot.mouseMove(ttf1Center);
+ robot.mousePress(MouseEvent.BUTTON1_MASK);
+ robot.delay(200);
+ robot.mouseMove(ttf1Center.x + 15, ttf1Center.y);
+ robot.mouseRelease(MouseEvent.BUTTON1_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardsContent();
+ compareText(false);
+ }
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/AddFlavorForNativeTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method
+ * addFlavorForUnencodedNative(String nat, DataFlavor flav)
+ * with valid natives and DataFlavors. Specifically test for
+ * adding new mappings, one-way and two-way, and to update
+ * existing mappings.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main AddFlavorForNativeTest
+ */
+
+public class AddFlavorForNativeTest {
+
+ SystemFlavorMap flavorMap;
+ Vector comp1, comp2, comp3;
+ Hashtable hash;
+ int hashSize;
+
+ String test_native;
+ String[] test_natives_set;
+ DataFlavor test_flavor1, test_flavor2, test_flavor3, test_flavor4;
+ DataFlavor[] test_flavors_set1, test_flavors_set2;
+
+ public static void main(String[] args) throws Exception {
+ new AddFlavorForNativeTest().doTest();
+ }
+
+ public void doTest() throws Exception {
+ // Initialize DataFlavors and arrays used for test data
+ initMappings();
+
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get all the native strings and preferred DataFlavor mappings
+ hash = new Hashtable(flavorMap.getFlavorsForNatives(null));
+ hashSize = hash.size();
+
+ // Setup One-way Mappings
+ System.out.println("One-way Mappings Test");
+ flavorMap.addFlavorForUnencodedNative(test_native, test_flavor1);
+ flavorMap.addFlavorForUnencodedNative(test_native, test_flavor2);
+
+ // Confirm mapping with getFlavorsForNative
+ comp1 = new Vector(Arrays.asList(test_flavors_set1));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native));
+
+ if ( !comp1.equals(comp2)) {
+ throw new RuntimeException("\n*** After setting up one-way mapping" +
+ "\nwith addFlavorForUnencodedNative(String nat, DataFlavor flav)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("One-way: Test Passes");
+
+ // Setup Two-way Mapping
+ System.out.println("Two-way Mappings Test");
+ flavorMap.addUnencodedNativeForFlavor(test_flavor1, test_native);
+ flavorMap.addUnencodedNativeForFlavor(test_flavor2, test_native);
+
+ // Confirm mapping with getNativesForFlavor
+ comp1 = new Vector(Arrays.asList(test_natives_set));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flavor1));
+ comp3 = new Vector(flavorMap.getNativesForFlavor(test_flavor2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith addUnencodedNativeForFlavor(DataFlavor flav, String nat)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (String native): Test Passes");
+
+ // Check first native mapping
+ comp1 = new Vector(Arrays.asList(test_flavors_set1));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native));
+
+ if ( !comp1.equals(comp2)) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith addFlavorForUnencodedNative(String nat, DataFlavor flav)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (DataFlavor): Test Passes");
+
+ // Modify an existing mapping test
+ System.out.println("Modify Existing Mappings Test");
+ flavorMap.addFlavorForUnencodedNative(test_native, test_flavor3);
+ flavorMap.addFlavorForUnencodedNative(test_native, test_flavor4);
+
+ // Confirm mapping with getFlavorsForNative
+ comp1 = new Vector(Arrays.asList(test_flavors_set2));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native));
+
+ if ( !comp1.equals(comp2)) {
+ throw new RuntimeException("\n*** After modifying an existing mapping" +
+ "\nwith addFlavorForUnencodedNative(String nat, DataFlavor flav)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\nupdated mappings.");
+ } else
+ System.out.println("Modify Existing Mappings: Test Passes");
+ }
+
+ public void initMappings() throws Exception {
+ //create String natives
+ test_native = "TEST1";
+
+ test_flavor1 = new DataFlavor(Class.forName("java.awt.Label"), "test1");
+ test_flavor2 = new DataFlavor(Class.forName("java.awt.Button"), "test2");
+ test_flavor3 = new DataFlavor(Class.forName("java.awt.Checkbox"), "test3");
+ test_flavor4 = new DataFlavor(Class.forName("java.awt.List"), "test4");
+
+ //create and initialize DataFlavor arrays
+ test_flavors_set1 = new DataFlavor[] {test_flavor1, test_flavor2};
+ test_flavors_set2 = new DataFlavor[] {test_flavor1, test_flavor2, test_flavor3, test_flavor4};
+
+ //create and initialize String native arrays
+ test_natives_set = new String[] {test_native};
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/AddFlavorTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.awt.datatransfer.DataTransferer;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.*;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method:
+ * addFlavorForUnencodedNative(String nat, DataFlavor flav)
+ * with valid natives and DataFlavors. This stress test will
+ * define numerous mappings of valid String natives and
+ * DataFlavors. The mappings will be verified by examining
+ * that all entries are present, and order is maintained.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @author dmitriy.ermashov@oracle.com
+ * @run main AddFlavorTest
+ */
+
+public class AddFlavorTest {
+
+ SystemFlavorMap flavorMap;
+ Hashtable<String, List<DataFlavor>> hashVerify;
+
+ public static void main (String[] args) throws Exception {
+ new AddFlavorTest().doTest();
+ }
+
+ void doTest() throws Exception {
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Test addFlavorForUnencodedNative(String nat, DataFlavor flav);
+ //
+ // Enumerate through all the system defined String natives,
+ // and for each String native, define it again to the SystemFlavorMap
+ // with a slightly modified String native (name).
+ //
+ // As a list of DataFlavors will be returned for each String native,
+ // the method addFlavorForUnencodedNative will be called for each
+ // DataFlavor in the list.
+ hashVerify = new Hashtable();
+
+ for (String key : flavorMap.getFlavorsForNatives(null).keySet()) {
+ Set<DataFlavor> flavorsSet = new HashSet<>(flavorMap.getFlavorsForNative(key));
+ // construct a unique String native
+ key = key.concat("TEST");
+
+ for (DataFlavor element : flavorsSet)
+ flavorMap.addFlavorForUnencodedNative(key, element);
+
+ // This part is valid only for X-based graphical systems
+ if (!System.getProperty("os.name").startsWith("Win") && !System.getProperty("os.name").startsWith("Mac") ) {
+ if (key.contains("/")) {
+ Set<DataFlavor> fls = DataTransferer.getInstance().getPlatformMappingsForNative(key);
+ flavorsSet.addAll(fls);
+ if (!fls.isEmpty() && key.startsWith("text/"))
+ flavorsSet.addAll(convertMimeTypeToDataFlavors(key));
+ }
+ }
+ hashVerify.put(key, new Vector(flavorsSet));
+ }
+
+ // Assertions: After establishing "new" mappings, verify that the defined
+ // DataFlavors can be retrieved and that the List is preserved.
+ verifyNewMappings();
+ }
+
+ // Verify getFlavorsForNative(String nat) is returning the correct list
+ // of DataFlavors (for the new mappings).
+ void verifyNewMappings() {
+ // Enumerate through all natives
+ System.out.println("*** native size = " + hashVerify.size());
+ for (Enumeration e = hashVerify.keys() ; e.hasMoreElements() ;) {
+ String key = (String)e.nextElement();
+ compareFlavors(hashVerify.get(key), flavorMap.getFlavorsForNative(key), key);
+ compareFlavors(flavorMap.getFlavorsForNative(key), hashVerify.get(key), key);
+ }
+ }
+
+ void compareFlavors(List<DataFlavor> flavors1, List<DataFlavor> flavors2, String key){
+ DataTransferer.DataFlavorComparator comparator = new DataTransferer.DataFlavorComparator();
+ for (DataFlavor flavor1 : flavors1) {
+ boolean result = false;
+ for (DataFlavor flavor2 : flavors2) {
+ if (comparator.compare(flavor1, flavor2) == 0)
+ result = true;
+ }
+ if (!result)
+ throw new RuntimeException("\n*** Error in verifyNewMappings()" +
+ "\nmethod1: addFlavorForUnencodedNative(String nat, DataFlavor flav)" +
+ "\nmethod2: List getFlavorsForNative(String nat)" +
+ "\nString native: " + key +
+ "\nAfter adding several mappings with addFlavorForUnencodedNative," +
+ "\nthe returned list did not match the mappings that were added." +
+ "\nEither the mapping was not included in the list, or the order was incorect.");
+ }
+
+ }
+
+ Set<DataFlavor> convertMimeTypeToDataFlavors(String baseType) throws Exception {
+ Set<DataFlavor> result = new LinkedHashSet<>();
+
+ for (String charset : DataTransferer.standardEncodings()) {
+ for (String txtClass : new String[]{"java.io.InputStream", "java.nio.ByteBuffer", "\"[B\""}) {
+ String mimeType = baseType + ";charset=" + charset + ";class=" + txtClass;
+
+ if ("text/html".equals(baseType)) {
+ for (String documentType : new String[]{"all", "selection", "fragment"})
+ result.add(new DataFlavor(mimeType + ";document=" + documentType));
+ } else {
+ DataFlavor df = new DataFlavor(mimeType);
+ if (df.equals(DataFlavor.plainTextFlavor))
+ df = DataFlavor.plainTextFlavor;
+ result.add(df);
+ }
+ }
+ }
+ return result;
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/AddNativeForFlavorTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method
+ * addUnencodedNativeForFlavor(DataFlavor flav, String nat)
+ * with valid natives and DataFlavors. Specifically test for
+ * adding new mappings, one-way and two-way, and to update
+ * existing mappings.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main AddNativeForFlavorTest
+ */
+
+public class AddNativeForFlavorTest {
+
+ SystemFlavorMap flavorMap;
+ Vector comp1, comp2, comp3;
+ Hashtable hash;
+ int hashSize;
+
+ String test_native1, test_native2, test_native3, test_native4;
+ String[] test_natives_set1, test_natives_set2;
+ DataFlavor test_flav;
+ DataFlavor[] test_flavors_set;
+
+ public static void main(String[] args) throws Exception {
+ new AddNativeForFlavorTest().doTest();
+ }
+
+ public void doTest() throws Exception {
+ // Initialize DataFlavors and arrays used for test data
+ initMappings();
+
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get all the native strings and preferred DataFlavor mappings
+ hash = new Hashtable(flavorMap.getFlavorsForNatives(null));
+ hashSize = hash.size();
+
+ // Setup One-way Mappings
+ System.out.println("One-way Mappings Test");
+ flavorMap.addUnencodedNativeForFlavor(test_flav, test_native1);
+ flavorMap.addUnencodedNativeForFlavor(test_flav, test_native2);
+
+ // Confirm mapping with getNativesForFlavor
+ comp1 = new Vector(Arrays.asList(test_natives_set1));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flav));
+
+ if ( !comp1.equals(comp2)) {
+ throw new RuntimeException("\n*** After setting up one-way mapping" +
+ "\nwith addUnencodedNativeForFlavor(DataFlavor flav, String nat)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("One-way: Test Passes");
+
+ // Setup Two-way Mapping
+ System.out.println("Two-way Mappings Test");
+ flavorMap.addFlavorForUnencodedNative(test_native1, test_flav);
+ flavorMap.addFlavorForUnencodedNative(test_native2, test_flav);
+
+ // Confirm mapping with getFlavorsForNative
+ comp1 = new Vector(Arrays.asList(test_flavors_set));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native1));
+ comp3 = new Vector(flavorMap.getFlavorsForNative(test_native2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith addFlavorForUnencodedNative(String nat, DataFlavor flav)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (DataFlavor): Test Passes");
+
+ // Check first native mapping
+ comp1 = new Vector(Arrays.asList(test_natives_set1));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flav));
+
+ if ( !comp1.equals(comp2)) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith addUnencodedNativeForFlavor(DataFlavor flav, String nat)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (String native): Test Passes");
+
+ // Modify an existing mapping test
+ System.out.println("Modify Existing Mappings Test");
+ flavorMap.addUnencodedNativeForFlavor(test_flav, test_native3);
+ flavorMap.addUnencodedNativeForFlavor(test_flav, test_native4);
+
+ // Confirm mapping with getNativesForFlavor
+ comp1 = new Vector(Arrays.asList(test_natives_set2));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flav));
+
+ if ( !comp1.equals(comp2)) {
+ throw new RuntimeException("\n*** After modifying an existing mapping" +
+ "\nwith addUnencodedNativeForFlavor(DataFlavor flav, String nat)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\nupdated mappings.");
+ }
+ else
+ System.out.println("Modify Existing Mappings: Test Passes");
+
+ }
+
+ public void initMappings() throws Exception {
+ //create String natives
+ test_native1 = "TEST1";
+ test_native2 = "TEST2";
+ test_native3 = "TEST3";
+ test_native4 = "TEST4";
+
+ test_flav = new DataFlavor(Class.forName("java.awt.Label"), "test1");
+
+ //create and initialize DataFlavor arrays
+ test_flavors_set = new DataFlavor[] {test_flav};
+
+ //create and initialize String native arrays
+ test_natives_set1 = new String[] {test_native1, test_native2};
+ test_natives_set2 = new String[] {test_native1, test_native2, test_native3, test_native4};
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/AddNativeTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.*;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method:
+ * addUnencodedNativeForFlavor(DataFlavor flav, String nat)
+ * with valid natives and DataFlavors. This stress test will
+ * define numerous mappings of valid String natives and
+ * DataFlavors. The mappings will be verified by examining
+ * that all entries are present.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main AddNativeTest
+ */
+
+public class AddNativeTest {
+
+ SystemFlavorMap flavorMap;
+ Hashtable hashVerify;
+
+ Map mapFlavors;
+ Map mapNatives;
+
+ Hashtable hashFlavors;
+ Hashtable hashNatives;
+
+ public static void main(String[] args) {
+ new AddNativeTest().doTest();
+ }
+
+ public void doTest() {
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get SystemFlavorMap Maps of String Natives and DataFlavors
+ mapFlavors = flavorMap.getNativesForFlavors(null);
+ mapNatives = flavorMap.getFlavorsForNatives(null);
+
+ hashFlavors = new Hashtable(mapFlavors);
+ hashNatives = new Hashtable(mapNatives);
+
+ // Test addUnencodedNativeForFlavor(DataFlavor flav, String nat);
+ //
+ // Enumerate through all the system defined DataFlavors,
+ // and for each DataFlavor, define it again to the SystemFlavorMap
+ // with a slightly modified Mime Type.
+ //
+ // As a list of String natives will be returned for each DataFlavor,
+ // the method addUnencodedNativeForFlavor will be called for each
+ // String native in the list.
+ //
+ // For verification, a seperate Hashtable (Map) will be maintained with changes.
+ DataFlavor key;
+ hashVerify = new Hashtable();
+
+ for (Enumeration e = hashFlavors.keys() ; e.hasMoreElements() ;) {
+ key = (DataFlavor)e.nextElement();
+
+ java.util.List listNatives = flavorMap.getNativesForFlavor(key);
+ Vector vectorNatives = new Vector(listNatives);
+
+ // Construct a new DataFlavor from an existing DataFlavor's MimeType
+ // Example:
+ // Original MimeType: "text/plain; class=java.io.Reader; charset=Unicode"
+ // Modified MimeType: "text/plain-TEST; class=java.io.Reader; charset=Unicode"
+
+ StringBuffer mimeType = new StringBuffer(key.getMimeType());
+ mimeType.insert(mimeType.indexOf(";"),"-TEST");
+
+ DataFlavor testFlavor = new DataFlavor(mimeType.toString(), "Test DataFlavor");
+
+ for (ListIterator i = vectorNatives.listIterator() ; i.hasNext() ;) {
+ String element = (String)i.next();
+ flavorMap.addUnencodedNativeForFlavor(testFlavor, element);
+ }
+
+ //Added following 4 lines - Aruna Samji - 07/22/2003
+ Vector existingNatives = new Vector(flavorMap.getNativesForFlavor(testFlavor));
+ existingNatives.addAll(vectorNatives);
+ vectorNatives = existingNatives;
+ hashVerify.put(testFlavor, vectorNatives);
+ }
+
+ // Assertions: After establishing "new" mappings, verify that the defined
+ // DataFlavors can be retrieved.
+ verifyNewMappings();
+ }
+
+ // Verify getFlavorsForNative(String nat) is returning the correct list
+ // of DataFlavors (for the new mappings).
+ public boolean verifyNewMappings() {
+ boolean result = true;
+
+ // Enumerate through all DataFlavors
+ for (Enumeration e = hashVerify.keys() ; e.hasMoreElements() ;) {
+ DataFlavor key = (DataFlavor)e.nextElement();
+
+ java.util.List listNatives = flavorMap.getNativesForFlavor(key);
+ Vector vectorNatives = new Vector(listNatives);
+
+ // Compare the list of Natives
+ //Next line changed by Kanishk to comply with bug 4696522
+ //if ( !vectorNatives.equals((Vector)hashVerify.get(key))) {
+ if ( !(vectorNatives.containsAll((Vector)hashVerify.get(key)) && ((Vector)hashVerify.get(key)).containsAll(vectorNatives))) {
+ throw new RuntimeException("\n*** Error in verifyNewMappings()" +
+ "\nmethod1: addUnencodedNativeForFlavor(DataFlavor flav, String nat)" +
+ "\nmethod2: List getNativesForFlavor(DataFlavor flav)" +
+ "\nDataFlavor: " + key.getMimeType() +
+ "\nAfter adding several mappings with addUnencodedNativeForFlavor," +
+ "\nthe returned list did not match the mappings that were added." +
+ "\nThe mapping was not included in the list.");
+ }
+ }
+ System.out.println("*** DataFlavor size = " + hashVerify.size());
+ System.out.println("*** verifyNewMappings result: " + result + "\n");
+ return result;
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/GetFlavorsForNewNativeTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method
+ * getFlavorsForNative(String nat)
+ * with unknown String natives. Specifically test for
+ * unknown Unencoded String native in which an empty list is
+ * returned, and with unknown Encoded String native where
+ * two-way mapping should be established.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main GetFlavorsForNewNativeTest
+ */
+
+public class GetFlavorsForNewNativeTest {
+
+ SystemFlavorMap flavorMap;
+ Vector comp1, comp2, comp3, comp4;
+ Hashtable hash;
+ int hashSize;
+
+ String test_native1, test_encoded;
+ DataFlavor test_flavor1, test_flavor2;
+ String[] test_natives_set;
+ DataFlavor[] test_flavors_set;
+
+ public static void main (String[] args) throws Exception {
+ new GetFlavorsForNewNativeTest().doTest();
+ }
+
+ public void doTest() throws Exception {
+ // Initialize DataFlavors and arrays used for test data
+ initMappings();
+
+ flavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get all the native strings and preferred DataFlavor mappings
+ hash = new Hashtable(flavorMap.getFlavorsForNatives(null));
+ hashSize = hash.size();
+
+ // GetFlavorsForNative using Unencoded Native
+ //
+ // If a new Unencoded native is specified as a parameter, the String
+ // native should be ignored and no mapping established.
+ System.out.println("GetFlavorsForNative using Unencoded Native Test");
+
+ comp1 = new Vector(flavorMap.getFlavorsForNative(test_native1));
+
+ if (comp1.size() != 0) {
+ throw new RuntimeException("\n*** After passing a new Unencoded native" +
+ "\nwith getFlavorsForNative(String nat)" +
+ "\nthe String native should be ignored and no mapping established.");
+ } else
+ System.out.println("GetFlavorsForNative using Unencoded Native Test: Test Passes");
+
+
+ // GetFlavorsForNative using Encoded Native (verify 2-way mapping)
+ //
+ // If a new Encoded native is specified, the method should establish a mapping
+ // in both directions between specified native and DataFlavor whose MIME type
+ // is a decoded version of the native.
+ System.out.println("GetFlavorsForNative using Encoded Native Test");
+
+ comp1 = new Vector(Arrays.asList(test_flavors_set));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_encoded));
+
+ comp3 = new Vector(Arrays.asList(test_natives_set));
+ comp4 = new Vector(flavorMap.getNativesForFlavor(test_flavor2));
+
+ if (!comp1.equals(comp2) || !comp3.equals(comp4)) {
+ throw new RuntimeException("\n*** After passing a new Encoded native" +
+ "\nwith getFlavorsForNative(String nat)" +
+ "\nthe mapping in both directions was not established.");
+ } else
+ System.out.println("GetFlavorsForNative using Encoded Native: Test Passes");
+ }
+
+ public void initMappings() throws Exception {
+ //initialize mapping variables used in this test
+ //create an Unencoded String native
+ test_native1 = "TEST1";
+
+ //create a DataFlavor from Button class
+ test_flavor1 = new DataFlavor(Class.forName("java.awt.Button"), "Button");
+
+ //create an Encoded String native using Button class MIME Type
+ String buttonMIME = test_flavor1.getMimeType();
+ test_encoded = SystemFlavorMap.encodeJavaMIMEType(buttonMIME);
+
+ //create a DataFlavor from the Encoded String native
+ test_flavor2 = SystemFlavorMap.decodeDataFlavor(test_encoded);
+
+ //create and initialize DataFlavor arrays
+ test_flavors_set = new DataFlavor[] {test_flavor2};
+
+ //create and initialize String native arrays
+ test_natives_set = new String[] {test_encoded};
+ }
+
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/GetNativesForNewFlavorTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method
+ * getNativesForFlavor(DataFlavor flav)
+ * with unknown DataFlavor. Specifically test for
+ * passing an unknown DataFlavor where two-way mapping
+ * should be established.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main GetNativesForNewFlavorTest
+ */
+
+public class GetNativesForNewFlavorTest {
+
+ SystemFlavorMap flavorMap;
+ Vector comp1, comp2, comp3, comp4;
+ Hashtable hash;
+ int hashSize;
+
+ String test_encoded;
+ DataFlavor test_flavor1, test_flavor2;
+ String[] test_natives_set;
+ DataFlavor[] test_flavors_set;
+
+ public static void main (String[] args) throws Exception {
+ new GetNativesForNewFlavorTest().doTest();
+ }
+
+ public void doTest() throws Exception {
+ // Initialize DataFlavors and arrays used for test data
+ initMappings();
+
+ boolean passed = true;
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get all the native strings and preferred DataFlavor mappings
+ hash = new Hashtable(flavorMap.getFlavorsForNatives(null));
+ hashSize = hash.size();
+
+ // GetNativesForFlavor using unknown DataFlavor (verify 2-way mapping)
+ //
+ // If a new DataFlavor is specified, the method should establish a mapping
+ // in both directions between specified DataFlavor and an encoded
+ // version of its MIME type as its native.
+ System.out.println("GetNativesForFlavor using new DataFlavor");
+
+ comp1 = new Vector(Arrays.asList(test_natives_set));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flavor1));
+
+ comp3 = new Vector(Arrays.asList(test_flavors_set));
+ comp4 = new Vector(flavorMap.getFlavorsForNative(test_encoded));
+
+ if ( !comp1.equals(comp2) || !comp3.equals(comp4) ) {
+ throw new RuntimeException("\n*** After passing a new DataFlavor" +
+ "\nwith getNativesForFlavor(DataFlavor flav)" +
+ "\nthe mapping in both directions was not established.");
+ }
+ else
+ System.out.println("GetNativesForFlavor using new DataFlavor: Test Passes");
+ }
+
+ public void initMappings() throws Exception {
+ //initialize mapping variables used in this test
+ //create a DataFlavor from Button class
+ test_flavor1 = new DataFlavor(Class.forName("java.awt.Button"), "Button");
+
+ //create an Encoded String native using Button class MIME Type
+ String buttonMIME = test_flavor1.getMimeType();
+ test_encoded = SystemFlavorMap.encodeJavaMIMEType(buttonMIME);
+
+ //create a DataFlavor from the Encoded String native
+ test_flavor2 = SystemFlavorMap.decodeDataFlavor(test_encoded);
+
+ //create and initialize DataFlavor arrays
+ test_flavors_set = new DataFlavor[] {test_flavor1};
+
+ //create and initialize String native arrays
+ test_natives_set = new String[] {test_encoded};
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/InvalidMapArgumentsTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+
+/*
+ * @test
+ * @summary To check for error handling with new Clipboard/SystemFlavorMap
+ * methods, and insure that the appropriate exceptions are being thrown.
+ * Specifically check for null variables in the methods:
+ * - addFlavorForUnencodedNative(String nat, DataFlavor flav)
+ * - addUnencodedNativeForFlavor(DataFlavor flav, String nat)
+ * - setNativesForFlavor(DataFlavor flav, String[] natives)
+ * - setFlavorsForNative(String nat, DataFlavor[] flavors)
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main InvalidMapArgumentsTest
+ */
+
+public class InvalidMapArgumentsTest {
+
+ SystemFlavorMap flavorMap;
+ String test_nat;
+ String[] test_natives;
+ DataFlavor test_flav;
+ DataFlavor[] test_flavors;
+
+ public static void main (String[] args){
+ new InvalidMapArgumentsTest().doTest();
+ }
+
+ public void doTest (){
+ //Get things going. Request focus, set size, et cetera
+ initMappings();
+
+ // Test for combinations of null values for
+ // addFlavorForUnencodedNative(String nat, DataFlavor flav)
+ addFlavorForUnencodedNativeTest(null, null, "both String nat and DataFlavor flav set to null. ");
+ addFlavorForUnencodedNativeTest(null, test_flav, "String nat set to null. ");
+ addFlavorForUnencodedNativeTest(test_nat, null, "DataFlavor flav set to null. ");
+
+
+ // Test for combinations of null values for
+ // addUnencodedNativeForFlavor(DataFlavor flav, String nat)
+ addUnencodedNativeForFlavorTest(null, null, "both DataFlavor flav and String nat set to null. ");
+ addUnencodedNativeForFlavorTest(null, test_nat, "DataFlavor flav set to null. ");
+ addUnencodedNativeForFlavorTest(test_flav, null, "String nat set to null. ");
+
+
+ // Test for combinations of null values for
+ // setNativesForFlavor(DataFlavor flav, String[] natives)
+ setNativesForFlavorTest(null, null, "both DataFlavor flav and String[] natives set to null. ");
+ setNativesForFlavorTest(null, test_natives, "DataFlavor flav set to null. ");
+ setNativesForFlavorTest(test_flav, null, "String[] natives set to null. ");
+
+
+ // Test for combinations of null values for
+ // setFlavorsForNative(String nat, DataFlavor[] flavors)
+ setFlavorsForNativeTest(null, null, "both String nat and DataFlavor[] flavors set to null. ");
+ setFlavorsForNativeTest(null, test_flavors, "String nat set to null. ");
+ setFlavorsForNativeTest(test_nat, null, "DataFlavor[] flavors set to null. ");
+ }
+
+ public void initMappings() {
+ //initialize mapping variables used in this test
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ //create a DataFlavor with valid parameters (mimeType, humanPresentableName)
+ test_flav = new DataFlavor("text/plain; charset=ascii","ASCII Flavor");
+
+ //create a String native
+ test_nat = "TEXT_TEST";
+
+ //create a DataFlavor array
+ test_flavors = new DataFlavor[] {test_flav};
+
+ //create a String native array
+ test_natives = new String[] {test_nat};
+ }
+
+ public void setNativesForFlavorTest(DataFlavor flav, String[] natives, String errmsg) {
+ try{
+ flavorMap.setNativesForFlavor(flav, natives);
+ throw new RuntimeException("NullPointerException is not thrown for method "+
+ "setNativesForFlavor with "+errmsg);
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void setFlavorsForNativeTest(String nat, DataFlavor[] flavors, String errmsg) {
+ try{
+ flavorMap.setFlavorsForNative(nat, flavors);
+ throw new RuntimeException("NullPointerException is not thrown for method "+
+ "setFlavorsForNative with "+errmsg);
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void addFlavorForUnencodedNativeTest(String nat, DataFlavor flav, String errmsg) {
+ try{
+ flavorMap.addFlavorForUnencodedNative(nat, flav);
+ throw new RuntimeException("NullPointerException is not thrown for method "+
+ "addFlavorForUnencodedNative with "+errmsg);
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void addUnencodedNativeForFlavorTest(DataFlavor flav, String nat, String errmsg) {
+ try{
+ flavorMap.addUnencodedNativeForFlavor(flav, nat);
+ throw new RuntimeException("NullPointerException is not thrown for method "+
+ "addUnencodedNativeForFlavor with "+errmsg);
+ } catch (NullPointerException e) {
+ }
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/ManyFlavorMapTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.*;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap methods
+ * List getFlavorsForNative(String nat)
+ * List getNativesForFlavor(DataFlavor flav)
+ * with valid natives and DataFlavors, including null.
+ * This test will verify that the returned mappings
+ * include all entries and that the correct order is
+ * maintained.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main ManyFlavorMapTest
+ */
+
+public class ManyFlavorMapTest {
+
+ SystemFlavorMap flavorMap;
+
+ Map mapFlavors;
+ Map mapNatives;
+
+ Hashtable hashFlavors;
+ Hashtable hashNatives;
+
+ public static void main (String[] args) {
+ new ManyFlavorMapTest().doTest();
+ }
+
+ public void doTest() {
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get SystemFlavorMap Maps of String Natives and DataFlavors
+ mapFlavors = flavorMap.getNativesForFlavors(null);
+ mapNatives = flavorMap.getFlavorsForNatives(null);
+
+ hashFlavors = new Hashtable(mapFlavors);
+ hashNatives = new Hashtable(mapNatives);
+
+ // Assertion: Verify getNativesForFlavors(null) is returning the full list
+ // of String Native entries
+ List listNatives = flavorMap.getNativesForFlavor(null);
+ verifyListAllNativeEntries(listNatives);
+
+ // Assertion: Verify getFlavorsForNatives(null) is returning the full list
+ // of DataFlavor entries
+ List listFlavors = flavorMap.getFlavorsForNative(null);
+ verifyListAllDataFlavorEntries(listFlavors);
+
+ // Assertion: Verify getNativesForFlavor(DataFlavor flav) is returning the list
+ // of Native Strings (for all supported DataFlavors)
+ //
+ // Verify that the first list item is the most preferred Native
+ verifyListNativeEntries();
+
+ // Assertion: Verify getFlavorsForNative(String nat) is returning the list
+ // of DataFlavors(for all supported natives)
+ //
+ // Verify that the first list item is the most preferred DataFlavor
+ verifyListDataFlavorEntries();
+ }
+
+ // Verify getFlavorsForNative(String nat) is returning the list
+ // of DataFlavors(for all supported natives)
+ public void verifyListDataFlavorEntries() {
+ // Enumerate through all natives
+ for (Enumeration e = hashNatives.keys() ; e.hasMoreElements() ;) {
+ String key = (String)e.nextElement();
+
+ // SystemFlavorMap preferred value
+ DataFlavor value = (DataFlavor)hashNatives.get(key);
+
+ java.util.List listFlavors = flavorMap.getFlavorsForNative(key);
+ Vector vectorFlavors = new Vector(listFlavors);
+
+ // First element should be preferred value
+ DataFlavor prefFlavor = (DataFlavor)vectorFlavors.firstElement();
+ if ( value != prefFlavor ) {
+ throw new RuntimeException("\n*** Error in verifyListDataFlavorEntries()" +
+ "\nAPI Test: List getFlavorsForNative(String nat)" +
+ "\native: " + key +
+ "\nSystemFlavorMap preferred native: " + value.getMimeType() +
+ "\nList first entry: " + prefFlavor.getMimeType() +
+ "\nTest failed because List first entry does not match preferred");
+ }
+ }
+ System.out.println("*** native size = " + hashNatives.size());
+ }
+
+ // Verify getNativesForFlavor(DataFlavor flav) is returning the list
+ // of Native Strings (for all supported DataFlavors)
+ public void verifyListNativeEntries() {
+ // Enumerate through all DataFlavors
+ for (Enumeration e = hashFlavors.keys() ; e.hasMoreElements() ;) {
+ DataFlavor key = (DataFlavor)e.nextElement();
+
+ // SystemFlavorMap preferred value
+ String value = (String)hashFlavors.get(key);
+
+ java.util.List listNatives = flavorMap.getNativesForFlavor(key);
+ Vector vectorNatives = new Vector(listNatives);
+
+ // First element should be preferred value
+ String prefNative = (String)vectorNatives.firstElement();
+ if ( value != prefNative ) {
+ throw new RuntimeException("\n*** Error in verifyListNativeEntries()" +
+ "\nAPI Test: List getNativesForFlavor(DataFlavor flav)" +
+ "\nDataFlavor: " + key.getMimeType() +
+ "\nSystemFlavorMap preferred native: " + value +
+ "\nList first entry: " + prefNative +
+ "\nTest failed because List first entry does not match preferred");
+ }
+ }
+ System.out.println("*** DataFlavor size = " + hashFlavors.size());
+ }
+
+ // Compare List of Natives with list from SystemFlavorMap
+ //
+ // Verification will be done by comparing the two results as sets
+ public void verifyListAllNativeEntries(java.util.List listNatives) {
+
+ HashSet hashSetMap = new HashSet(mapNatives.keySet());
+ HashSet hashSetList = new HashSet(listNatives);
+
+ System.out.println("*** hashSetMap size = " + hashSetMap.size());
+ System.out.println("*** hashSetList size = " + hashSetList.size());
+
+ if (!hashSetMap.equals(hashSetList)) {
+ throw new RuntimeException("\n*** Error in verifyListAllNativeEntries()" +
+ "\nAPI Test: List getNativesForFlavor(null)" +
+ "\nTest failed because the returned List does not exactly" +
+ "\nmatch objects returned from SystemFlavorMap.");
+ }
+ }
+
+ // Compare List of DataFlavors with list from SystemFlavorMap
+ //
+ // Verification will be done by comparing the two results as sets
+ public void verifyListAllDataFlavorEntries(java.util.List listFlavors) {
+
+ HashSet hashSetMap = new HashSet(mapFlavors.keySet());
+ HashSet hashSetList = new HashSet(listFlavors);
+
+ System.out.println("*** hashSetMap size = " + hashSetMap.size());
+ System.out.println("*** hashSetList size = " + hashSetList.size());
+
+ if (!hashSetMap.equals(hashSetList)) {
+ throw new RuntimeException("\n*** Error in verifyListAllDataFlavorEntries()" +
+ "\nAPI Test: List getFlavorsForNative(null)" +
+ "\nTest failed because the returned List does not exactly" +
+ "\nmatch objects returned from SystemFlavorMap.");
+ }
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/SetDataFlavorsTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method:
+ * setNativesForFlavor(DataFlavor flav, String[] natives)
+ * with valid natives and DataFlavors. This stress test will
+ * define numerous mappings of valid String natives and
+ * DataFlavors. The mappings will be verified by examining
+ * that all entries are present, and order is maintained.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main SetDataFlavorsTest
+ */
+
+public class SetDataFlavorsTest {
+
+ SystemFlavorMap flavorMap;
+ Hashtable hashVerify;
+
+ Map mapFlavors;
+ Map mapNatives;
+
+ Hashtable hashFlavors;
+ Hashtable hashNatives;
+
+ public static void main (String[] args) {
+ new SetDataFlavorsTest().doTest();
+ }
+
+ public void doTest() {
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get SystemFlavorMap Maps of String Natives and DataFlavors
+ mapFlavors = flavorMap.getNativesForFlavors(null);
+ mapNatives = flavorMap.getFlavorsForNatives(null);
+
+ hashFlavors = new Hashtable(mapFlavors);
+ hashNatives = new Hashtable(mapNatives);
+
+
+ // Test setNativesForFlavor(DataFlavors flav, String[] natives);
+ //
+ // Enumerate through all the system defined DataFlavors,
+ // and for each DataFlavor, define it again to the SystemFlavorMap
+ // with a slightly modified MimeType.
+ //
+ // For verification, a seperate Hashtable will be maintained of the additions.
+ DataFlavor key;
+ hashVerify = new Hashtable();
+
+ for (Enumeration e = hashFlavors.keys() ; e.hasMoreElements() ;) {
+ key = (DataFlavor)e.nextElement();
+
+ java.util.List listNatives = flavorMap.getNativesForFlavor(key);
+ Vector vectorNatives = new Vector(listNatives);
+ String[] arrayNatives = (String[])vectorNatives.toArray(new String[0]);
+
+ // Construct a new DataFlavor from an existing DataFlavor's MimeType
+ // Example:
+ // Original MimeType: "text/plain; class=java.io.Reader; charset=Unicode"
+ // Modified MimeType: "text/plain-TEST; class=java.io.Reader; charset=Unicode"
+
+ StringBuffer mimeType = new StringBuffer(key.getMimeType());
+ mimeType.insert(mimeType.indexOf(";"),"-TEST");
+
+ DataFlavor testFlav = new DataFlavor(mimeType.toString(), "Test DataFlavor");
+
+ // define the new String native entry
+ flavorMap.setNativesForFlavor(testFlav, arrayNatives);
+ // keep track of this new native entry
+ hashVerify.put(testFlav, vectorNatives);
+ }
+
+ // After establishing "new" mappings, verify that the defined
+ // Natives can be retrieved and that the List (order) is preserved.
+ verifyNewMappings();
+ }
+
+ // Verify getNativesForFlavor(DataFlavor flav) is returning the correct list
+ // of Natives (for the new mappings).
+ public void verifyNewMappings() {
+ // Enumerate through all DataFlavors
+ for (Enumeration e = hashVerify.keys() ; e.hasMoreElements() ;) {
+ DataFlavor key = (DataFlavor)e.nextElement();
+
+ java.util.List listNatives = flavorMap.getNativesForFlavor(key);
+ Vector vectorFlavors = new Vector(listNatives);
+
+ // Compare the list of Natives
+ if ( !vectorFlavors.equals(hashVerify.get(key))) {
+ throw new RuntimeException("\n*** Error in verifyNewMappings()" +
+ "\nmethod1: setNativesForFlavor(DataFlavor flav, String[] natives)" +
+ "\nmethod2: List getNativesForFlavor(DataFlavor flav)" +
+ "\nDataFlavor: " + key.getMimeType() +
+ "\nThe Returned List did not match the original set of Natives.");
+ }
+ }
+ System.out.println("*** DataFlavor size = " + hashVerify.size());
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/SetFlavorsForNativeTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method
+ * setFlavorsForNative(String nat, DataFlavor[] flavors)
+ * with valid natives and DataFlavors. Specifically test for
+ * adding new mappings, one-way and two-way, and to update
+ * existing mappings.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main SetFlavorsForNativeTest
+ */
+
+public class SetFlavorsForNativeTest {
+
+ SystemFlavorMap flavorMap;
+ Vector comp1, comp2, comp3;
+ Hashtable hash;
+ int hashSize;
+
+ String test_native1, test_native2, test_native3, test_native4;
+ String[] test_natives_set1, test_natives_set2;
+ DataFlavor test_flavor1, test_flavor2, test_flavor3, test_flavor4;
+ DataFlavor[] test_flavors_set1, test_flavors_set2;
+
+ public static void main (String[] args) throws Exception {
+ new SetFlavorsForNativeTest().doTest();
+ }
+
+ public void doTest() throws Exception {
+ // Initialize DataFlavors and arrays used for test data
+ initMappings();
+
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get all the native strings and preferred DataFlavor mappings
+ hash = new Hashtable(flavorMap.getFlavorsForNatives(null));
+ hashSize = hash.size();
+
+ // Setup One-way Mappings
+ System.out.println("One-way Mappings Test");
+ flavorMap.setFlavorsForNative(test_native1, test_flavors_set1);
+ flavorMap.setFlavorsForNative(test_native2, test_flavors_set1);
+
+ // Confirm mapping with getFlavorsForNative
+ comp1 = new Vector(Arrays.asList(test_flavors_set1));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native1));
+ comp3 = new Vector(flavorMap.getFlavorsForNative(test_native2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up one-way mapping" +
+ "\nwith setFlavorsForNative(String nat, DataFlavors[] flavors)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("One-way: Test Passes");
+
+ // Setup Two-way Mapping
+ System.out.println("Two-way Mappings Test");
+ flavorMap.setNativesForFlavor(test_flavor1, test_natives_set1);
+ flavorMap.setNativesForFlavor(test_flavor2, test_natives_set1);
+
+ // Confirm mapping with getNativesForFlavor
+ comp1 = new Vector(Arrays.asList(test_natives_set1));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flavor1));
+ comp3 = new Vector(flavorMap.getNativesForFlavor(test_flavor2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith setNativesForFlavor(DataFlavor flav, String[] natives)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (DataFlavor): Test Passes");
+
+ // Check first native mapping
+ comp1 = new Vector(Arrays.asList(test_flavors_set1));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native1));
+ comp3 = new Vector(flavorMap.getFlavorsForNative(test_native2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith setFlavorsForNative(String nat, DataFlavors[] flavors)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (String native): Test Passes");
+
+ //
+ // Modify an existing mapping test
+ System.out.println("Modify Existing Mappings Test");
+ flavorMap.setFlavorsForNative(test_native1, test_flavors_set2);
+ flavorMap.setFlavorsForNative(test_native2, test_flavors_set2);
+
+ // Confirm mapping with getFlavorsForNative
+ comp1 = new Vector(Arrays.asList(test_flavors_set2));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native1));
+ comp3 = new Vector(flavorMap.getFlavorsForNative(test_native2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After modifying an existing mapping" +
+ "\nwith setFlavorsForNative(String nat, DataFlavors[] flavors)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Modify Existing Mappings: Test Passes");
+
+ }
+
+ // Initialize mapping variables used in this test
+ public void initMappings() throws Exception {
+ //create String natives
+ test_native1 = "TEST1";
+ test_native2 = "TEST2";
+ test_native3 = "TEST3";
+ test_native4 = "TEST4";
+
+ test_flavor1 = new DataFlavor(Class.forName("java.awt.Label"), "test1");
+ test_flavor2 = new DataFlavor(Class.forName("java.awt.Button"), "test2");
+ test_flavor3 = new DataFlavor(Class.forName("java.awt.Checkbox"), "test3");
+ test_flavor4 = new DataFlavor(Class.forName("java.awt.List"), "test4");
+
+ //create and initialize DataFlavor arrays
+ test_flavors_set1 = new DataFlavor[] {test_flavor1, test_flavor2};
+ test_flavors_set2 = new DataFlavor[] {test_flavor3, test_flavor4};
+
+ //create and initialize String native arrays
+ test_natives_set1 = new String[] {test_native1, test_native2};
+ test_natives_set2 = new String[] {test_native3, test_native4};
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/SetNativesForFlavor.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method
+ * setNativesForFlavor(DataFlavor flav, String[] natives)
+ * with valid natives and DataFlavors. Specifically test for
+ * adding new mappings, one-way and two-way, and to update
+ * existing mappings.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main SetNativesForFlavorTest
+ */
+
+public class SetNativesForFlavor {
+
+ SystemFlavorMap flavorMap;
+ Vector comp1, comp2, comp3;
+ Hashtable hash;
+ int hashSize;
+
+ String test_native1, test_native2, test_native3, test_native4;
+ String[] test_natives_set1, test_natives_set2;
+ DataFlavor test_flavor1, test_flavor2, test_flavor3, test_flavor4;
+ DataFlavor[] test_flavors_set1, test_flavors_set2;
+
+ public static void main (String[] args) throws Exception {
+ new SetNativesForFlavor().doTest();
+ }
+
+ public void doTest() throws Exception {
+ // Initialize DataFlavors and arrays used for test data
+ initMappings();
+
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get all the native strings and preferred DataFlavor mappings
+ hash = new Hashtable(flavorMap.getFlavorsForNatives(null));
+ hashSize = hash.size();
+
+ // Setup One-way Mappings
+ System.out.println("One-way Mappings Test");
+ flavorMap.setNativesForFlavor(test_flavor1, test_natives_set1);
+ flavorMap.setNativesForFlavor(test_flavor2, test_natives_set1);
+
+ // Confirm mapping with getNativesForFlavor
+ comp1 = new Vector(Arrays.asList(test_natives_set1));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flavor1));
+ comp3 = new Vector(flavorMap.getNativesForFlavor(test_flavor2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up one-way mapping" +
+ "\nwith setNativesForFlavor(DataFlavor flav, String[] natives)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("One-way: Test Passes");
+
+ // Setup Two-way Mapping
+ System.out.println("Two-way Mappings Test");
+ flavorMap.setFlavorsForNative(test_native1, test_flavors_set1);
+ flavorMap.setFlavorsForNative(test_native2, test_flavors_set1);
+
+ // Confirm mapping with getFlavorsForNative
+ comp1 = new Vector(Arrays.asList(test_flavors_set1));
+ comp2 = new Vector(flavorMap.getFlavorsForNative(test_native1));
+ comp3 = new Vector(flavorMap.getFlavorsForNative(test_native2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith setFlavorsForNative(string nat, DataFlavor[] flavors)" +
+ "\nthe mappings returned from getFlavorsForNative() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (DataFlavor): Test Passes");
+
+ // Check first native mapping
+ comp1 = new Vector(Arrays.asList(test_natives_set1));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flavor1));
+ comp3 = new Vector(flavorMap.getNativesForFlavor(test_flavor2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After setting up two-way mapping" +
+ "\nwith setNativesForFlavor(DataFlavor flav, String[] natives)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Two-way (String native): Test Passes");
+
+ // Modify an existing mapping test
+ System.out.println("Modify Existing Mappings Test");
+ flavorMap.setNativesForFlavor(test_flavor1, test_natives_set2);
+ flavorMap.setNativesForFlavor(test_flavor2, test_natives_set2);
+
+ // Confirm mapping with getNativesForFlavor
+ comp1 = new Vector(Arrays.asList(test_natives_set2));
+ comp2 = new Vector(flavorMap.getNativesForFlavor(test_flavor1));
+ comp3 = new Vector(flavorMap.getNativesForFlavor(test_flavor2));
+
+ if ( !(comp1.equals(comp2)) || !(comp1.equals(comp3))) {
+ throw new RuntimeException("\n*** After modifying an existing mapping" +
+ "\nwith setNativesForFlavor(DataFlavor flav, String[] natives)" +
+ "\nthe mappings returned from getNativesForFlavor() do not match" +
+ "\noriginal mappings.");
+ }
+ else
+ System.out.println("Modify Existing Mappings: Test Passes");
+
+ }
+
+ // Initialize mapping variables used in this test
+ public void initMappings() throws Exception {
+ //create String natives
+ test_native1 = "TEST1";
+ test_native2 = "TEST2";
+ test_native3 = "TEST3";
+ test_native4 = "TEST4";
+
+ test_flavor1 = new DataFlavor(Class.forName("java.awt.Label"), "test1");
+ test_flavor2 = new DataFlavor(Class.forName("java.awt.Button"), "test2");
+ test_flavor3 = new DataFlavor(Class.forName("java.awt.Checkbox"), "test3");
+ test_flavor4 = new DataFlavor(Class.forName("java.awt.List"), "test4");
+
+ //create and initialize DataFlavor arrays
+ test_flavors_set1 = new DataFlavor[] {test_flavor1, test_flavor2};
+ test_flavors_set2 = new DataFlavor[] {test_flavor3, test_flavor4};
+
+ //create and initialize String native arrays
+ test_natives_set1 = new String[] {test_native1, test_native2};
+ test_natives_set2 = new String[] {test_native3, test_native4};
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemFlavorMap/SetNativesTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.SystemFlavorMap;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Vector;
+
+/*
+ * @test
+ * @summary To test SystemFlavorMap method:
+ * setFlavorsForNative(String nat, DataFlavors[] flavors)
+ * with valid natives and DataFlavors. This stress test will
+ * define numerous mappings of valid String natives and
+ * DataFlavors. The mappings will be verified by examining
+ * that all entries are present, and order is maintained.
+ * @author Rick Reynaga (rick.reynaga@eng.sun.com) area=Clipboard
+ * @run main SetNativesTest
+ */
+
+public class SetNativesTest {
+
+ SystemFlavorMap flavorMap;
+ Hashtable hashVerify;
+
+ Map mapFlavors;
+ Map mapNatives;
+
+ Hashtable hashFlavors;
+ Hashtable hashNatives;
+
+ public static void main (String[] args){
+ new SetNativesTest().doTest();
+ }
+
+ public void doTest() {
+ flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap();
+
+ // Get SystemFlavorMap Maps of String Natives and DataFlavors
+ mapFlavors = flavorMap.getNativesForFlavors(null);
+ mapNatives = flavorMap.getFlavorsForNatives(null);
+
+ hashFlavors = new Hashtable(mapFlavors);
+ hashNatives = new Hashtable(mapNatives);
+
+
+ // Test setFlavorsForNative(String nat, DataFlavors[] flavors);
+ //
+ // Enumerate through all the system defined String natives,
+ // and for each String native, define it again to the SystemFlavorMap
+ // with a slightly modified String native (name).
+ //
+ // For verification, a seperate Hashtable will be maintained of the additions.
+ String key;
+ hashVerify = new Hashtable();
+
+ for (Enumeration e = hashNatives.keys() ; e.hasMoreElements() ;) {
+ key = (String)e.nextElement();
+
+ java.util.List listFlavors = flavorMap.getFlavorsForNative(key);
+ Vector vectorFlavors = new Vector(listFlavors);
+ DataFlavor[] arrayFlavors = (DataFlavor[])vectorFlavors.toArray(new DataFlavor[0]);
+
+ key = key.concat("TEST"); // construct a unique String native
+ // define the new String native entry
+ flavorMap.setFlavorsForNative(key, arrayFlavors);
+ // keep track of this new native entry
+ hashVerify.put(key, vectorFlavors);
+ }
+
+ // After establishing "new" mappings, verify that the defined
+ // DataFlavors can be retrieved and that the List (order) is preserved.
+ verifyNewMappings();
+ }
+
+ // Verify getFlavorsForNative(String nat) is returning the correct list
+ // of DataFlavors (for the new mappings).
+ public void verifyNewMappings() {
+ // Enumerate through all natives
+ for (Enumeration e = hashVerify.keys() ; e.hasMoreElements() ;) {
+ String key = (String)e.nextElement();
+
+ java.util.List listFlavors = flavorMap.getFlavorsForNative(key);
+ Vector vectorFlavors = new Vector(listFlavors);
+
+ // Compare the list of DataFlavors
+ if ( !vectorFlavors.equals((Vector)hashVerify.get(key))) {
+ throw new RuntimeException("\n*** Error in verifyNewMappings()" +
+ "\nmethod1: setFlavorsForNative(String nat, DataFlavors[] flavors)" +
+ "\nmethod2: List getFlavorsForNative(String nat)" +
+ "\nString native: " + key +
+ "\nThe Returned List did not match the original set of DataFlavors.");
+ }
+ }
+ System.out.println("*** native size = " + hashVerify.size());
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemSelection/SystemSelectionAWTTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.InputEvent;
+import java.util.Properties;
+
+/*
+ * @test
+ * @summary To check the functionality of newly added API getSystemSelection & make sure
+ * that it's mapped to primary clipboard
+ * @author Jitender(jitender.singh@eng.sun.com) area=AWT
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main SystemSelectionAWTTest
+ */
+
+public class SystemSelectionAWTTest {
+
+ Frame frame;
+ TextField tf1, tf2;
+ Clipboard clip;
+ Transferable t;
+
+ public static void main(String[] args) throws Exception {
+ new SystemSelectionAWTTest().doTest();
+ }
+
+ SystemSelectionAWTTest() {
+ frame = new Frame();
+ frame.setSize(200, 200);
+
+ tf1 = new TextField();
+ tf1.addFocusListener( new FocusAdapter() {
+ public void focusGained(FocusEvent fe) {
+ fe.getSource();
+ }
+ });
+
+ tf2 = new TextField();
+
+ frame.add(tf2, BorderLayout.NORTH);
+ frame.add(tf1, BorderLayout.CENTER);
+
+ frame.setVisible(true);
+ frame.toFront();
+ tf1.requestFocus();
+ tf1.setText("Selection Testing");
+ }
+
+ // Check whether Security manager is there
+ public void checkSecurity() {
+ SecurityManager sm = System.getSecurityManager();
+
+ if (sm == null) {
+ System.out.println("security manager is not there");
+ getPrimaryClipboard();
+ } else {
+ try {
+ sm.checkPermission(new AWTPermission("accessClipboard"));
+ getPrimaryClipboard();
+ } catch(SecurityException e) {
+ clip = null;
+ System.out.println("Access to System selection is not allowed");
+ }
+ }
+ }
+
+ // Get the contents from the clipboard
+ void getClipboardContent() throws Exception {
+ t = clip.getContents(this);
+ if ( (t != null) && (t.isDataFlavorSupported(DataFlavor.stringFlavor) )) {
+ tf2.setBackground(Color.red);
+ tf2.setForeground(Color.black);
+ tf2.setText((String) t.getTransferData(DataFlavor.stringFlavor));
+ }
+ }
+
+ // Get System Selection i.e. Primary Clipboard
+ private void getPrimaryClipboard() {
+ Properties ps = System.getProperties();
+ String operSys = ps.getProperty("os.name");
+ clip = Toolkit.getDefaultToolkit().getSystemSelection();
+ if (clip == null) {
+ if ((operSys.substring(0,3)).equalsIgnoreCase("Win") ||
+ (operSys.substring(0,3)).equalsIgnoreCase("Mac"))
+ System.out.println(operSys + " operating system does not support system selection ");
+ else
+ throw new RuntimeException("Method getSystemSelection() is returning null on X11 platform");
+ }
+ }
+
+ // Compare the selected text with one pasted from the clipboard
+ public void compareText() {
+ if ((tf2.getText()).equals(tf1.getSelectedText()) &&
+ System.getProperties().getProperty("os.name").substring(0,3) != "Win") {
+ System.out.println("Selected text & clipboard contents are same\n");
+ } else {
+ throw new RuntimeException("Selected text & clipboard contents differs\n");
+ }
+ }
+
+ public void doTest() throws Exception {
+ ExtendedRobot robot = new ExtendedRobot();
+
+ frame.setLocation(100, 100);
+ robot.waitForIdle(2000);
+
+ Point tf1Location = tf1.getLocationOnScreen();
+ Dimension tf1Size = tf1.getSize();
+ checkSecurity();
+
+ if (clip != null) {
+ robot.mouseMove(tf1Location.x + 5, tf1Location.y + tf1Size.height / 2);
+ robot.waitForIdle(2000);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardContent();
+ compareText();
+
+ robot.mouseMove(tf1Location.x + tf1Size.width / 2, tf1Location.y + tf1Size.height / 2);
+ robot.waitForIdle(2000);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardContent();
+ compareText();
+ }
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/datatransfer/SystemSelection/SystemSelectionSwingTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.InputEvent;
+import java.util.Properties;
+
+/*
+ * @test
+ * @summary To check the functionality of newly added API getSystemSelection & make sure
+ * that it's mapped to primary clipboard
+ * @author Jitender(jitender.singh@eng.sun.com) area=AWT
+ * @library ../../../../lib/testlibrary
+ * @build ExtendedRobot
+ * @run main SystemSelectionSwingTest
+ */
+
+public class SystemSelectionSwingTest {
+
+ JFrame jframe;
+ JTextField jtf1, jtf2;
+ Clipboard clip;
+ Transferable t;
+
+ public static void main(String[] args) throws Exception {
+ new SystemSelectionSwingTest().doTest();
+ }
+
+ SystemSelectionSwingTest() {
+ jframe = new JFrame();
+ jframe.setSize(200, 200);
+
+ jtf1 = new JTextField();
+ jtf1.addFocusListener( new FocusAdapter() {
+ public void focusGained(FocusEvent fe) {
+ fe.getSource();
+ }
+ });
+
+ jtf2 = new JTextField();
+
+ jframe.add(jtf2, BorderLayout.NORTH);
+ jframe.add(jtf1, BorderLayout.CENTER);
+
+ jframe.setVisible(true);
+ jframe.toFront();
+ jtf1.requestFocus();
+ jtf1.setText("Selection Testing");
+ }
+
+ // Check whether Security manager is there
+ public void checkSecurity() {
+ SecurityManager sm = System.getSecurityManager();
+
+ if (sm == null) {
+ System.out.println("security manager is not there");
+ getPrimaryClipboard();
+ } else {
+ try {
+ sm.checkPermission(new AWTPermission("accessClipboard"));
+ getPrimaryClipboard();
+ } catch(SecurityException e) {
+ clip = null;
+ System.out.println("Access to System selection is not allowed");
+ }
+ }
+ }
+
+ // Get the contents from the clipboard
+ void getClipboardContent() throws Exception {
+ t = clip.getContents(this);
+ if ( (t != null) && (t.isDataFlavorSupported(DataFlavor.stringFlavor) )) {
+ jtf2.setBackground(Color.red);
+ jtf2.setForeground(Color.black);
+ jtf2.setText((String) t.getTransferData(DataFlavor.stringFlavor));
+ }
+ }
+
+
+ // Get System Selection i.e. Primary Clipboard
+ private void getPrimaryClipboard() {
+ Properties ps = System.getProperties();
+ String operSys = ps.getProperty("os.name");
+ clip = Toolkit.getDefaultToolkit().getSystemSelection();
+ if (clip == null) {
+ if ((operSys.substring(0,3)).equalsIgnoreCase("Win") ||
+ (operSys.substring(0,3)).equalsIgnoreCase("Mac"))
+ System.out.println(operSys + " operating system does not support system selection ");
+ else
+ throw new RuntimeException("Method getSystemSelection() is returning null on X11 platform");
+ }
+ }
+
+ // Compare the selected text with one pasted from the clipboard
+ public void compareText() {
+ if ((jtf2.getText()).equals(jtf1.getSelectedText()) &&
+ System.getProperties().getProperty("os.name").substring(0,3) != "Win") {
+ System.out.println("Selected text & clipboard contents are same\n");
+ } else {
+ throw new RuntimeException("Selected text & clipboard contents differs\n");
+ }
+ }
+
+ public void doTest() throws Exception {
+ ExtendedRobot robot = new ExtendedRobot();
+
+ jframe.setLocation(100, 100);
+ robot.waitForIdle(2000);
+
+ Point tf1Location = jtf1.getLocationOnScreen();
+ Dimension tf1Size = jtf1.getSize();
+ checkSecurity();
+
+ if (clip != null) {
+ robot.mouseMove(tf1Location.x + 5, tf1Location.y + tf1Size.height / 2);
+ robot.waitForIdle(2000);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardContent();
+ compareText();
+
+ robot.mouseMove(tf1Location.x + tf1Size.width / 2, tf1Location.y + tf1Size.height / 2);
+ robot.waitForIdle(2000);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(20);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.waitForIdle(2000);
+
+ getClipboardContent();
+ compareText();
+ }
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/print/PrinterJob/PolylinePrintingTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @bug 8041902
+ * @summary Test printing of wide poly lines.
+ * @run main/manual=yesno PolylinePrintingTest
+ */
+
+import java.awt.Dialog;
+import java.awt.Frame;
+import java.awt.TextArea;
+import java.awt.BasicStroke;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Path2D;
+import java.awt.print.PageFormat;
+import java.awt.print.Paper;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+
+public class PolylinePrintingTest implements Printable {
+
+ public int print(Graphics graphics, PageFormat pageFormat,
+ int pageIndex) throws PrinterException {
+
+ if (pageIndex > 0) {
+ return NO_SUCH_PAGE;
+ }
+
+ Graphics2D g2d = (Graphics2D) graphics;
+ g2d.setStroke(new BasicStroke(25,
+ BasicStroke.CAP_ROUND,
+ BasicStroke.JOIN_MITER,
+ 10.0F, null, 1.0F));
+
+ int[] x2Points = {100, 250, 400};
+ int[] y2Points = {100, 400, 100};
+ drawPolylineGOOD(g2d, x2Points, y2Points);
+ drawPolylineBAD(g2d, x2Points, y2Points);
+
+ return PAGE_EXISTS;
+ }
+
+ private void drawPolylineGOOD(Graphics2D g2d,
+ int[] x2Points, int[] y2Points) {
+
+ Path2D polyline =
+ new Path2D.Float(Path2D.WIND_EVEN_ODD, x2Points.length);
+
+ polyline.moveTo(x2Points[0], y2Points[0]);
+
+ for (int index = 1; index < x2Points.length; index++) {
+ polyline.lineTo(x2Points[index], y2Points[index]);
+ }
+ g2d.draw(polyline);
+ }
+
+ private void drawPolylineBAD(Graphics2D g, int[] xp, int[] yp) {
+ int offset = 200;
+ g.translate(0, offset);
+ g.drawPolyline(xp, yp, xp.length);
+ }
+
+ public PolylinePrintingTest() throws PrinterException {
+ PrinterJob job = PrinterJob.getPrinterJob();
+ PageFormat pf = job.defaultPage();
+ Paper p = pf.getPaper();
+ p.setImageableArea(0,0,p.getWidth(), p.getHeight());
+ pf.setPaper(p);
+ job.setPrintable(this, pf);
+ if (job.printDialog()) {
+ job.print();
+ }
+ }
+
+ public static void main(String[] args) throws PrinterException {
+ String[] instructions = {
+ "You must have a printer available to perform this test.",
+ "OK the print dialog, and collect the printed page.",
+ "Passing test : Output should show two identical chevrons.",
+ "Failing test : The line joins will appear different."
+ };
+ Sysout.createDialog();
+ Sysout.printInstructions(instructions);
+ new PolylinePrintingTest();
+ }
+}
+
+class Sysout {
+ private static TestDialog dialog;
+
+ public static void createDialogWithInstructions( String[] instructions )
+ {
+ dialog = new TestDialog( new Frame(), "Instructions" );
+ dialog.printInstructions( instructions );
+ dialog.show();
+ println( "Any messages for the tester will display here." );
+ }
+
+ public static void createDialog( )
+ {
+ dialog = new TestDialog( new Frame(), "Instructions" );
+ String[] defInstr = { "Instructions will appear here. ", "" } ;
+ dialog.printInstructions( defInstr );
+ dialog.show();
+ println( "Any messages for the tester will display here." );
+ }
+
+
+ public static void printInstructions( String[] instructions )
+ {
+ dialog.printInstructions( instructions );
+ }
+
+
+ public static void println( String messageIn )
+ {
+ dialog.displayMessage( messageIn );
+ }
+
+}// Sysout class
+
+/**
+ This is part of the standard test machinery. It provides a place for the
+ test instructions to be displayed, and a place for interactive messages
+ to the user to be displayed.
+ To have the test instructions displayed, see Sysout.
+ To have a message to the user be displayed, see Sysout.
+ Do not call anything in this dialog directly.
+ */
+class TestDialog extends Dialog {
+ TextArea instructionsText;
+ TextArea messageText;
+ int maxStringLength = 80;
+
+ //DO NOT call this directly, go through Sysout
+ public TestDialog( Frame frame, String name )
+ {
+ super( frame, name );
+ int scrollBoth = TextArea.SCROLLBARS_BOTH;
+ instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
+ add( "North", instructionsText );
+
+ messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
+ add("Center", messageText);
+
+ pack();
+
+ show();
+ }// TestDialog()
+
+ //DO NOT call this directly, go through Sysout
+ public void printInstructions( String[] instructions )
+ {
+ //Clear out any current instructions
+ instructionsText.setText( "" );
+
+ //Go down array of instruction strings
+
+ String printStr, remainingStr;
+ for( int i=0; i < instructions.length; i++ )
+ {
+ //chop up each into pieces maxSringLength long
+ remainingStr = instructions[ i ];
+ while( remainingStr.length() > 0 )
+ {
+ //if longer than max then chop off first max chars to print
+ if( remainingStr.length() >= maxStringLength )
+ {
+ //Try to chop on a word boundary
+ int posOfSpace = remainingStr.
+ lastIndexOf( ' ', maxStringLength - 1 );
+ if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
+
+ printStr = remainingStr.substring( 0, posOfSpace + 1 );
+ remainingStr = remainingStr.substring( posOfSpace + 1 );
+ }
+ //else just print
+ else
+ {
+ printStr = remainingStr;
+ remainingStr = "";
+ }
+
+ instructionsText.append( printStr + "\n" );
+
+ }// while
+
+ }// for
+
+ }//printInstructions()
+
+ //DO NOT call this directly, go through Sysout
+ public void displayMessage( String messageIn )
+ {
+ messageText.append( messageIn + "\n" );
+ }
+
+}// TestDialog class
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Introspector/4058433/TestBeanProperty.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.beans.BeanProperty;
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.beans.PropertyDescriptor;
+import java.util.Arrays;
+/*
+ * @test
+ * @bug 4058433
+ * @summary Tests the BeanProperty annotation
+ * @author Sergey Malenkov
+ * @library ..
+ */
+public class TestBeanProperty {
+ public static void main(String[] args) throws Exception {
+ Class<?>[] types = {B.class, BL.class, BLF.class, E.class, H.class, P.class, VU.class, D.class, EV.class, EVL.class, EVX.class};
+ for (Class<?> type : types) {
+ PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, "value");
+ if (((B.class == type) || (BLF.class == type)) && pd.isBound()) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("not bound");
+ }
+ if ((BL.class == type) == !pd.isBound()) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("bound");
+ }
+ if ((E.class == type) == !pd.isExpert()) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("expert");
+ }
+ if ((H.class == type) == !pd.isHidden()) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("hidden");
+ }
+ if ((P.class == type) == !pd.isPreferred()) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("preferred");
+ }
+ if ((R.class == type) == !Boolean.TRUE.equals(pd.getValue("required"))) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("required");
+ }
+ if ((VU.class == type) == !Boolean.TRUE.equals(pd.getValue("visualUpdate"))) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("visualUpdate");
+ }
+ if ((EV.class == type) == !isEV(pd, "LEFT", 2, "javax.swing.SwingConstants.LEFT", "RIGHT", 4, "javax.swing.SwingConstants.RIGHT")) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("enumerationValues from another package");
+ }
+ if ((EVL.class == type) == !isEV(pd, "ZERO", 0, "ZERO", "ONE", 1, "ONE")) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("enumerationValues from another package");
+ }
+ if ((EVX.class == type) == !isEV(pd, "ZERO", 0, "X.ZERO", "ONE", 1, "X.ONE")) {
+ BeanUtils.reportPropertyDescriptor(pd);
+ throw new Error("enumerationValues from another package");
+ }
+ }
+ }
+
+ private static boolean isEV(PropertyDescriptor pd, Object... expected) {
+ Object value = pd.getValue("enumerationValues");
+ return value instanceof Object[] && Arrays.equals((Object[]) value, expected);
+ }
+
+ public static class B {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class BL {
+ private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public void addPropertyChangeListener(PropertyChangeListener listener) {
+ this.pcs.addPropertyChangeListener(listener);
+ }
+
+ public void removePropertyChangeListener(PropertyChangeListener listener) {
+ this.pcs.removePropertyChangeListener(listener);
+ }
+ }
+
+ public static class BLF {
+ private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(bound = false)
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public void addPropertyChangeListener(PropertyChangeListener listener) {
+ this.pcs.addPropertyChangeListener(listener);
+ }
+
+ public void removePropertyChangeListener(PropertyChangeListener listener) {
+ this.pcs.removePropertyChangeListener(listener);
+ }
+ }
+
+ public static class E {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(expert = true)
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class H {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(hidden = true)
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class P {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(preferred = true)
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class R {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(required = true)
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class VU {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(visualUpdate = true)
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class D {
+ private int value;
+
+ @BeanProperty(description = "getter")
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(description = "setter")
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class EV {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(enumerationValues = {
+ "javax.swing.SwingConstants.LEFT",
+ "javax.swing.SwingConstants.RIGHT"})
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static class EVL {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(enumerationValues = {"ZERO", "ONE"})
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public static int ZERO = 0;
+ public static int ONE = 1;
+ }
+
+ public static class EVX {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ @BeanProperty(enumerationValues = {
+ "X.ZERO",
+ "X.ONE"})
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ public static interface X {
+ int ZERO = 0;
+ int ONE = 1;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Introspector/4058433/TestJavaBean.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.awt.event.ActionListener;
+import java.beans.BeanDescriptor;
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.beans.JavaBean;
+/*
+ * @test
+ * @bug 4058433
+ * @summary Tests the JavaBean annotation
+ * @author Sergey Malenkov
+ */
+public class TestJavaBean {
+ public static void main(String[] args) throws Exception {
+ test(X.class);
+ test(D.class);
+ test(DP.class);
+ test(DES.class);
+ }
+
+ private static void test(Class<?> type) throws Exception {
+ System.out.println(type);
+ BeanInfo info = Introspector.getBeanInfo(type);
+ BeanDescriptor bd = info.getBeanDescriptor();
+
+ String description = bd.getShortDescription();
+ System.out.println("description = " + description);
+
+ int dp = info.getDefaultPropertyIndex();
+ System.out.println("property index = " + dp);
+ if (0 <= dp) {
+ String name = info.getPropertyDescriptors()[dp].getName();
+ System.out.println("property name = " + name);
+ }
+ int des = info.getDefaultEventIndex();
+ System.out.println("event set index = " + des);
+ if (0 <= des) {
+ String name = info.getPropertyDescriptors()[des].getName();
+ System.out.println("event set name = " + name);
+ }
+
+ if ((D.class == type) == bd.getName().equals(description)) {
+ throw new Error("unexpected description of the bean");
+ }
+ if ((DP.class == type) == (dp < 0)) {
+ throw new Error("unexpected index of the default property");
+ }
+ if ((DES.class == type) == (des < 0)) {
+ throw new Error("unexpected index of the default event set");
+ }
+ }
+
+ public static class X {
+ }
+
+ @JavaBean(description = "description")
+ public static class D {
+ }
+
+ @JavaBean(defaultProperty = "value")
+ public static class DP {
+ private int value;
+
+ public int getValue() {
+ return this.value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+ }
+
+ @JavaBean(defaultEventSet = "action")
+ public static class DES {
+ public void addActionListener(ActionListener listener) {
+ }
+
+ public void removeActionListener(ActionListener listener) {
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Introspector/4058433/TestSwingContainer.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.beans.BeanDescriptor;
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.util.Objects;
+import javax.swing.SwingContainer;
+/*
+ * @test
+ * @bug 4058433
+ * @summary Tests the SwingContainer annotation
+ * @author Sergey Malenkov
+ */
+public class TestSwingContainer {
+ public static void main(String[] args) throws Exception {
+ test(X.class, null, null);
+ test(T.class, true, null);
+ test(D.class, true, "method");
+ test(F.class, false, null);
+ test(A.class, false, "method");
+ }
+
+ private static void test(Class<?> type, Object iC, Object cD) throws Exception {
+ System.out.println(type);
+ BeanInfo info = Introspector.getBeanInfo(type);
+ BeanDescriptor bd = info.getBeanDescriptor();
+ test(bd, "isContainer", iC);
+ test(bd, "containerDelegate", cD);
+ }
+
+ private static void test(BeanDescriptor bd, String name, Object expected) {
+ Object value = bd.getValue(name);
+ System.out.println(name + " = " + value);
+ if (!Objects.equals(value, expected)) {
+ throw new Error(name + ": expected = " + expected + "; actual = " + value);
+ }
+ }
+
+ public static class X {
+ }
+
+ @SwingContainer()
+ public static class T {
+ }
+
+ @SwingContainer(delegate = "method")
+ public static class D {
+ }
+
+ @SwingContainer(false)
+ public static class F {
+ }
+
+ @SwingContainer(value = false, delegate = "method")
+ public static class A {
+ }
+}
--- a/jdk/test/java/beans/Introspector/7084904/Test7084904.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/beans/Introspector/7084904/Test7084904.java Wed Jul 05 19:50:57 2017 +0200
@@ -27,6 +27,7 @@
* @bug 7084904
* @summary Compares reflection and bean introspection
* @author Sergey Malenkov
+ * @library ..
*/
public class Test7084904 {
public static void main(String[] args) throws Exception {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Performance/Test4058433.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.Image;
+import java.beans.BeanDescriptor;
+import java.beans.BeanInfo;
+import java.beans.EventSetDescriptor;
+import java.beans.FeatureDescriptor;
+import java.beans.IndexedPropertyDescriptor;
+import java.beans.Introspector;
+import java.beans.MethodDescriptor;
+import java.beans.ParameterDescriptor;
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Enumeration;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/*
+ * @test
+ * @bug 4058433
+ * @summary Generates BeanInfo for public classes in AWT, Accessibility, and Swing
+ * @author Sergey Malenkov
+ * @run main/manual Test4058433
+ */
+
+public class Test4058433 implements Comparator<Object> {
+ @Override
+ public int compare(Object one, Object two) {
+ if (one instanceof Method && two instanceof Method) {
+ Method oneMethod = (Method) one;
+ Method twoMethod = (Method) two;
+ int result = oneMethod.getName().compareTo(twoMethod.getName());
+ if (result != 0) {
+ return result;
+ }
+ }
+ if (one instanceof FeatureDescriptor && two instanceof FeatureDescriptor) {
+ FeatureDescriptor oneFD = (FeatureDescriptor) one;
+ FeatureDescriptor twoFD = (FeatureDescriptor) two;
+ int result = oneFD.getName().compareTo(twoFD.getName());
+ if (result != 0) {
+ return result;
+ }
+ }
+ return one.toString().compareTo(two.toString());
+ }
+
+ public static void main(String[] args) throws Exception {
+ String resource = ClassLoader.getSystemResource("java/lang/Object.class").toString();
+
+ Pattern pattern = Pattern.compile("jar:file:(.*)!.*");
+ Matcher matcher = pattern.matcher(resource);
+ matcher.matches();
+ resource = matcher.group(1);
+
+ TreeSet<Class<?>> types = new TreeSet<>(new Test4058433());
+ try (JarFile jarFile = new JarFile(resource.replaceAll("%20", " "))) {
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ String name = entries.nextElement().getName();
+ if (name.startsWith("java/awt/") || name.startsWith("javax/accessibility/") || name.startsWith("javax/swing/")) {
+ if (name.endsWith(".class")) {
+ name = name.substring(0, name.indexOf(".")).replace('/', '.');
+ Class<?> type = Class.forName(name);
+ if (!type.isInterface() && !type.isEnum() && !type.isAnnotation() && !type.isAnonymousClass()) {
+ if (null == type.getDeclaringClass()) {
+ types.add(type);
+ }
+ }
+ }
+ }
+ }
+ }
+ System.out.println("found " + types.size() + " classes");
+ long time = -System.currentTimeMillis();
+ for (Class<?> type : types) {
+ System.out.println("========================================");
+ BeanInfo info = Introspector.getBeanInfo(type);
+
+ BeanDescriptor bd = info.getBeanDescriptor();
+ System.out.println(bd.getBeanClass());
+ print("customizer", bd.getCustomizerClass());
+ print(bd);
+ print("mono 16x16", info.getIcon(BeanInfo.ICON_MONO_16x16));
+ print("mono 32x32", info.getIcon(BeanInfo.ICON_MONO_32x32));
+ print("color 16x16", info.getIcon(BeanInfo.ICON_COLOR_16x16));
+ print("color 32x32", info.getIcon(BeanInfo.ICON_COLOR_32x32));
+
+ PropertyDescriptor[] pds = info.getPropertyDescriptors();
+ PropertyDescriptor dpd = getDefault(pds, info.getDefaultPropertyIndex());
+ System.out.println(pds.length + " property descriptors");
+ Arrays.sort(pds, new Test4058433());
+ for (PropertyDescriptor pd : pds) {
+ print(pd);
+ if (dpd == pd) {
+ System.out.println("default property");
+ }
+ print("bound", pd.isBound());
+ print("constrained", pd.isConstrained());
+ print("property editor", pd.getPropertyEditorClass());
+ print("property type", pd.getPropertyType());
+ print("read method", pd.getReadMethod());
+ print("write method", pd.getWriteMethod());
+ if (pd instanceof IndexedPropertyDescriptor) {
+ IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
+ print("indexed property type", ipd.getIndexedPropertyType());
+ print("indexed read method", ipd.getIndexedReadMethod());
+ print("indexed write method", ipd.getIndexedWriteMethod());
+ }
+ }
+ EventSetDescriptor[] esds = info.getEventSetDescriptors();
+ EventSetDescriptor desd = getDefault(esds, info.getDefaultEventIndex());
+ System.out.println(esds.length + " event set descriptors");
+ Arrays.sort(esds, new Test4058433());
+ for (EventSetDescriptor esd : esds) {
+ print(esd);
+ if (desd == esd) {
+ System.out.println("default event set");
+ }
+ print("in default", esd.isInDefaultEventSet());
+ print("unicast", esd.isUnicast());
+ print("listener type", esd.getListenerType());
+ print("get listener method", esd.getGetListenerMethod());
+ print("add listener method", esd.getAddListenerMethod());
+ print("remove listener method", esd.getRemoveListenerMethod());
+ Method[] methods = esd.getListenerMethods();
+ Arrays.sort(methods, new Test4058433());
+ for (Method method : methods) {
+ print("listener method", method);
+ }
+ print(esd.getListenerMethodDescriptors());
+ }
+ print(info.getMethodDescriptors());
+ }
+ time += System.currentTimeMillis();
+ System.out.println("DONE IN " + time + " MS");
+ }
+
+ private static <T> T getDefault(T[] array, int index) {
+ return (index == -1) ? null : array[index];
+ }
+
+ private static void print(MethodDescriptor[] mds) {
+ System.out.println(mds.length + " method descriptors");
+ Arrays.sort(mds, new Test4058433());
+ for (MethodDescriptor md : mds) {
+ print(md);
+ print("method", md.getMethod());
+ ParameterDescriptor[] pds = md.getParameterDescriptors();
+ if (pds != null) {
+ System.out.println(pds.length + " parameter descriptors");
+ for (ParameterDescriptor pd : pds) {
+ print(pd);
+ }
+ }
+ }
+ }
+
+ private static void print(FeatureDescriptor descriptor) {
+ String name = descriptor.getName();
+ String display = descriptor.getDisplayName();
+ String description = descriptor.getShortDescription();
+ System.out.println("name: " + name);
+ if (!Objects.equals(name, display)) {
+ System.out.println("display name: " + display);
+ }
+ if (!Objects.equals(display, description)) {
+ System.out.println("description: " + description.trim());
+ }
+ print("expert", descriptor.isExpert());
+ print("hidden", descriptor.isHidden());
+ print("preferred", descriptor.isPreferred());
+ TreeMap<String,Object> map = new TreeMap<>();
+ Enumeration<String> enumeration = descriptor.attributeNames();
+ while (enumeration.hasMoreElements()) {
+ String id = enumeration.nextElement();
+ Object value = descriptor.getValue(id);
+ if (value.getClass().isArray()) {
+ TreeSet<String> set = new TreeSet<>();
+ int index = 0;
+ int length = Array.getLength(value);
+ while (index < length) {
+ set.add(Array.get(value, index++) + ", " +
+ Array.get(value, index++) + ", " +
+ Array.get(value, index++));
+ }
+ value = set.toString();
+ }
+ map.put(id, value);
+ }
+ for (Entry<String,Object> entry : map.entrySet()) {
+ System.out.println(entry.getKey() + ": " + entry.getValue());
+ }
+ }
+
+ private static void print(String id, boolean flag) {
+ if (flag) {
+ System.out.println(id + " is set");
+ }
+ }
+
+ private static void print(String id, Class<?> type) {
+ if (type != null) {
+ System.out.println(id + ": " + type.getName());
+ }
+ }
+
+ private static void print(String id, Method method) {
+ if (method != null) {
+ System.out.println(id + ": " + method);
+ }
+ }
+
+ private static void print(String name, Image image) {
+ if (image != null) {
+ System.out.println(name + " icon is exist");
+ }
+ }
+}
--- a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 6741606 7146431 8000450 8019830 8022945
+ * @bug 6741606 7146431 8000450 8019830 8022945 8027144 8041633
* @summary Make sure all restricted packages listed in the package.access
* property in the java.security file are blocked
* @run main/othervm CheckPackageAccess
@@ -83,7 +83,8 @@
"org.jcp.xml.dsig.internal.",
"jdk.internal.",
"jdk.nashorn.internal.",
- "jdk.nashorn.tools."
+ "jdk.nashorn.tools.",
+ "com.sun.activation.registries."
};
public static void main(String[] args) throws Exception {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/instrument/RedefineMethodDelInvoke.sh Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,98 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# @test
+# @bug 8042796
+# @summary jvmtiRedefineClasses.cpp: guarantee(false) failed: OLD and/or OBSOLETE method(s) found
+# @author Daniel D. Daugherty
+# @author Serguei Spitsyn
+#
+# @run shell MakeJAR3.sh RedefineMethodDelInvokeAgent 'Can-Redefine-Classes: true'
+# @run build RedefineMethodDelInvokeApp
+# @run shell RedefineMethodDelInvoke.sh
+#
+
+if [ "${TESTJAVA}" = "" ]
+then
+ echo "TESTJAVA not set. Test cannot execute. Failed."
+ exit 1
+fi
+
+if [ "${COMPILEJAVA}" = "" ]
+then
+ COMPILEJAVA="${TESTJAVA}"
+fi
+echo "COMPILEJAVA=${COMPILEJAVA}"
+
+if [ "${TESTSRC}" = "" ]
+then
+ echo "TESTSRC not set. Test cannot execute. Failed."
+ exit 1
+fi
+
+if [ "${TESTCLASSES}" = "" ]
+then
+ echo "TESTCLASSES not set. Test cannot execute. Failed."
+ exit 1
+fi
+
+JAVAC="${COMPILEJAVA}"/bin/javac
+JAVA="${TESTJAVA}"/bin/java
+
+cp "${TESTSRC}"/RedefineMethodDelInvokeTarget_1.java \
+ RedefineMethodDelInvokeTarget.java
+"${JAVAC}" ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d . RedefineMethodDelInvokeTarget.java
+mv RedefineMethodDelInvokeTarget.java RedefineMethodDelInvokeTarget_1.java
+mv RedefineMethodDelInvokeTarget.class RedefineMethodDelInvokeTarget_1.class
+
+cp "${TESTSRC}"/RedefineMethodDelInvokeTarget_2.java \
+ RedefineMethodDelInvokeTarget.java
+"${JAVAC}" ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d . RedefineMethodDelInvokeTarget.java
+mv RedefineMethodDelInvokeTarget.java RedefineMethodDelInvokeTarget_2.java
+mv RedefineMethodDelInvokeTarget.class RedefineMethodDelInvokeTarget_2.class
+
+"${JAVA}" ${TESTVMOPTS} -javaagent:RedefineMethodDelInvokeAgent.jar \
+ -classpath "${TESTCLASSES}" RedefineMethodDelInvokeApp > output.log 2>&1
+
+result=$?
+if [ "$result" = 0 ]; then
+ echo "The test returned expected exit code: $result"
+else
+ echo "FAIL: the test returned unexpected exit code: $result"
+ exit $result
+fi
+
+cat output.log
+
+MESG="Exception"
+grep "$MESG" output.log
+result=$?
+if [ "$result" = 0 ]; then
+ echo "FAIL: found '$MESG' in the test output"
+ result=1
+else
+ echo "PASS: did NOT find '$MESG' in the test output"
+ result=0
+fi
+
+exit $result
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/instrument/RedefineMethodDelInvokeAgent.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.lang.instrument.Instrumentation;
+
+public class RedefineMethodDelInvokeAgent {
+ private static Instrumentation instrumentation;
+
+ private RedefineMethodDelInvokeAgent() {
+ }
+
+ public static void premain(String agentArgs, Instrumentation inst) {
+ System.out.println("Hello from RedefineMethodDelInvokeAgent!");
+ System.out.println("isRedefineClassesSupported()=" +
+ inst.isRedefineClassesSupported());
+
+ instrumentation = inst;
+ }
+
+ public static Instrumentation getInstrumentation() {
+ return instrumentation;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/instrument/RedefineMethodDelInvokeApp.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.*;
+import java.lang.instrument.*;
+
+public class RedefineMethodDelInvokeApp {
+ public static void main(String args[]) {
+ System.out.println("Hello from RedefineMethodDelInvokeApp!");
+
+ try {
+ new RedefineMethodDelInvokeApp().doTest();
+ } catch (Exception ex) {
+ System.out.println("Exception has been caught");
+ ex.printStackTrace();
+ System.exit(1);
+ }
+ System.exit(0);
+ }
+
+ private void doTest() throws Exception {
+ RedefineMethodDelInvokeTarget target =
+ new RedefineMethodDelInvokeTarget();
+
+ System.out.println("RedefineMethodDelInvokeApp: invoking myMethod0(), myMethod1(), myMethod2()");
+ target.test();
+
+ // delete myMethod2()
+ do_redefine(1);
+
+ System.out.println("RedefineMethodDelInvokeApp: invoking myMethod0(), myMethod1()");
+ target.test();
+
+ // delete myMethod1()
+ do_redefine(2);
+
+ System.out.println("RedefineMethodDelInvokeApp: invoking myMethod0()");
+ target.test();
+ }
+
+ private static void do_redefine(int counter) throws Exception {
+ File f = new File("RedefineMethodDelInvokeTarget_" + counter +
+ ".class");
+ System.out.println("Reading test class from " + f);
+ InputStream redefineStream = new FileInputStream(f);
+
+ byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);
+
+ ClassDefinition redefineParamBlock = new ClassDefinition(
+ RedefineMethodDelInvokeTarget.class, redefineBuffer);
+
+ RedefineMethodDelInvokeAgent.getInstrumentation().redefineClasses(
+ new ClassDefinition[] {redefineParamBlock});
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/instrument/RedefineMethodDelInvokeTarget.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class RedefineMethodDelInvokeTarget {
+ public void test() {
+ myMethod0();
+ }
+
+ public static void myMethod0() {
+ System.out.println("Target 0: myMethod0: Calling myMethod1()");
+ myMethod1();
+ }
+
+ private static void myMethod1() {
+ System.out.println("Target 0: myMethod1: Calling myMethod2()");
+ myMethod2();
+ }
+
+ private static void myMethod2() {
+ System.out.println("Target 0: myMethod2");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/instrument/RedefineMethodDelInvokeTarget_1.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class RedefineMethodDelInvokeTarget {
+ public void test() {
+ myMethod0();
+ }
+
+ public static void myMethod0() {
+ System.out.println("Target 1: myMethod0: Calling myMethod1()");
+ myMethod1();
+ }
+
+ private static void myMethod1() {
+ System.out.println("Target 1: myMethod1");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/instrument/RedefineMethodDelInvokeTarget_2.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class RedefineMethodDelInvokeTarget {
+ public void test() {
+ myMethod0();
+ }
+
+ public static void myMethod0() {
+ System.out.println("Target 2: myMethod0");
+ }
+}
--- a/jdk/test/java/util/regex/RegExTest.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/util/regex/RegExTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
* 6358731 6178785 6284152 6231989 6497148 6486934 6233084 6504326 6635133
* 6350801 6676425 6878475 6919132 6931676 6948903 6990617 7014645 7039066
* 7067045 7014640 7189363 8007395 8013252 8013254 8012646 8023647 6559590
- * 8027645 8035076 8039124
+ * 8027645 8035076 8039124 8035975
*/
import java.util.regex.*;
@@ -150,6 +150,7 @@
groupCurlyNotFoundSuppTest();
groupCurlyBackoffTest();
patternAsPredicate();
+ invalidFlags();
if (failure) {
throw new
@@ -4457,4 +4458,30 @@
}
report("Pattern.asPredicate");
}
+
+ // This test is for 8035975
+ private static void invalidFlags() throws Exception {
+ for (int flag = 1; flag != 0; flag <<= 1) {
+ switch (flag) {
+ case Pattern.CASE_INSENSITIVE:
+ case Pattern.MULTILINE:
+ case Pattern.DOTALL:
+ case Pattern.UNICODE_CASE:
+ case Pattern.CANON_EQ:
+ case Pattern.UNIX_LINES:
+ case Pattern.LITERAL:
+ case Pattern.UNICODE_CHARACTER_CLASS:
+ case Pattern.COMMENTS:
+ // valid flag, continue
+ break;
+ default:
+ try {
+ Pattern.compile(".", flag);
+ failCount++;
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+ }
+ report("Invalid compile flags");
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/stream/bootlib/java/util/stream/ThowableHelper.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package java.util.stream;
+
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+public final class ThowableHelper {
+
+ public static void checkException(Class<? extends Exception> ce, Runnable r) {
+ Exception caught = null;
+ try {
+ r.run();
+ } catch (Exception e) {
+ caught = e;
+ }
+
+ assertNotNull(caught);
+ assertTrue(ce.isInstance(caught));
+ }
+
+ public static void checkNPE(Runnable r) {
+ checkException(NullPointerException.class, r);
+ }
+
+ public static void checkISE(Runnable r) {
+ checkException(IllegalStateException.class, r);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/CollectAndSummaryStatisticsTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary primtive stream collection with summary statistics
+ * @bug 8044047
+ */
+
+package org.openjdk.tests.java.util.stream;
+
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.DoubleSummaryStatistics;
+import java.util.IntSummaryStatistics;
+import java.util.List;
+import java.util.LongSummaryStatistics;
+import java.util.stream.Collectors;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.OpTestCase;
+
+import static java.util.stream.LambdaTestHelpers.countTo;
+import static java.util.stream.ThowableHelper.checkNPE;
+
+@Test
+public class CollectAndSummaryStatisticsTest extends OpTestCase {
+
+ public void testIntCollectNull() {
+ checkNPE(() -> IntStream.of(1).collect(null,
+ IntSummaryStatistics::accept,
+ IntSummaryStatistics::combine));
+ checkNPE(() -> IntStream.of(1).collect(IntSummaryStatistics::new,
+ null,
+ IntSummaryStatistics::combine));
+ checkNPE(() -> IntStream.of(1).collect(IntSummaryStatistics::new,
+ IntSummaryStatistics::accept,
+ null));
+ }
+
+ public void testLongCollectNull() {
+ checkNPE(() -> LongStream.of(1).collect(null,
+ LongSummaryStatistics::accept,
+ LongSummaryStatistics::combine));
+ checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
+ null,
+ LongSummaryStatistics::combine));
+ checkNPE(() -> LongStream.of(1).collect(LongSummaryStatistics::new,
+ LongSummaryStatistics::accept,
+ null));
+ }
+
+ public void testDoubleCollectNull() {
+ checkNPE(() -> DoubleStream.of(1).collect(null,
+ DoubleSummaryStatistics::accept,
+ DoubleSummaryStatistics::combine));
+ checkNPE(() -> DoubleStream.of(1).collect(DoubleSummaryStatistics::new,
+ null,
+ DoubleSummaryStatistics::combine));
+ checkNPE(() -> DoubleStream.of(1).collect(DoubleSummaryStatistics::new,
+ DoubleSummaryStatistics::accept,
+ null));
+ }
+
+ public void testIntStatistics() {
+ List<IntSummaryStatistics> instances = new ArrayList<>();
+ instances.add(countTo(1000).stream().collect(Collectors.summarizingInt(i -> i)));
+ instances.add(countTo(1000).stream().mapToInt(i -> i).summaryStatistics());
+ instances.add(countTo(1000).stream().mapToInt(i -> i).collect(IntSummaryStatistics::new,
+ IntSummaryStatistics::accept,
+ IntSummaryStatistics::combine));
+ instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingInt(i -> i)));
+ instances.add(countTo(1000).parallelStream().mapToInt(i -> i).summaryStatistics());
+ instances.add(countTo(1000).parallelStream().mapToInt(i -> i).collect(IntSummaryStatistics::new,
+ IntSummaryStatistics::accept,
+ IntSummaryStatistics::combine));
+
+ for (IntSummaryStatistics stats : instances) {
+ assertEquals(stats.getCount(), 1000);
+ assertEquals(stats.getSum(), countTo(1000).stream().mapToInt(i -> i).sum());
+ assertEquals(stats.getAverage(), (double) stats.getSum() / stats.getCount());
+ assertEquals(stats.getMax(), 1000);
+ assertEquals(stats.getMin(), 1);
+ }
+ }
+
+
+ public void testLongStatistics() {
+ List<LongSummaryStatistics> instances = new ArrayList<>();
+ instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
+ instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
+ instances.add(countTo(1000).stream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
+ LongSummaryStatistics::accept,
+ LongSummaryStatistics::combine));
+ instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
+ instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());
+ instances.add(countTo(1000).parallelStream().mapToLong(i -> i).collect(LongSummaryStatistics::new,
+ LongSummaryStatistics::accept,
+ LongSummaryStatistics::combine));
+
+ for (LongSummaryStatistics stats : instances) {
+ assertEquals(stats.getCount(), 1000);
+ assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
+ assertEquals(stats.getAverage(), (double) stats.getSum() / stats.getCount());
+ assertEquals(stats.getMax(), 1000L);
+ assertEquals(stats.getMin(), 1L);
+ }
+ }
+
+ public void testDoubleStatistics() {
+ List<DoubleSummaryStatistics> instances = new ArrayList<>();
+ instances.add(countTo(1000).stream().collect(Collectors.summarizingDouble(i -> i)));
+ instances.add(countTo(1000).stream().mapToDouble(i -> i).summaryStatistics());
+ instances.add(countTo(1000).stream().mapToDouble(i -> i).collect(DoubleSummaryStatistics::new,
+ DoubleSummaryStatistics::accept,
+ DoubleSummaryStatistics::combine));
+ instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingDouble(i -> i)));
+ instances.add(countTo(1000).parallelStream().mapToDouble(i -> i).summaryStatistics());
+ instances.add(countTo(1000).parallelStream().mapToDouble(i -> i).collect(DoubleSummaryStatistics::new,
+ DoubleSummaryStatistics::accept,
+ DoubleSummaryStatistics::combine));
+
+ for (DoubleSummaryStatistics stats : instances) {
+ assertEquals(stats.getCount(), 1000);
+ assertEquals(stats.getSum(), (double) countTo(1000).stream().mapToInt(i -> i).sum());
+ assertEquals(stats.getAverage(), stats.getSum() / stats.getCount());
+ assertEquals(stats.getMax(), 1000.0);
+ assertEquals(stats.getMin(), 1.0);
+ }
+ }
+}
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ExplodeOpTest.java Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package org.openjdk.tests.java.util.stream;
-
-import org.testng.annotations.Test;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.function.Function;
-import java.util.stream.*;
-
-import static java.util.stream.LambdaTestHelpers.*;
-
-/**
- * ExplodeOpTest
- *
- * @author Brian Goetz
- */
-@Test
-public class ExplodeOpTest extends OpTestCase {
-
- static final Function<Integer, Stream<Integer>> integerRangeMapper
- = e -> IntStream.range(0, e).boxed();
-
- public void testFlatMap() {
- String[] stringsArray = {"hello", "there", "", "yada"};
- Stream<String> strings = Arrays.asList(stringsArray).stream();
- assertConcat(strings.flatMap(flattenChars).iterator(), "hellothereyada");
-
- assertCountSum(countTo(10).stream().flatMap(mfId), 10, 55);
- assertCountSum(countTo(10).stream().flatMap(mfNull), 0, 0);
- assertCountSum(countTo(3).stream().flatMap(mfLt), 6, 4);
-
- exerciseOps(TestData.Factory.ofArray("stringsArray", stringsArray), s -> s.flatMap(flattenChars));
- exerciseOps(TestData.Factory.ofArray("LONG_STRING", new String[] {LONG_STRING}), s -> s.flatMap(flattenChars));
- }
-
- @Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
- public void testOps(String name, TestData.OfRef<Integer> data) {
- Collection<Integer> result = exerciseOps(data, s -> s.flatMap(mfId));
- assertEquals(data.size(), result.size());
-
- result = exerciseOps(data, s -> s.flatMap(mfNull));
- assertEquals(0, result.size());
-
- result = exerciseOps(data, s-> s.flatMap(e -> Stream.empty()));
- assertEquals(0, result.size());
-
- exerciseOps(data, s -> s.flatMap(mfLt));
- exerciseOps(data, s -> s.flatMap(integerRangeMapper));
- exerciseOps(data, s -> s.flatMap((Integer e) -> IntStream.range(0, e).boxed().limit(10)));
- }
-
- //
-
- @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class)
- public void testIntOps(String name, TestData.OfInt data) {
- Collection<Integer> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToInt(j -> j)));
- assertEquals(data.size(), result.size());
- assertContents(data, result);
-
- result = exerciseOps(data, s -> s.flatMap(i -> IntStream.empty()));
- assertEquals(0, result.size());
-
- exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, e)));
- exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, e).limit(10)));
- }
-
- //
-
- @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class)
- public void testLongOps(String name, TestData.OfLong data) {
- Collection<Long> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToLong(j -> j)));
- assertEquals(data.size(), result.size());
- assertContents(data, result);
-
- result = exerciseOps(data, s -> LongStream.empty());
- assertEquals(0, result.size());
-
- exerciseOps(data, s -> s.flatMap(e -> LongStream.range(0, e)));
- exerciseOps(data, s -> s.flatMap(e -> LongStream.range(0, e).limit(10)));
- }
-
- //
-
- @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
- public void testDoubleOps(String name, TestData.OfDouble data) {
- Collection<Double> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToDouble(j -> j)));
- assertEquals(data.size(), result.size());
- assertContents(data, result);
-
- result = exerciseOps(data, s -> DoubleStream.empty());
- assertEquals(0, result.size());
-
- exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).asDoubleStream()));
- exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).limit(10).asDoubleStream()));
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/FlatMapOpTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary flat-map operations
+ * @bug 8044047
+ */
+
+package org.openjdk.tests.java.util.stream;
+
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.function.Function;
+import java.util.stream.*;
+
+import static java.util.stream.LambdaTestHelpers.*;
+import static java.util.stream.ThowableHelper.checkNPE;
+
+@Test
+public class FlatMapOpTest extends OpTestCase {
+
+ public void testNullMapper() {
+ checkNPE(() -> Stream.of(1).flatMap(null));
+ checkNPE(() -> IntStream.of(1).flatMap(null));
+ checkNPE(() -> LongStream.of(1).flatMap(null));
+ checkNPE(() -> DoubleStream.of(1).flatMap(null));
+ }
+
+ static final Function<Integer, Stream<Integer>> integerRangeMapper
+ = e -> IntStream.range(0, e).boxed();
+
+ public void testFlatMap() {
+ String[] stringsArray = {"hello", "there", "", "yada"};
+ Stream<String> strings = Arrays.asList(stringsArray).stream();
+ assertConcat(strings.flatMap(flattenChars).iterator(), "hellothereyada");
+
+ assertCountSum(countTo(10).stream().flatMap(mfId), 10, 55);
+ assertCountSum(countTo(10).stream().flatMap(mfNull), 0, 0);
+ assertCountSum(countTo(3).stream().flatMap(mfLt), 6, 4);
+
+ exerciseOps(TestData.Factory.ofArray("stringsArray", stringsArray), s -> s.flatMap(flattenChars));
+ exerciseOps(TestData.Factory.ofArray("LONG_STRING", new String[] {LONG_STRING}), s -> s.flatMap(flattenChars));
+ }
+
+ @Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
+ public void testOps(String name, TestData.OfRef<Integer> data) {
+ Collection<Integer> result = exerciseOps(data, s -> s.flatMap(mfId));
+ assertEquals(data.size(), result.size());
+
+ result = exerciseOps(data, s -> s.flatMap(mfNull));
+ assertEquals(0, result.size());
+
+ result = exerciseOps(data, s-> s.flatMap(e -> Stream.empty()));
+ assertEquals(0, result.size());
+
+ exerciseOps(data, s -> s.flatMap(mfLt));
+ exerciseOps(data, s -> s.flatMap(integerRangeMapper));
+ exerciseOps(data, s -> s.flatMap((Integer e) -> IntStream.range(0, e).boxed().limit(10)));
+ }
+
+ //
+
+ @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class)
+ public void testIntOps(String name, TestData.OfInt data) {
+ Collection<Integer> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToInt(j -> j)));
+ assertEquals(data.size(), result.size());
+ assertContents(data, result);
+
+ result = exerciseOps(data, s -> s.flatMap(i -> IntStream.empty()));
+ assertEquals(0, result.size());
+
+ exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, e)));
+ exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, e).limit(10)));
+ }
+
+ //
+
+ @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class)
+ public void testLongOps(String name, TestData.OfLong data) {
+ Collection<Long> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToLong(j -> j)));
+ assertEquals(data.size(), result.size());
+ assertContents(data, result);
+
+ result = exerciseOps(data, s -> LongStream.empty());
+ assertEquals(0, result.size());
+
+ exerciseOps(data, s -> s.flatMap(e -> LongStream.range(0, e)));
+ exerciseOps(data, s -> s.flatMap(e -> LongStream.range(0, e).limit(10)));
+ }
+
+ //
+
+ @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
+ public void testDoubleOps(String name, TestData.OfDouble data) {
+ Collection<Double> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToDouble(j -> j)));
+ assertEquals(data.size(), result.size());
+ assertContents(data, result);
+
+ result = exerciseOps(data, s -> DoubleStream.empty());
+ assertEquals(0, result.size());
+
+ exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).asDoubleStream()));
+ exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).limit(10).asDoubleStream()));
+ }
+}
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,7 @@
import java.util.stream.TestData;
import static java.util.stream.Collectors.toList;
+import static java.util.stream.ThowableHelper.checkISE;
@Test
public class StreamBuilderTest extends OpTestCase {
@@ -52,23 +53,6 @@
return sizes.stream().map(i -> new Object[] { i }).toArray(Object[][]::new);
}
- private void checkException(Class<? extends Exception> ce, Runnable r) {
- Exception caught = null;
- try {
- r.run();
- } catch (Exception e) {
- caught = e;
- }
-
- assertNotNull(caught);
- assertTrue(ce.isInstance(caught));
- }
-
- private void checkISE(Runnable r) {
- checkException(IllegalStateException.class, r);
- }
-
- //
@Test
public void testSingleton() {
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamCloseTest.java Thu Jul 17 09:50:06 2014 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamCloseTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -20,6 +20,13 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
+
+/*
+ * @test
+ * @summary close handlers and closing streams
+ * @bug 8044047
+ */
+
package org.openjdk.tests.java.util.stream;
import java.util.Arrays;
@@ -29,14 +36,14 @@
import org.testng.annotations.Test;
import static java.util.stream.LambdaTestHelpers.countTo;
+import static java.util.stream.ThowableHelper.checkNPE;
-/**
- * StreamCloseTest
- *
- * @author Brian Goetz
- */
@Test(groups = { "serialization-hostile" })
public class StreamCloseTest extends OpTestCase {
+ public void testNullCloseHandler() {
+ checkNPE(() -> Stream.of(1).onClose(null));
+ }
+
public void testEmptyCloseHandler() {
try (Stream<Integer> ints = countTo(100).stream()) {
ints.forEach(i -> {});
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SummaryStatisticsTest.java Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package org.openjdk.tests.java.util.stream;
-
-import java.util.ArrayList;
-import java.util.DoubleSummaryStatistics;
-import java.util.IntSummaryStatistics;
-import java.util.List;
-import java.util.LongSummaryStatistics;
-import java.util.stream.Collectors;
-import java.util.stream.OpTestCase;
-
-import org.testng.annotations.Test;
-
-import static java.util.stream.LambdaTestHelpers.countTo;
-
-/**
- * TestSummaryStatistics
- *
- * @author Brian Goetz
- */
-@Test
-public class SummaryStatisticsTest extends OpTestCase {
- public void testIntStatistics() {
- List<IntSummaryStatistics> instances = new ArrayList<>();
- instances.add(countTo(1000).stream().collect(Collectors.summarizingInt(i -> i)));
- instances.add(countTo(1000).stream().mapToInt(i -> i).summaryStatistics());
- instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingInt(i -> i)));
- instances.add(countTo(1000).parallelStream().mapToInt(i -> i).summaryStatistics());
-
- for (IntSummaryStatistics stats : instances) {
- assertEquals(stats.getCount(), 1000);
- assertEquals(stats.getSum(), countTo(1000).stream().mapToInt(i -> i).sum());
- assertEquals(stats.getMax(), 1000);
- assertEquals(stats.getMin(), 1);
- }
- }
-
- public void testLongStatistics() {
- List<LongSummaryStatistics> instances = new ArrayList<>();
- instances.add(countTo(1000).stream().collect(Collectors.summarizingLong(i -> i)));
- instances.add(countTo(1000).stream().mapToLong(i -> i).summaryStatistics());
- instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingLong(i -> i)));
- instances.add(countTo(1000).parallelStream().mapToLong(i -> i).summaryStatistics());
-
- for (LongSummaryStatistics stats : instances) {
- assertEquals(stats.getCount(), 1000);
- assertEquals(stats.getSum(), (long) countTo(1000).stream().mapToInt(i -> i).sum());
- assertEquals(stats.getMax(), 1000L);
- assertEquals(stats.getMin(), 1L);
- }
- }
-
- public void testDoubleStatistics() {
- List<DoubleSummaryStatistics> instances = new ArrayList<>();
- instances.add(countTo(1000).stream().collect(Collectors.summarizingDouble(i -> i)));
- instances.add(countTo(1000).stream().mapToDouble(i -> i).summaryStatistics());
- instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingDouble(i -> i)));
- instances.add(countTo(1000).parallelStream().mapToDouble(i -> i).summaryStatistics());
-
- for (DoubleSummaryStatistics stats : instances) {
- assertEquals(stats.getCount(), 1000);
- assertEquals(stats.getSum(), (double) countTo(1000).stream().mapToInt(i -> i).sum());
- assertEquals(stats.getMax(), 1000.0);
- assertEquals(stats.getMin(), 1.0);
- }
- }
-}
--- a/jdk/test/javax/management/remote/mandatory/util/CacheMapTest.java Thu Jul 17 09:50:06 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 7654321
- * @summary Tests the CacheMap class.
- * @author Eamonn McManus
- * @run clean CacheMapTest
- * @run build CacheMapTest
- * @run main CacheMapTest
- */
-
-import java.util.Iterator;
-import java.util.Map;
-
-import com.sun.jmx.remote.util.CacheMap;
-
-public class CacheMapTest {
- public static void main(String[] args) {
- try {
- boolean ok = test(5) && test(100);
- if (ok) {
- System.out.println("Test completed");
- return;
- } else {
- System.out.println("Test failed!");
- System.exit(1);
- }
- } catch (Exception e) {
- System.err.println("Unexpected exception: " + e);
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- private static boolean test(int cacheSize) throws Exception {
- System.out.println("CacheMap test with cache size " + cacheSize);
- CacheMap map = new CacheMap(cacheSize);
- int size = 0;
- int maxIterations = cacheSize * 10;
- while (map.size() == size && size < maxIterations) {
- Integer key = new Integer(size);
- Object x = map.put(key, "x");
- if (x != null) {
- System.out.println("Map already had entry " + key + "!");
- return false;
- }
- x = map.get(key);
- if (!"x".equals(x)) {
- System.out.println("Got back surprising value: " + x);
- return false;
- }
- size++;
- }
- System.out.println("Map size is " + map.size() + " after inserting " +
- size + " elements");
- do {
- System.gc();
- Thread.sleep(1);
- System.out.println("Map size is " + map.size() + " after GC");
- } while (map.size() > cacheSize);
- if (map.size() < cacheSize) {
- System.out.println("Map shrank to less than cache size: " +
- map.size() + " (surprising but not wrong)");
- } else
- System.out.println("Map shrank to cache size as expected");
- int lowest = size - cacheSize;
- // lowest value that can still be in cache if LRU is respected
- for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
- Map.Entry entry = (Map.Entry) it.next();
- Integer x = (Integer) entry.getKey();
- int xx = x.intValue();
- if (xx < lowest || xx >= size) {
- System.out.println("Old value remained (" + x + "), " +
- "expected none earlier than " + lowest);
- return false;
- }
- Object xxx = entry.getValue();
- if (!"x".equals(xxx)) {
- System.out.println("Got back surprising value: " + xxx);
- return false;
- }
- }
- if (map.size() > 0)
- System.out.println("Remaining elements are the most recent ones");
- System.out.println("Test passed");
- return true;
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JFileChooser/8046391/bug8046391.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8046391
+ * @summary JFileChooser hangs if displayed in Windows L&F
+ * @author Alexey Ivanov
+ * @run main/othervm/timeout=10 bug8046391
+*/
+
+import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
+import sun.awt.OSInfo;
+import sun.awt.OSInfo.OSType;
+
+import javax.swing.JFileChooser;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+
+public class bug8046391 {
+
+ public static void main(String[] args) throws Exception {
+ OSType type = OSInfo.getOSType();
+ if (type != OSType.WINDOWS) {
+ System.out.println("This test is for Windows only... skipping!");
+ return;
+ }
+
+ SwingUtilities.invokeAndWait(() -> {
+ try {
+ UIManager.setLookAndFeel(new WindowsLookAndFeel());
+ } catch (UnsupportedLookAndFeelException e) {
+ e.printStackTrace();
+ }
+ System.out.println("Creating JFileChooser...");
+ JFileChooser fileChooser = new JFileChooser();
+ System.out.println("Test passed: chooser = " + fileChooser);
+ });
+ // Test fails if creating JFileChooser hangs
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JScrollPane/bug8044371.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8044371
+ * @summary setOneTouchExpandable functionality of JSplitPane will reduce vertical Scrollbar
+ * @author Anton Nashatyrev
+ * @library ..
+ */
+
+
+import javax.swing.*;
+import javax.swing.plaf.metal.MetalLookAndFeel;
+import java.awt.*;
+import java.awt.event.AdjustmentEvent;
+import java.awt.event.AdjustmentListener;
+
+public class bug8044371 implements AdjustmentListener {
+ JSplitPane sptPane;
+ int lastAdjust = 0;
+ int initialAdjust = 0;
+
+ public static void main(String[] args) throws Throwable {
+ UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
+ SwingTest.start(bug8044371.class);
+ }
+
+ public bug8044371(JFrame frame) {
+ JPanel p = new JPanel();
+ final JScrollPane jScrollPane = new JScrollPane(new JPanel()
+ {{setPreferredSize(new Dimension(1500,1500));}},
+ JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
+ JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
+ jScrollPane.getViewport().scrollRectToVisible(new Rectangle(1500, 1500, 0, 0));
+ jScrollPane.getVerticalScrollBar().addAdjustmentListener(this);
+
+ sptPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jScrollPane, p);
+ sptPane.setDividerLocation(90);
+ sptPane.setOneTouchExpandable(true);
+ frame.getContentPane().add(sptPane);
+ }
+
+ public void adjustmentValueChanged(AdjustmentEvent e) {
+ System.out.println( "adjustmentValueChanged: " + e.getValue());
+ lastAdjust = e.getValue();
+ }
+
+ public void step1() {
+ if (lastAdjust == 0) {
+ throw new RuntimeException("Adjustment == 0");
+ }
+ initialAdjust = lastAdjust;
+ sptPane.setDividerLocation(0);
+ }
+
+ public void step2() {
+ if (lastAdjust < initialAdjust) {
+ throw new RuntimeException("Failed: Adjustment decreased: " + lastAdjust);
+ }
+ sptPane.setDividerLocation(90);
+ }
+ public void step3() {
+ if (lastAdjust < initialAdjust) {
+ throw new RuntimeException("Failed: Adjustment decreased: " + lastAdjust);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/PopupFactory/8048506/bug8048506.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8048506
+ * @summary Tests that popup with null-owner does not throw NPE
+ * @author Dmitry Markov
+ */
+
+import javax.swing.*;
+import javax.swing.plaf.metal.MetalLookAndFeel;
+
+public class bug8048506 {
+
+ public static void main(String[] args) throws Exception {
+ UIManager.setLookAndFeel(new MetalLookAndFeel());
+
+ SwingUtilities.invokeAndWait(new Runnable() {
+ @Override
+ public void run() {
+ createAndShowGUI();
+ }
+ });
+ System.out.println("The test passed");
+ }
+
+ private static void createAndShowGUI() {
+ JFrame frame = new JFrame("bug8048506");
+ frame.setSize(400, 400);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.setVisible(true);
+
+ PopupFactory factory = PopupFactory.getSharedInstance();
+
+ // Create and show popup with owner
+ Popup popup1 = factory.getPopup(frame, new JLabel("Popup with owner"), 100, 100);
+ popup1.show();
+
+ //Create and show popup without owner
+ Popup popup2 = factory.getPopup(null, new JLabel("Popup without owner"), 200, 200);
+ popup2.show();
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/validation/8049514/FeaturePropagationTest.java Wed Jul 05 19:50:57 2017 +0200
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/**
+ * @test
+ * @bug 8049514
+ * @summary verifies that feature set on the factory is propagated properly
+ * to the validator
+ * @run main/othervm FeaturePropagationTest
+ */
+
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStreamReader;
+import javax.xml.XMLConstants;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.*;
+
+/**
+ * JDK-8049514
+ *
+ * FEATURE_SECURE_PROCESSING can not be turned off on a validator through
+ * SchemaFactory
+ */
+public class FeaturePropagationTest {
+
+ static String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n"
+ + " xmlns:test='jaxp13_test'\n"
+ + " targetNamespace='jaxp13_test'\n"
+ + " elementFormDefault='qualified'>\n"
+ + " <element name='test' type='string'/>\n"
+ + "</schema>\n";
+
+ public static void main(String[] args) throws Exception {
+ InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xsd.getBytes()));
+ StreamSource xsdSource = new StreamSource(reader);
+
+ SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
+ schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
+ Schema schema = null;
+ schema = schemaFactory.newSchema(xsdSource);
+
+ Validator validator = schema.newValidator();
+
+ if (validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
+ throw new RuntimeException("Feature set on the factory is not inherited!");
+ }
+
+ }
+}
--- a/test/Makefile Thu Jul 17 09:50:06 2014 -0700
+++ b/test/Makefile Wed Jul 05 19:50:57 2017 +0200
@@ -66,6 +66,32 @@
hotspot_%:
@$(NO_STOPPING)$(call SUBDIR_TEST, $(HOTSPOT_DIR), TEST="$@" $@)
+#
+# jtreg_tests
+#
+# Invocation:
+#
+# make jtreg_tests TESTDIRS=<test-dirs>
+#
+# where <test-dirs> is something like '../<component>/test/runtime',
+# <component> in turn being one of the top level directories (for
+# example 'hotspot').
+#
+# The below will strip the path prefix and delegate to the
+# corresponding ../<component>/test/Makefile.
+
+ifneq ($(TESTDIRS),)
+# Extract the component from ../<component>/...
+COMPONENT=$(word 2,$(subst /, ,$(TESTDIRS)))
+
+# Strip off the ../<component>/test prefix and pass the rest as TESTDIRS
+# to the delegate Makefile
+TESTDIRS_TESTS=$(patsubst ../$(COMPONENT)/test/%,%,$(TESTDIRS))
+endif
+
+jtreg_tests:
+ @$(NO_STOPPING)$(call SUBDIR_TEST, $(TOPDIR)/$(COMPONENT), TESTDIRS=$(TESTDIRS_TESTS) $@)
+
################################################################
# Phony targets (e.g. these are not filenames)