|
Java example source code file (management.cpp)
The management.cpp Java example source code
/*
* Copyright (c) 2003, 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 "classfile/systemDictionary.hpp"
#include "compiler/compileBroker.hpp"
#include "memory/iterator.hpp"
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
#include "oops/klass.hpp"
#include "oops/objArrayKlass.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/arguments.hpp"
#include "runtime/globals.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jniHandles.hpp"
#include "runtime/os.hpp"
#include "runtime/serviceThread.hpp"
#include "services/classLoadingService.hpp"
#include "services/diagnosticCommand.hpp"
#include "services/diagnosticFramework.hpp"
#include "services/heapDumper.hpp"
#include "services/jmm.h"
#include "services/lowMemoryDetector.hpp"
#include "services/gcNotifier.hpp"
#include "services/nmtDCmd.hpp"
#include "services/management.hpp"
#include "services/memoryManager.hpp"
#include "services/memoryPool.hpp"
#include "services/memoryService.hpp"
#include "services/runtimeService.hpp"
#include "services/threadService.hpp"
#include "utilities/macros.hpp"
PerfVariable* Management::_begin_vm_creation_time = NULL;
PerfVariable* Management::_end_vm_creation_time = NULL;
PerfVariable* Management::_vm_init_done_time = NULL;
Klass* Management::_sensor_klass = NULL;
Klass* Management::_threadInfo_klass = NULL;
Klass* Management::_memoryUsage_klass = NULL;
Klass* Management::_memoryPoolMXBean_klass = NULL;
Klass* Management::_memoryManagerMXBean_klass = NULL;
Klass* Management::_garbageCollectorMXBean_klass = NULL;
Klass* Management::_managementFactory_klass = NULL;
Klass* Management::_garbageCollectorImpl_klass = NULL;
Klass* Management::_gcInfo_klass = NULL;
Klass* Management::_diagnosticCommandImpl_klass = NULL;
Klass* Management::_managementFactoryHelper_klass = NULL;
jmmOptionalSupport Management::_optional_support = {0};
TimeStamp Management::_stamp;
void management_init() {
#if INCLUDE_MANAGEMENT
Management::init();
ThreadService::init();
RuntimeService::init();
ClassLoadingService::init();
#else
ThreadService::init();
// Make sure the VM version is initialized
// This is normally called by RuntimeService::init().
// Since that is conditionalized out, we need to call it here.
Abstract_VM_Version::initialize();
#endif // INCLUDE_MANAGEMENT
}
#if INCLUDE_MANAGEMENT
void Management::init() {
EXCEPTION_MARK;
// These counters are for java.lang.management API support.
// They are created even if -XX:-UsePerfData is set and in
// that case, they will be allocated on C heap.
_begin_vm_creation_time =
PerfDataManager::create_variable(SUN_RT, "createVmBeginTime",
PerfData::U_None, CHECK);
_end_vm_creation_time =
PerfDataManager::create_variable(SUN_RT, "createVmEndTime",
PerfData::U_None, CHECK);
_vm_init_done_time =
PerfDataManager::create_variable(SUN_RT, "vmInitDoneTime",
PerfData::U_None, CHECK);
// Initialize optional support
_optional_support.isLowMemoryDetectionSupported = 1;
_optional_support.isCompilationTimeMonitoringSupported = 1;
_optional_support.isThreadContentionMonitoringSupported = 1;
if (os::is_thread_cpu_time_supported()) {
_optional_support.isCurrentThreadCpuTimeSupported = 1;
_optional_support.isOtherThreadCpuTimeSupported = 1;
} else {
_optional_support.isCurrentThreadCpuTimeSupported = 0;
_optional_support.isOtherThreadCpuTimeSupported = 0;
}
_optional_support.isBootClassPathSupported = 1;
_optional_support.isObjectMonitorUsageSupported = 1;
#if INCLUDE_SERVICES
// This depends on the heap inspector
_optional_support.isSynchronizerUsageSupported = 1;
#endif // INCLUDE_SERVICES
_optional_support.isThreadAllocatedMemorySupported = 1;
_optional_support.isRemoteDiagnosticCommandsSupported = 1;
// Registration of the diagnostic commands
DCmdRegistrant::register_dcmds();
DCmdRegistrant::register_dcmds_ext();
uint32_t full_export = DCmd_Source_Internal | DCmd_Source_AttachAPI
| DCmd_Source_MBean;
DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<NMTDCmd>(full_export, true, false));
}
void Management::initialize(TRAPS) {
// Start the service thread
ServiceThread::initialize();
if (ManagementServer) {
ResourceMark rm(THREAD);
HandleMark hm(THREAD);
// Load and initialize the sun.management.Agent class
// invoke startAgent method to start the management server
Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(),
loader,
Handle(),
true,
CHECK);
instanceKlassHandle ik (THREAD, k);
JavaValue result(T_VOID);
JavaCalls::call_static(&result,
ik,
vmSymbols::startAgent_name(),
vmSymbols::void_method_signature(),
CHECK);
}
}
void Management::get_optional_support(jmmOptionalSupport* support) {
memcpy(support, &_optional_support, sizeof(jmmOptionalSupport));
}
Klass* Management::load_and_initialize_klass(Symbol* sh, TRAPS) {
Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL);
instanceKlassHandle ik (THREAD, k);
if (ik->should_be_initialized()) {
ik->initialize(CHECK_NULL);
}
// If these classes change to not be owned by the boot loader, they need
// to be walked to keep their class loader alive in oops_do.
assert(ik->class_loader() == NULL, "need to follow in oops_do");
return ik();
}
void Management::record_vm_startup_time(jlong begin, jlong duration) {
// if the performance counter is not initialized,
// then vm initialization failed; simply return.
if (_begin_vm_creation_time == NULL) return;
_begin_vm_creation_time->set_value(begin);
_end_vm_creation_time->set_value(begin + duration);
PerfMemory::set_accessible(true);
}
jlong Management::timestamp() {
TimeStamp t;
t.update();
return t.ticks() - _stamp.ticks();
}
void Management::oops_do(OopClosure* f) {
MemoryService::oops_do(f);
ThreadService::oops_do(f);
}
Klass* Management::java_lang_management_ThreadInfo_klass(TRAPS) {
if (_threadInfo_klass == NULL) {
_threadInfo_klass = load_and_initialize_klass(vmSymbols::java_lang_management_ThreadInfo(), CHECK_NULL);
}
return _threadInfo_klass;
}
Klass* Management::java_lang_management_MemoryUsage_klass(TRAPS) {
if (_memoryUsage_klass == NULL) {
_memoryUsage_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryUsage(), CHECK_NULL);
}
return _memoryUsage_klass;
}
Klass* Management::java_lang_management_MemoryPoolMXBean_klass(TRAPS) {
if (_memoryPoolMXBean_klass == NULL) {
_memoryPoolMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryPoolMXBean(), CHECK_NULL);
}
return _memoryPoolMXBean_klass;
}
Klass* Management::java_lang_management_MemoryManagerMXBean_klass(TRAPS) {
if (_memoryManagerMXBean_klass == NULL) {
_memoryManagerMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryManagerMXBean(), CHECK_NULL);
}
return _memoryManagerMXBean_klass;
}
Klass* Management::java_lang_management_GarbageCollectorMXBean_klass(TRAPS) {
if (_garbageCollectorMXBean_klass == NULL) {
_garbageCollectorMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_GarbageCollectorMXBean(), CHECK_NULL);
}
return _garbageCollectorMXBean_klass;
}
Klass* Management::sun_management_Sensor_klass(TRAPS) {
if (_sensor_klass == NULL) {
_sensor_klass = load_and_initialize_klass(vmSymbols::sun_management_Sensor(), CHECK_NULL);
}
return _sensor_klass;
}
Klass* Management::sun_management_ManagementFactory_klass(TRAPS) {
if (_managementFactory_klass == NULL) {
_managementFactory_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactory(), CHECK_NULL);
}
return _managementFactory_klass;
}
Klass* Management::sun_management_GarbageCollectorImpl_klass(TRAPS) {
if (_garbageCollectorImpl_klass == NULL) {
_garbageCollectorImpl_klass = load_and_initialize_klass(vmSymbols::sun_management_GarbageCollectorImpl(), CHECK_NULL);
}
return _garbageCollectorImpl_klass;
}
Klass* Management::com_sun_management_GcInfo_klass(TRAPS) {
if (_gcInfo_klass == NULL) {
_gcInfo_klass = load_and_initialize_klass(vmSymbols::com_sun_management_GcInfo(), CHECK_NULL);
}
return _gcInfo_klass;
}
Klass* Management::sun_management_DiagnosticCommandImpl_klass(TRAPS) {
if (_diagnosticCommandImpl_klass == NULL) {
_diagnosticCommandImpl_klass = load_and_initialize_klass(vmSymbols::sun_management_DiagnosticCommandImpl(), CHECK_NULL);
}
return _diagnosticCommandImpl_klass;
}
Klass* Management::sun_management_ManagementFactoryHelper_klass(TRAPS) {
if (_managementFactoryHelper_klass == NULL) {
_managementFactoryHelper_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactoryHelper(), CHECK_NULL);
}
return _managementFactoryHelper_klass;
}
static void initialize_ThreadInfo_constructor_arguments(JavaCallArguments* args, ThreadSnapshot* snapshot, TRAPS) {
Handle snapshot_thread(THREAD, snapshot->threadObj());
jlong contended_time;
jlong waited_time;
if (ThreadService::is_thread_monitoring_contention()) {
contended_time = Management::ticks_to_ms(snapshot->contended_enter_ticks());
waited_time = Management::ticks_to_ms(snapshot->monitor_wait_ticks() + snapshot->sleep_ticks());
} else {
// set them to -1 if thread contention monitoring is disabled.
contended_time = max_julong;
waited_time = max_julong;
}
int thread_status = snapshot->thread_status();
assert((thread_status & JMM_THREAD_STATE_FLAG_MASK) == 0, "Flags already set in thread_status in Thread object");
if (snapshot->is_ext_suspended()) {
thread_status |= JMM_THREAD_STATE_FLAG_SUSPENDED;
}
if (snapshot->is_in_native()) {
thread_status |= JMM_THREAD_STATE_FLAG_NATIVE;
}
ThreadStackTrace* st = snapshot->get_stack_trace();
Handle stacktrace_h;
if (st != NULL) {
stacktrace_h = st->allocate_fill_stack_trace_element_array(CHECK);
} else {
stacktrace_h = Handle();
}
args->push_oop(snapshot_thread);
args->push_int(thread_status);
args->push_oop(Handle(THREAD, snapshot->blocker_object()));
args->push_oop(Handle(THREAD, snapshot->blocker_object_owner()));
args->push_long(snapshot->contended_enter_count());
args->push_long(contended_time);
args->push_long(snapshot->monitor_wait_count() + snapshot->sleep_count());
args->push_long(waited_time);
args->push_oop(stacktrace_h);
}
// Helper function to construct a ThreadInfo object
instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot, TRAPS) {
Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
instanceKlassHandle ik (THREAD, k);
JavaValue result(T_VOID);
JavaCallArguments args(14);
// First allocate a ThreadObj object and
// push the receiver as the first argument
Handle element = ik->allocate_instance_handle(CHECK_NULL);
args.push_oop(element);
// initialize the arguments for the ThreadInfo constructor
initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);
// Call ThreadInfo constructor with no locked monitors and synchronizers
JavaCalls::call_special(&result,
ik,
vmSymbols::object_initializer_name(),
vmSymbols::java_lang_management_ThreadInfo_constructor_signature(),
&args,
CHECK_NULL);
return (instanceOop) element();
}
instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot,
objArrayHandle monitors_array,
typeArrayHandle depths_array,
objArrayHandle synchronizers_array,
TRAPS) {
Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
instanceKlassHandle ik (THREAD, k);
JavaValue result(T_VOID);
JavaCallArguments args(17);
// First allocate a ThreadObj object and
// push the receiver as the first argument
Handle element = ik->allocate_instance_handle(CHECK_NULL);
args.push_oop(element);
// initialize the arguments for the ThreadInfo constructor
initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);
// push the locked monitors and synchronizers in the arguments
args.push_oop(monitors_array);
args.push_oop(depths_array);
args.push_oop(synchronizers_array);
// Call ThreadInfo constructor with locked monitors and synchronizers
JavaCalls::call_special(&result,
ik,
vmSymbols::object_initializer_name(),
vmSymbols::java_lang_management_ThreadInfo_with_locks_constructor_signature(),
&args,
CHECK_NULL);
return (instanceOop) element();
}
// Helper functions
static JavaThread* find_java_thread_from_id(jlong thread_id) {
assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
JavaThread* java_thread = NULL;
// Sequential search for now. Need to do better optimization later.
for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
oop tobj = thread->threadObj();
if (!thread->is_exiting() &&
tobj != NULL &&
thread_id == java_lang_Thread::thread_id(tobj)) {
java_thread = thread;
break;
}
}
return java_thread;
}
static GCMemoryManager* get_gc_memory_manager_from_jobject(jobject mgr, TRAPS) {
if (mgr == NULL) {
THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
}
oop mgr_obj = JNIHandles::resolve(mgr);
instanceHandle h(THREAD, (instanceOop) mgr_obj);
Klass* k = Management::java_lang_management_GarbageCollectorMXBean_klass(CHECK_NULL);
if (!h->is_a(k)) {
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
"the object is not an instance of java.lang.management.GarbageCollectorMXBean class",
NULL);
}
MemoryManager* gc = MemoryService::get_memory_manager(h);
if (gc == NULL || !gc->is_gc_memory_manager()) {
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
"Invalid GC memory manager",
NULL);
}
return (GCMemoryManager*) gc;
}
static MemoryPool* get_memory_pool_from_jobject(jobject obj, TRAPS) {
if (obj == NULL) {
THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
}
oop pool_obj = JNIHandles::resolve(obj);
assert(pool_obj->is_instance(), "Should be an instanceOop");
instanceHandle ph(THREAD, (instanceOop) pool_obj);
return MemoryService::get_memory_pool(ph);
}
static void validate_thread_id_array(typeArrayHandle ids_ah, TRAPS) {
int num_threads = ids_ah->length();
// Validate input thread IDs
int i = 0;
for (i = 0; i < num_threads; i++) {
jlong tid = ids_ah->long_at(i);
if (tid <= 0) {
// throw exception if invalid thread id.
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"Invalid thread ID entry");
}
}
}
static void validate_thread_info_array(objArrayHandle infoArray_h, TRAPS) {
// check if the element of infoArray is of type ThreadInfo class
Klass* threadinfo_klass = Management::java_lang_management_ThreadInfo_klass(CHECK);
Klass* element_klass = ObjArrayKlass::cast(infoArray_h->klass())->element_klass();
if (element_klass != threadinfo_klass) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"infoArray element type is not ThreadInfo class");
}
}
static MemoryManager* get_memory_manager_from_jobject(jobject obj, TRAPS) {
if (obj == NULL) {
THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
}
oop mgr_obj = JNIHandles::resolve(obj);
assert(mgr_obj->is_instance(), "Should be an instanceOop");
instanceHandle mh(THREAD, (instanceOop) mgr_obj);
return MemoryService::get_memory_manager(mh);
}
// Returns a version string and sets major and minor version if
// the input parameters are non-null.
JVM_LEAF(jint, jmm_GetVersion(JNIEnv *env))
return JMM_VERSION;
JVM_END
// Gets the list of VM monitoring and management optional supports
// Returns 0 if succeeded; otherwise returns non-zero.
JVM_LEAF(jint, jmm_GetOptionalSupport(JNIEnv *env, jmmOptionalSupport* support))
if (support == NULL) {
return -1;
}
Management::get_optional_support(support);
return 0;
JVM_END
// Returns a java.lang.String object containing the input arguments to the VM.
JVM_ENTRY(jobject, jmm_GetInputArguments(JNIEnv *env))
ResourceMark rm(THREAD);
if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
return NULL;
}
char** vm_flags = Arguments::jvm_flags_array();
char** vm_args = Arguments::jvm_args_array();
int num_flags = Arguments::num_jvm_flags();
int num_args = Arguments::num_jvm_args();
size_t length = 1; // null terminator
int i;
for (i = 0; i < num_flags; i++) {
length += strlen(vm_flags[i]);
}
for (i = 0; i < num_args; i++) {
length += strlen(vm_args[i]);
}
// add a space between each argument
length += num_flags + num_args - 1;
// Return the list of input arguments passed to the VM
// and preserve the order that the VM processes.
char* args = NEW_RESOURCE_ARRAY(char, length);
args[0] = '\0';
// concatenate all jvm_flags
if (num_flags > 0) {
strcat(args, vm_flags[0]);
for (i = 1; i < num_flags; i++) {
strcat(args, " ");
strcat(args, vm_flags[i]);
}
}
if (num_args > 0 && num_flags > 0) {
// append a space if args already contains one or more jvm_flags
strcat(args, " ");
}
// concatenate all jvm_args
if (num_args > 0) {
strcat(args, vm_args[0]);
for (i = 1; i < num_args; i++) {
strcat(args, " ");
strcat(args, vm_args[i]);
}
}
Handle hargs = java_lang_String::create_from_platform_dependent_str(args, CHECK_NULL);
return JNIHandles::make_local(env, hargs());
JVM_END
// Returns an array of java.lang.String object containing the input arguments to the VM.
JVM_ENTRY(jobjectArray, jmm_GetInputArgumentArray(JNIEnv *env))
ResourceMark rm(THREAD);
if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
return NULL;
}
char** vm_flags = Arguments::jvm_flags_array();
char** vm_args = Arguments::jvm_args_array();
int num_flags = Arguments::num_jvm_flags();
int num_args = Arguments::num_jvm_args();
instanceKlassHandle ik (THREAD, SystemDictionary::String_klass());
objArrayOop r = oopFactory::new_objArray(ik(), num_args + num_flags, CHECK_NULL);
objArrayHandle result_h(THREAD, r);
int index = 0;
for (int j = 0; j < num_flags; j++, index++) {
Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
result_h->obj_at_put(index, h());
}
for (int i = 0; i < num_args; i++, index++) {
Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
result_h->obj_at_put(index, h());
}
return (jobjectArray) JNIHandles::make_local(env, result_h());
JVM_END
// Returns an array of java/lang/management/MemoryPoolMXBean object
// one for each memory pool if obj == null; otherwise returns
// an array of memory pools for a given memory manager if
// it is a valid memory manager.
JVM_ENTRY(jobjectArray, jmm_GetMemoryPools(JNIEnv* env, jobject obj))
ResourceMark rm(THREAD);
int num_memory_pools;
MemoryManager* mgr = NULL;
if (obj == NULL) {
num_memory_pools = MemoryService::num_memory_pools();
} else {
mgr = get_memory_manager_from_jobject(obj, CHECK_NULL);
if (mgr == NULL) {
return NULL;
}
num_memory_pools = mgr->num_memory_pools();
}
// Allocate the resulting MemoryPoolMXBean[] object
Klass* k = Management::java_lang_management_MemoryPoolMXBean_klass(CHECK_NULL);
instanceKlassHandle ik (THREAD, k);
objArrayOop r = oopFactory::new_objArray(ik(), num_memory_pools, CHECK_NULL);
objArrayHandle poolArray(THREAD, r);
if (mgr == NULL) {
// Get all memory pools
for (int i = 0; i < num_memory_pools; i++) {
MemoryPool* pool = MemoryService::get_memory_pool(i);
instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);
instanceHandle ph(THREAD, p);
poolArray->obj_at_put(i, ph());
}
} else {
// Get memory pools managed by a given memory manager
for (int i = 0; i < num_memory_pools; i++) {
MemoryPool* pool = mgr->get_memory_pool(i);
instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);
instanceHandle ph(THREAD, p);
poolArray->obj_at_put(i, ph());
}
}
return (jobjectArray) JNIHandles::make_local(env, poolArray());
JVM_END
// Returns an array of java/lang/management/MemoryManagerMXBean object
// one for each memory manager if obj == null; otherwise returns
// an array of memory managers for a given memory pool if
// it is a valid memory pool.
JVM_ENTRY(jobjectArray, jmm_GetMemoryManagers(JNIEnv* env, jobject obj))
ResourceMark rm(THREAD);
int num_mgrs;
MemoryPool* pool = NULL;
if (obj == NULL) {
num_mgrs = MemoryService::num_memory_managers();
} else {
pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
if (pool == NULL) {
return NULL;
}
num_mgrs = pool->num_memory_managers();
}
// Allocate the resulting MemoryManagerMXBean[] object
Klass* k = Management::java_lang_management_MemoryManagerMXBean_klass(CHECK_NULL);
instanceKlassHandle ik (THREAD, k);
objArrayOop r = oopFactory::new_objArray(ik(), num_mgrs, CHECK_NULL);
objArrayHandle mgrArray(THREAD, r);
if (pool == NULL) {
// Get all memory managers
for (int i = 0; i < num_mgrs; i++) {
MemoryManager* mgr = MemoryService::get_memory_manager(i);
instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);
instanceHandle ph(THREAD, p);
mgrArray->obj_at_put(i, ph());
}
} else {
// Get memory managers for a given memory pool
for (int i = 0; i < num_mgrs; i++) {
MemoryManager* mgr = pool->get_memory_manager(i);
instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);
instanceHandle ph(THREAD, p);
mgrArray->obj_at_put(i, ph());
}
}
return (jobjectArray) JNIHandles::make_local(env, mgrArray());
JVM_END
// Returns a java/lang/management/MemoryUsage object containing the memory usage
// of a given memory pool.
JVM_ENTRY(jobject, jmm_GetMemoryPoolUsage(JNIEnv* env, jobject obj))
ResourceMark rm(THREAD);
MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
if (pool != NULL) {
MemoryUsage usage = pool->get_memory_usage();
Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
return JNIHandles::make_local(env, h());
} else {
return NULL;
}
JVM_END
// Returns a java/lang/management/MemoryUsage object containing the memory usage
// of a given memory pool.
JVM_ENTRY(jobject, jmm_GetPeakMemoryPoolUsage(JNIEnv* env, jobject obj))
ResourceMark rm(THREAD);
MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
if (pool != NULL) {
MemoryUsage usage = pool->get_peak_memory_usage();
Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
return JNIHandles::make_local(env, h());
} else {
return NULL;
}
JVM_END
// Returns a java/lang/management/MemoryUsage object containing the memory usage
// of a given memory pool after most recent GC.
JVM_ENTRY(jobject, jmm_GetPoolCollectionUsage(JNIEnv* env, jobject obj))
ResourceMark rm(THREAD);
MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
if (pool != NULL && pool->is_collected_pool()) {
MemoryUsage usage = pool->get_last_collection_usage();
Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
return JNIHandles::make_local(env, h());
} else {
return NULL;
}
JVM_END
// Sets the memory pool sensor for a threshold type
JVM_ENTRY(void, jmm_SetPoolSensor(JNIEnv* env, jobject obj, jmmThresholdType type, jobject sensorObj))
if (obj == NULL || sensorObj == NULL) {
THROW(vmSymbols::java_lang_NullPointerException());
}
Klass* sensor_klass = Management::sun_management_Sensor_klass(CHECK);
oop s = JNIHandles::resolve(sensorObj);
assert(s->is_instance(), "Sensor should be an instanceOop");
instanceHandle sensor_h(THREAD, (instanceOop) s);
if (!sensor_h->is_a(sensor_klass)) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"Sensor is not an instance of sun.management.Sensor class");
}
MemoryPool* mpool = get_memory_pool_from_jobject(obj, CHECK);
assert(mpool != NULL, "MemoryPool should exist");
switch (type) {
case JMM_USAGE_THRESHOLD_HIGH:
case JMM_USAGE_THRESHOLD_LOW:
// have only one sensor for threshold high and low
mpool->set_usage_sensor_obj(sensor_h);
break;
case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:
case JMM_COLLECTION_USAGE_THRESHOLD_LOW:
// have only one sensor for threshold high and low
mpool->set_gc_usage_sensor_obj(sensor_h);
break;
default:
assert(false, "Unrecognized type");
}
JVM_END
// Sets the threshold of a given memory pool.
// Returns the previous threshold.
//
// Input parameters:
// pool - the MemoryPoolMXBean object
// type - threshold type
// threshold - the new threshold (must not be negative)
//
JVM_ENTRY(jlong, jmm_SetPoolThreshold(JNIEnv* env, jobject obj, jmmThresholdType type, jlong threshold))
if (threshold < 0) {
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
"Invalid threshold value",
-1);
}
if ((size_t)threshold > max_uintx) {
stringStream st;
st.print("Invalid valid threshold value. Threshold value (" UINT64_FORMAT ") > max value of size_t (" SIZE_FORMAT ")", (size_t)threshold, max_uintx);
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), st.as_string(), -1);
}
MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_(0L));
assert(pool != NULL, "MemoryPool should exist");
jlong prev = 0;
switch (type) {
case JMM_USAGE_THRESHOLD_HIGH:
if (!pool->usage_threshold()->is_high_threshold_supported()) {
return -1;
}
prev = pool->usage_threshold()->set_high_threshold((size_t) threshold);
break;
case JMM_USAGE_THRESHOLD_LOW:
if (!pool->usage_threshold()->is_low_threshold_supported()) {
return -1;
}
prev = pool->usage_threshold()->set_low_threshold((size_t) threshold);
break;
case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:
if (!pool->gc_usage_threshold()->is_high_threshold_supported()) {
return -1;
}
// return and the new threshold is effective for the next GC
return pool->gc_usage_threshold()->set_high_threshold((size_t) threshold);
case JMM_COLLECTION_USAGE_THRESHOLD_LOW:
if (!pool->gc_usage_threshold()->is_low_threshold_supported()) {
return -1;
}
// return and the new threshold is effective for the next GC
return pool->gc_usage_threshold()->set_low_threshold((size_t) threshold);
default:
assert(false, "Unrecognized type");
return -1;
}
// When the threshold is changed, reevaluate if the low memory
// detection is enabled.
if (prev != threshold) {
LowMemoryDetector::recompute_enabled_for_collected_pools();
LowMemoryDetector::detect_low_memory(pool);
}
return prev;
JVM_END
// Gets an array containing the amount of memory allocated on the Java
// heap for a set of threads (in bytes). Each element of the array is
// the amount of memory allocated for the thread ID specified in the
// corresponding entry in the given array of thread IDs; or -1 if the
// thread does not exist or has terminated.
JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids,
jlongArray sizeArray))
// Check if threads is null
if (ids == NULL || sizeArray == NULL) {
THROW(vmSymbols::java_lang_NullPointerException());
}
ResourceMark rm(THREAD);
typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
typeArrayHandle ids_ah(THREAD, ta);
typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray));
typeArrayHandle sizeArray_h(THREAD, sa);
// validate the thread id array
validate_thread_id_array(ids_ah, CHECK);
// sizeArray must be of the same length as the given array of thread IDs
int num_threads = ids_ah->length();
if (num_threads != sizeArray_h->length()) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"The length of the given long array does not match the length of "
"the given array of thread IDs");
}
MutexLockerEx ml(Threads_lock);
for (int i = 0; i < num_threads; i++) {
JavaThread* java_thread = find_java_thread_from_id(ids_ah->long_at(i));
if (java_thread != NULL) {
sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes());
}
}
JVM_END
// Returns a java/lang/management/MemoryUsage object representing
// the memory usage for the heap or non-heap memory.
JVM_ENTRY(jobject, jmm_GetMemoryUsage(JNIEnv* env, jboolean heap))
ResourceMark rm(THREAD);
// Calculate the memory usage
size_t total_init = 0;
size_t total_used = 0;
size_t total_committed = 0;
size_t total_max = 0;
bool has_undefined_init_size = false;
bool has_undefined_max_size = false;
for (int i = 0; i < MemoryService::num_memory_pools(); i++) {
MemoryPool* pool = MemoryService::get_memory_pool(i);
if ((heap && pool->is_heap()) || (!heap && pool->is_non_heap())) {
MemoryUsage u = pool->get_memory_usage();
total_used += u.used();
total_committed += u.committed();
if (u.init_size() == (size_t)-1) {
has_undefined_init_size = true;
}
if (!has_undefined_init_size) {
total_init += u.init_size();
}
if (u.max_size() == (size_t)-1) {
has_undefined_max_size = true;
}
if (!has_undefined_max_size) {
total_max += u.max_size();
}
}
}
// if any one of the memory pool has undefined init_size or max_size,
// set it to -1
if (has_undefined_init_size) {
total_init = (size_t)-1;
}
if (has_undefined_max_size) {
total_max = (size_t)-1;
}
MemoryUsage usage((heap ? InitialHeapSize : total_init),
total_used,
total_committed,
(heap ? Universe::heap()->max_capacity() : total_max));
Handle obj = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
return JNIHandles::make_local(env, obj());
JVM_END
// Returns the boolean value of a given attribute.
JVM_LEAF(jboolean, jmm_GetBoolAttribute(JNIEnv *env, jmmBoolAttribute att))
switch (att) {
case JMM_VERBOSE_GC:
return MemoryService::get_verbose();
case JMM_VERBOSE_CLASS:
return ClassLoadingService::get_verbose();
case JMM_THREAD_CONTENTION_MONITORING:
return ThreadService::is_thread_monitoring_contention();
case JMM_THREAD_CPU_TIME:
return ThreadService::is_thread_cpu_time_enabled();
case JMM_THREAD_ALLOCATED_MEMORY:
return ThreadService::is_thread_allocated_memory_enabled();
default:
assert(0, "Unrecognized attribute");
return false;
}
JVM_END
// Sets the given boolean attribute and returns the previous value.
JVM_ENTRY(jboolean, jmm_SetBoolAttribute(JNIEnv *env, jmmBoolAttribute att, jboolean flag))
switch (att) {
case JMM_VERBOSE_GC:
return MemoryService::set_verbose(flag != 0);
case JMM_VERBOSE_CLASS:
return ClassLoadingService::set_verbose(flag != 0);
case JMM_THREAD_CONTENTION_MONITORING:
return ThreadService::set_thread_monitoring_contention(flag != 0);
case JMM_THREAD_CPU_TIME:
return ThreadService::set_thread_cpu_time_enabled(flag != 0);
case JMM_THREAD_ALLOCATED_MEMORY:
return ThreadService::set_thread_allocated_memory_enabled(flag != 0);
default:
assert(0, "Unrecognized attribute");
return false;
}
JVM_END
static jlong get_gc_attribute(GCMemoryManager* mgr, jmmLongAttribute att) {
switch (att) {
case JMM_GC_TIME_MS:
return mgr->gc_time_ms();
case JMM_GC_COUNT:
return mgr->gc_count();
case JMM_GC_EXT_ATTRIBUTE_INFO_SIZE:
// current implementation only has 1 ext attribute
return 1;
default:
assert(0, "Unrecognized GC attribute");
return -1;
}
}
class VmThreadCountClosure: public ThreadClosure {
private:
int _count;
public:
VmThreadCountClosure() : _count(0) {};
void do_thread(Thread* thread);
int count() { return _count; }
};
void VmThreadCountClosure::do_thread(Thread* thread) {
// exclude externally visible JavaThreads
if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {
return;
}
_count++;
}
static jint get_vm_thread_count() {
VmThreadCountClosure vmtcc;
{
MutexLockerEx ml(Threads_lock);
Threads::threads_do(&vmtcc);
}
return vmtcc.count();
}
static jint get_num_flags() {
// last flag entry is always NULL, so subtract 1
int nFlags = (int) Flag::numFlags - 1;
int count = 0;
for (int i = 0; i < nFlags; i++) {
Flag* flag = &Flag::flags[i];
// Exclude the locked (diagnostic, experimental) flags
if (flag->is_unlocked() || flag->is_unlocker()) {
count++;
}
}
return count;
}
static jlong get_long_attribute(jmmLongAttribute att) {
switch (att) {
case JMM_CLASS_LOADED_COUNT:
return ClassLoadingService::loaded_class_count();
case JMM_CLASS_UNLOADED_COUNT:
return ClassLoadingService::unloaded_class_count();
case JMM_THREAD_TOTAL_COUNT:
return ThreadService::get_total_thread_count();
case JMM_THREAD_LIVE_COUNT:
return ThreadService::get_live_thread_count();
case JMM_THREAD_PEAK_COUNT:
return ThreadService::get_peak_thread_count();
case JMM_THREAD_DAEMON_COUNT:
return ThreadService::get_daemon_thread_count();
case JMM_JVM_INIT_DONE_TIME_MS:
return Management::vm_init_done_time();
case JMM_JVM_UPTIME_MS:
return Management::ticks_to_ms(os::elapsed_counter());
case JMM_COMPILE_TOTAL_TIME_MS:
return Management::ticks_to_ms(CompileBroker::total_compilation_ticks());
case JMM_OS_PROCESS_ID:
return os::current_process_id();
// Hotspot-specific counters
case JMM_CLASS_LOADED_BYTES:
return ClassLoadingService::loaded_class_bytes();
case JMM_CLASS_UNLOADED_BYTES:
return ClassLoadingService::unloaded_class_bytes();
case JMM_SHARED_CLASS_LOADED_COUNT:
return ClassLoadingService::loaded_shared_class_count();
case JMM_SHARED_CLASS_UNLOADED_COUNT:
return ClassLoadingService::unloaded_shared_class_count();
case JMM_SHARED_CLASS_LOADED_BYTES:
return ClassLoadingService::loaded_shared_class_bytes();
case JMM_SHARED_CLASS_UNLOADED_BYTES:
return ClassLoadingService::unloaded_shared_class_bytes();
case JMM_TOTAL_CLASSLOAD_TIME_MS:
return ClassLoader::classloader_time_ms();
case JMM_VM_GLOBAL_COUNT:
return get_num_flags();
case JMM_SAFEPOINT_COUNT:
return RuntimeService::safepoint_count();
case JMM_TOTAL_SAFEPOINTSYNC_TIME_MS:
return RuntimeService::safepoint_sync_time_ms();
case JMM_TOTAL_STOPPED_TIME_MS:
return RuntimeService::safepoint_time_ms();
case JMM_TOTAL_APP_TIME_MS:
return RuntimeService::application_time_ms();
case JMM_VM_THREAD_COUNT:
return get_vm_thread_count();
case JMM_CLASS_INIT_TOTAL_COUNT:
return ClassLoader::class_init_count();
case JMM_CLASS_INIT_TOTAL_TIME_MS:
return ClassLoader::class_init_time_ms();
case JMM_CLASS_VERIFY_TOTAL_TIME_MS:
return ClassLoader::class_verify_time_ms();
case JMM_METHOD_DATA_SIZE_BYTES:
return ClassLoadingService::class_method_data_size();
case JMM_OS_MEM_TOTAL_PHYSICAL_BYTES:
return os::physical_memory();
default:
return -1;
}
}
// Returns the long value of a given attribute.
JVM_ENTRY(jlong, jmm_GetLongAttribute(JNIEnv *env, jobject obj, jmmLongAttribute att))
if (obj == NULL) {
return get_long_attribute(att);
} else {
GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_(0L));
if (mgr != NULL) {
return get_gc_attribute(mgr, att);
}
}
return -1;
JVM_END
// Gets the value of all attributes specified in the given array
// and sets the value in the result array.
// Returns the number of attributes found.
JVM_ENTRY(jint, jmm_GetLongAttributes(JNIEnv *env,
jobject obj,
jmmLongAttribute* atts,
jint count,
jlong* result))
int num_atts = 0;
if (obj == NULL) {
for (int i = 0; i < count; i++) {
result[i] = get_long_attribute(atts[i]);
if (result[i] != -1) {
num_atts++;
}
}
} else {
GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_0);
for (int i = 0; i < count; i++) {
result[i] = get_gc_attribute(mgr, atts[i]);
if (result[i] != -1) {
num_atts++;
}
}
}
return num_atts;
JVM_END
// Helper function to do thread dump for a specific list of threads
static void do_thread_dump(ThreadDumpResult* dump_result,
typeArrayHandle ids_ah, // array of thread ID (long[])
int num_threads,
int max_depth,
bool with_locked_monitors,
bool with_locked_synchronizers,
TRAPS) {
// First get an array of threadObj handles.
// A JavaThread may terminate before we get the stack trace.
GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray
Other Java examples (source code examples)Here is a short list of links related to this Java management.cpp source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.