public final class Jvm extends Object
| Modifier and Type | Class and Description |
|---|---|
static interface |
Jvm.SignalHandler |
| Modifier and Type | Field and Description |
|---|---|
static String |
JAVA_CLASS_PATH |
static String |
SYSTEM_PROPERTIES |
| Modifier and Type | Method and Description |
|---|---|
static long |
address(@NotNull ByteBuffer byteBuffer)
Returns the native address of the provided
byteBuffer. |
static void |
addSignalHandler(Jvm.SignalHandler signalHandler)
Adds the provided
signalHandler to an internal chain of handlers that will be invoked
upon detecting system signals (e.g. |
static void |
addToClassPath(@NotNull Class<?> clazz)
Ensures that all the jars and other resources are added to the class path of the classloader
associated by the provided
clazz. |
static boolean |
areOptionalSafepointsEnabled() |
static int |
arrayByteBaseOffset()
Returns the array byte base offset used by this JVM.
|
static void |
busyWaitMicros(long durationUs)
Pause in a busy loop for the provided
durationUs microseconds. |
static void |
busyWaitUntil(long waitUntilNs)
Pauses the current thread in a busy loop until the provided
waitUntilNs time is reached. |
static @NotNull ClassMetrics |
classMetrics(Class<?> clazz)
Acquires and returns the ClassMetrics for the provided
clazz. |
static int |
compileThreshold()
Returns the compile threshold for the JVM or else an
estimate thereof (e.g.
|
static long |
currentThreadId()
Retrieves the unique identifier of the current thread.
|
static @NotNull ExceptionHandler |
debug()
Returns an ExceptionHandler for debug messages, this prints as System.out or DEBUG level logging.
|
static void |
disableDebugHandler() |
static void |
disablePerfHandler() |
static void |
disableWarnHandler() |
static void |
doNotCloseOnInterrupt(Class<?> clazz,
FileChannel fc)
Employs a best-effort of preventing the provided
fc from being automatically closed
whenever the current thread gets interrupted. |
static boolean |
dontChain(Class<?> tClass) |
static void |
dumpException(@NotNull Map<ExceptionKey,Integer> exceptions) |
static @NotNull ExceptionHandler |
error()
Returns an ExceptionHandler for errors, this prints as System.err or ERROR level logging.
|
static long |
fieldOffset(Class<?> clazz,
String fieldName) |
static <A extends Annotation> |
findAnnotation(AnnotatedElement annotatedElement,
Class<A> annotationType)
Retrieve an annotation of the specified
annotationType that is present on the given
annotatedElement, including considering nested annotations and method inheritance. |
static boolean |
getBoolean(String systemPropertyKey)
Returns if a System Property with the provided
systemPropertyKey
either exists, is set to "yes" or is set to "true". |
static boolean |
getBoolean(String systemPropertyKey,
boolean defaultValue)
Returns if a System Property with the provided
systemPropertyKey
either exists, is set to "yes" or is set to "true" or, if it does not exist,
returns the provided defaultValue. |
static String |
getCpuClass() |
static double |
getDouble(String systemPropertyKey,
double defaultValue)
Returns the System Property associated with the provided
systemPropertyKey
parsed as a double or, if no such parsable System Property exists,
returns the provided defaultValue. |
static @NotNull Field |
getField(@NotNull Class<?> clazz,
@NotNull String fieldName)
Returns the Field for the provided
clazz and the provided fieldName or
throws an Exception if no such Field exists. |
static @Nullable Field |
getFieldOrNull(@NotNull Class<?> clazz,
@NotNull String fieldName)
Returns the Field for the provided
clazz and the provided fieldName or null
if no such Field exists. |
static Integer |
getInteger(String systemPropertyKey,
Integer defVal)
Guarantees that Jvm class is initialized before property is read.
|
static Long |
getLong(String systemPropertyKey,
Long defVal)
Guarantees that Jvm class is initialized before property is read.
|
static @NotNull Method |
getMethod(@NotNull Class<?> clazz,
@NotNull String methodName,
Class<?>... argTypes)
Returns the Method for the provided
clazz, methodName and
argTypes or throws an Exception. |
static String |
getPackageName(Class clazz)
Returns the package name of the specified class.
|
static int |
getProcessId()
Returns the current process id.
|
static String |
getProperty(String systemPropertyKey)
Guarantees that Jvm class is initialized before property is read.
|
static String |
getProperty(String systemPropertyKey,
String defaultValue)
Guarantees that Jvm class is initialized before property is read.
|
static long |
getSize(String property,
long defaultValue)
Uses Jvm.parseSize to parse a system property or returns defaultValue if not present, empty or unparseable.
|
static <V> V |
getValue(@NotNull Object target,
@NotNull String fieldName)
Returns the value of the provided
fieldName extracted from the provided target. |
static boolean |
hasException(@NotNull Map<ExceptionKey,Integer> exceptions) |
static void |
init() |
static boolean |
is64bit()
Returns if the JVM runs in 64 bit mode.
|
static boolean |
isArm()
Returns if the JVM runs on a CPU using the ARM architecture.
|
static boolean |
isAssertEnabled()
Was assertion enabled for the Jvm class when it was initialised.
|
static boolean |
isAzulZing() |
static boolean |
isAzulZulu() |
static boolean |
isCodeCoverage()
Returns if the JVM is running in code coverage mode.
|
static boolean |
isDebug()
Returns if the JVM is running in debug mode.
|
static boolean |
isDebugEnabled(Class<?> aClass) |
static boolean |
isFlightRecorder()
Returns if the JVM is running in flight recorder mode.
|
static boolean |
isJava12Plus() |
static boolean |
isJava14Plus() |
static boolean |
isJava15Plus() |
static boolean |
isJava19Plus() |
static boolean |
isJava20Plus() |
static boolean |
isJava21Plus() |
static boolean |
isJava9Plus() |
static boolean |
isLambdaClass(Class<?> clazz)
Checks if the given class represents a lambda expression.
|
static boolean |
isMacArm()
Returns if the JVM runs on a CPU using a Mac ARM architecture.
|
static boolean |
isPerfEnabled(Class<?> aClass) |
static boolean |
isProcessAlive(long pid)
Returns if a process with the provided
pid process id is alive. |
static boolean |
isResourceTracing()
Returns if certain chronicle resources (such as memory regions) are traced.
|
static String |
lockWithStack(@NotNull ReentrantLock lock)
Log the stack trace of the thread holding a lock.
|
static int |
majorVersion() |
static long |
maxDirectMemory()
Returns the maximum direct memory in bytes that can ever be allocated or 0 if the
value cannot be determined.
|
static void |
nanoPause()
Pause in a busy loop for a very short time.
|
static void |
park()
park the current thread, and stay parked
|
static long |
parseSize(@NotNull String value)
Parse a string as a decimal memory size with an optional scale.
|
static void |
pause(long durationMs)
Silently pause for the provided
durationMs milliseconds. |
static @NotNull ExceptionHandler |
perf()
Returns an ExceptionHandler for performance messages, this prints as System.out or INFO level logging.
|
static @NotNull Map<ExceptionKey,Integer> |
recordExceptions() |
static @NotNull Map<ExceptionKey,Integer> |
recordExceptions(boolean debug) |
static @NotNull Map<ExceptionKey,Integer> |
recordExceptions(boolean debug,
boolean exceptionsOnly) |
static @NotNull Map<ExceptionKey,Integer> |
recordExceptions(boolean debug,
boolean exceptionsOnly,
boolean logToSlf4j) |
static void |
reportUnoptimised() |
static void |
resetExceptionHandlers() |
static <T extends Throwable> |
rethrow(Throwable throwable)
Cast any Throwable (e.g.
|
static void |
safepoint()
Inserts a low-cost Java safe-point in the code path if -Djvm.safepoint.enabled
|
static void |
setAccessible(@NotNull AccessibleObject accessibleObject)
Set the accessible flag for the provided
accessibleObject indicating that
the reflected object should suppress Java language access checking when it is used. |
static void |
setDebugExceptionHandler(ExceptionHandler exceptionHandler) |
static void |
setErrorExceptionHandler(ExceptionHandler exceptionHandler) |
static void |
setExceptionHandlers(@Nullable ExceptionHandler error,
@Nullable ExceptionHandler warn,
@Nullable ExceptionHandler debug) |
static void |
setExceptionHandlers(@Nullable ExceptionHandler error,
@Nullable ExceptionHandler warn,
@Nullable ExceptionHandler debug,
@Nullable ExceptionHandler perf) |
static void |
setPerfExceptionHandler(ExceptionHandler exceptionHandler) |
static void |
setResourceTracing(boolean resourceTracing)
Sets the state of resource tracing.
|
static void |
setThreadLocalExceptionHandlers(@Nullable ExceptionHandler error,
@Nullable ExceptionHandler warn,
@Nullable ExceptionHandler debug) |
static void |
setThreadLocalExceptionHandlers(@Nullable ExceptionHandler error,
@Nullable ExceptionHandler warn,
@Nullable ExceptionHandler debug,
@Nullable ExceptionHandler perf) |
static void |
setWarnExceptionHandler(ExceptionHandler exceptionHandler) |
static boolean |
stackTraceEndsWith(String endsWith,
int maxDepth)
Returns if there is a class name that ends with the provided
endsWith string
when examining the current stack trace of depth at most up to the provided maxDepth. |
static @NotNull ExceptionHandler |
startup()
Returns an ExceptionHandler for startup messages, this prints as System.out or INFO level logging.
|
static boolean |
supportThread() |
static int |
trimLast(int first,
@NotNull StackTraceElement[] stes) |
static void |
trimStackTrace(@NotNull StringBuilder stringBuilder,
StackTraceElement... stackTraceElements)
Append the provided
StackTraceElements to the provided stringBuilder trimming some internal methods. |
static <T> Class<T> |
uncheckedCast(Class<?> o)
Performs an unchecked cast of a
Class object to Class<T>. |
static <T> T |
uncheckedCast(Object o)
Performs an unchecked cast of an object to the target type
T. |
static <T> T[] |
uncheckedCast(Object[] o)
Performs an unchecked cast of an array of objects to an array of the target type
T[]. |
static long |
usedDirectMemory()
Returns the accumulated amount of memory in bytes used by direct ByteBuffers
or 0 if the value cannot be determined.
|
static long |
usedNativeMemory()
Returns the accumulated amount of memory used in bytes by UnsafeMemory.allocate().
|
static @NotNull String |
userHome()
Returns the user's home directory (e.g.
|
static @NotNull ExceptionHandler |
warn()
Returns an ExceptionHandler for warnings, this prints as System.out or WARN level logging.
|
public static final String JAVA_CLASS_PATH
public static final String SYSTEM_PROPERTIES
public static void reportUnoptimised()
public static void init()
public static int compileThreshold()
The compile threshold can be explicitly set using the command line parameter "-XX:CompileThreshold="
public static int majorVersion()
public static boolean isJava9Plus()
public static boolean isJava12Plus()
public static boolean isJava14Plus()
public static boolean isJava15Plus()
public static boolean isJava19Plus()
public static boolean isJava20Plus()
public static boolean isJava21Plus()
public static int getProcessId()
@NotNull public static <T extends Throwable> @NotNull RuntimeException rethrow(Throwable throwable) throws T extends Throwable
T - the type of the Throwablethrowable - to castT - the throwable as an unchecked throwableT extends Throwablepublic static void trimStackTrace(@NotNull
@NotNull StringBuilder stringBuilder,
@NotNull
StackTraceElement... stackTraceElements)
StackTraceElements to the provided stringBuilder trimming some internal methods.stringBuilder - to append tostackTraceElements - stack trace elementspublic static int trimLast(int first,
@NotNull
@NotNull StackTraceElement[] stes)
public static boolean isDebug()
public static boolean isFlightRecorder()
public static boolean isCodeCoverage()
public static void pause(long durationMs)
durationMs milliseconds.
If the provided durationMs is positive, then the
current thread sleeps.
If the provided durationMs is zero, then the
current thread yields.
durationMs - to sleep for.public static void nanoPause()
public static void busyWaitMicros(long durationUs)
durationUs microseconds.
This method is designed to be used when the time to be waited is very small, typically under a millisecond (@{code durationUs < 1_000}).
durationUs - Time in durationUspublic static void busyWaitUntil(long waitUntilNs)
waitUntilNs time is reached.
This method is designed to be used when the time to be waited is very small, typically under a millisecond (@{code durationNs < 1_000_000}).
waitUntilNs - nanosecond precision counter value to await.@NotNull public static @NotNull Field getField(@NotNull @NotNull Class<?> clazz, @NotNull @NotNull String fieldName)
clazz and the provided fieldName or
throws an Exception if no such Field exists.clazz - to get the field forfieldName - of the fieldAssertionError - if no such Field exists@Nullable public static @Nullable Field getFieldOrNull(@NotNull @NotNull Class<?> clazz, @NotNull @NotNull String fieldName)
clazz and the provided fieldName or null
if no such Field exists.clazz - to get the field forfieldName - of the fieldAssertionError - if no such Field exists@NotNull public static @NotNull Method getMethod(@NotNull @NotNull Class<?> clazz, @NotNull @NotNull String methodName, Class<?>... argTypes)
clazz, methodName and
argTypes or throws an Exception.
if it exists or throws AssertionError.
Default methods are not detected unless the class explicitly overrides it
clazz - classmethodName - methodNameargTypes - argument typesAssertionError - if no such Method existspublic static void setAccessible(@NotNull
@NotNull AccessibleObject accessibleObject)
accessibleObject indicating that
the reflected object should suppress Java language access checking when it is used.
The setting of the accessible flag might be subject to security manager approval.
accessibleObject - to modifySecurityException - – if the request is denied.SecurityManager.checkPermission(java.security.Permission),
RuntimePermission@Nullable
public static <V> V getValue(@NotNull
@NotNull Object target,
@NotNull
@NotNull String fieldName)
fieldName extracted from the provided target.
The provided fieldName can denote fields of arbitrary depth (e.g. foo.bar.baz, whereby
the foo value will be extracted from the provided target and then the bar value
will be extracted from the foo value and so on).
V - return typetarget - used for extractionfieldName - denoting the field(s) to extractfieldName extracted from the provided targetpublic static String lockWithStack(@NotNull @NotNull ReentrantLock lock)
lock - to logpublic static long fieldOffset(Class<?> clazz, String fieldName)
clazz - the class for which you want to get field from [ it won't see inherited fields ]fieldName - the name of the fieldpublic static long usedDirectMemory()
(i.e. ever allocated via ByteBuffer.allocateDirect())
public static long usedNativeMemory()
public static long maxDirectMemory()
public static boolean is64bit()
public static void resetExceptionHandlers()
public static void setErrorExceptionHandler(ExceptionHandler exceptionHandler)
public static void setWarnExceptionHandler(ExceptionHandler exceptionHandler)
public static void setDebugExceptionHandler(ExceptionHandler exceptionHandler)
public static void setPerfExceptionHandler(ExceptionHandler exceptionHandler)
public static void disableDebugHandler()
public static void disablePerfHandler()
public static void disableWarnHandler()
@NotNull public static @NotNull Map<ExceptionKey,Integer> recordExceptions()
@NotNull public static @NotNull Map<ExceptionKey,Integer> recordExceptions(boolean debug)
@NotNull public static @NotNull Map<ExceptionKey,Integer> recordExceptions(boolean debug, boolean exceptionsOnly)
@NotNull public static @NotNull Map<ExceptionKey,Integer> recordExceptions(boolean debug, boolean exceptionsOnly, boolean logToSlf4j)
public static boolean hasException(@NotNull
@NotNull Map<ExceptionKey,Integer> exceptions)
public static void setExceptionHandlers(@Nullable
@Nullable ExceptionHandler error,
@Nullable
@Nullable ExceptionHandler warn,
@Nullable
@Nullable ExceptionHandler debug)
public static void setExceptionHandlers(@Nullable
@Nullable ExceptionHandler error,
@Nullable
@Nullable ExceptionHandler warn,
@Nullable
@Nullable ExceptionHandler debug,
@Nullable
@Nullable ExceptionHandler perf)
public static void setThreadLocalExceptionHandlers(@Nullable
@Nullable ExceptionHandler error,
@Nullable
@Nullable ExceptionHandler warn,
@Nullable
@Nullable ExceptionHandler debug)
public static void setThreadLocalExceptionHandlers(@Nullable
@Nullable ExceptionHandler error,
@Nullable
@Nullable ExceptionHandler warn,
@Nullable
@Nullable ExceptionHandler debug,
@Nullable
@Nullable ExceptionHandler perf)
@NotNull public static @NotNull ExceptionHandler error()
@NotNull public static @NotNull ExceptionHandler warn()
@NotNull public static @NotNull ExceptionHandler startup()
@NotNull public static @NotNull ExceptionHandler perf()
@NotNull public static @NotNull ExceptionHandler debug()
public static void dumpException(@NotNull
@NotNull Map<ExceptionKey,Integer> exceptions)
public static boolean isDebugEnabled(Class<?> aClass)
public static boolean isPerfEnabled(Class<?> aClass)
public static void addSignalHandler(Jvm.SignalHandler signalHandler)
signalHandler to an internal chain of handlers that will be invoked
upon detecting system signals (e.g. HUP, INT, TERM).
Not all signals are available on all operating systems.
signalHandler - to call on a signalpublic static void safepoint()
public static boolean areOptionalSafepointsEnabled()
public static boolean stackTraceEndsWith(String endsWith, int maxDepth)
endsWith string
when examining the current stack trace of depth at most up to the provided maxDepth.endsWith - to test against the current stack tracemaxDepth - to examineendsWith string
when examining the current stack trace of depth at most up to the provided maxDepthpublic static boolean isArm()
public static boolean isMacArm()
@NotNull public static @NotNull ClassMetrics classMetrics(Class<?> clazz) throws IllegalArgumentException
clazz.clazz - for which ClassMetrics shall be acquiredclazzIllegalArgumentException - if no ClassMetrics can be acquiredClassMetrics@NotNull public static @NotNull String userHome()
public static boolean dontChain(Class<?> tClass)
public static boolean isResourceTracing()
Tracing resources incurs slightly less performance but provides a means of detecting proper release of resources.
public static void setResourceTracing(boolean resourceTracing)
Note: Enabling resource tracing can exert significant pressure on the garbage collector during stress tests.
resourceTracing - true to enable resource tracing, false to disable.public static String getProperty(String systemPropertyKey)
System.getProperty(String)public static String getProperty(String systemPropertyKey, String defaultValue)
System.getProperty(String, String)public static Long getLong(String systemPropertyKey, Long defVal)
Long.getLong(String, Long)public static Integer getInteger(String systemPropertyKey, Integer defVal)
Integer.getInteger(String, Integer)public static boolean getBoolean(String systemPropertyKey)
systemPropertyKey
either exists, is set to "yes" or is set to "true".
This provides a more permissive boolean System systemPropertyKey flag where
-Dflag -Dflag=true -Dflag=yes are all accepted.
Guarantees that Jvm class is initialized before property is read.
systemPropertyKey - name to lookupsystemPropertyKey
either exists, is set to "yes" or is set to "true"public static boolean getBoolean(String systemPropertyKey, boolean defaultValue)
systemPropertyKey
either exists, is set to "yes" or is set to "true" or, if it does not exist,
returns the provided defaultValue.
This provides a more permissive boolean System systemPropertyKey flag where
-Dflag -Dflag=true -Dflag=yes are all accepted.
Guarantees that Jvm class is initialized before property is read.
systemPropertyKey - name to lookupdefaultValue - value to be used if unknownsystemPropertyKey
either exists, is set to "yes" or is set to "true" or, if it does not exist,
returns the provided defaultValue.public static long parseSize(@NotNull
@NotNull String value)
throws IllegalArgumentException
trailing B/b/iB/ib are ignored.
| 100 | 100 bytes |
| 100b | 100 bytes |
| 0.5kb | 512 bytes |
| 0.125MB | 128 KiB |
| 2M | 2 MiB |
| 0.75GiB | 768 MiB |
| 0.001TiB | 1.024 GiB |
value - size to parseIllegalArgumentException - if the string could not be parsedpublic static long getSize(String property, long defaultValue)
property - to look updefaultValue - to use otherwisepublic static long address(@NotNull
@NotNull ByteBuffer byteBuffer)
byteBuffer.
Use with caution!. Native address should always be carefully guarded to prevent unspecified results or even JVM crashes.
byteBuffer - from which to extract the native addressbyteBufferpublic static int arrayByteBaseOffset()
The value is the number of bytes that precedes the actual
memory layout of a byte[] array in a java array object.
Use with caution!. Native address should always be carefully guarded to prevent unspecified results or even JVM crashes.
public static void doNotCloseOnInterrupt(Class<?> clazz, FileChannel fc)
fc from being automatically closed
whenever the current thread gets interrupted.
If the effort failed, the provided clazz is used for logging purposes.
clazz - to use for logging should the effort fail.fc - to prevent from automatically closing upon interrupt.public static void addToClassPath(@NotNull
@NotNull Class<?> clazz)
clazz.clazz - to use as a template.public static double getDouble(String systemPropertyKey, double defaultValue)
systemPropertyKey
parsed as a double or, if no such parsable System Property exists,
returns the provided defaultValue.
Guarantees that Jvm class is initialized before property is read.
systemPropertyKey - to lookup in the System PropertiesdefaultValue - to be used if no parsable key association existssystemPropertyKey
parsed as a double or, if no such parsable System Property exists,
returns the provided defaultValuepublic static boolean isProcessAlive(long pid)
pid process id is alive.pid - the process id (pid) of the process to checkpid process id is alivepublic static boolean isAzulZing()
public static boolean isAzulZulu()
public static String getCpuClass()
public static boolean isAssertEnabled()
public static boolean supportThread()
public static void park()
public static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType)
annotationType that is present on the given
annotatedElement, including considering nested annotations and method inheritance.
If the annotation isn't found, this method returns null.A - denotes the annotation type.annotatedElement - the element (e.g., class, method, field) to inspect for annotations.annotationType - the desired annotation's type.A or null if not present.public static boolean isLambdaClass(Class<?> clazz)
Java creates synthetic classes for lambda expressions. Typically, the name of these classes contains the "$$Lambda" substring. Note that this naming convention is JVM-specific and can change in future versions. The approach is known to work up to Java 21.
clazz - the class to be checked.true if the class is a lambda, false otherwise.public static <T> T uncheckedCast(Object o)
T. This method
bypasses generic type checks, allowing for casting without explicit type checking,
offering a convenient way to avoid compiler warnings for unchecked casts.
Note: Use with caution as improper use can lead to ClassCastException at runtime
if the object is not of type T. Intended for situations where the type safety is
guaranteed through other means but cannot be expressed without generic type warnings.
T - the target type to cast too - the object to be castTClassCastException - if the object cannot be casted to the target type T
(a runtime risk due to type erasure)public static <T> T[] uncheckedCast(Object[] o)
T[].
This method bypasses generic array type checks, facilitating casting without explicit array
type checking.
Note: Use with caution as improper use can lead to ClassCastException at runtime
if the objects in the array cannot be cast to type T[]. This method is useful when
the programmer is confident in the implicit type safety of the operation but wishes to avoid
compiler warnings about unchecked operations.
T - the target component type of the array to cast too - the object array to be castT[]ClassCastException - if the objects in the array cannot be cast to the component type T[]public static <T> Class<T> uncheckedCast(Class<?> o)
Class object to Class<T>. This operation
is particularly useful in scenarios involving reflection where generic type parameters are
known but cannot be statically enforced by the compiler.
By bypassing compile-time generic type checks, it provides a way to work with generic types in a dynamic context at the cost of compile-time type safety.
Note: Use with caution as improper use can lead to a ClassCastException at runtime
if the class object cannot actually be cast to Class<T>. This method should be
employed when there is certainty about the underlying type compatibility.
T - the target generic type to cast the class too - the class object to be castClass<T>ClassCastException - if the class object cannot be cast to Class<T>
(a runtime risk inherent to unchecked casting)public static long currentThreadId()
This method provides a straightforward way to obtain the ID of the thread
from which the method is called. Currently, it uses Thread.currentThread()
and Thread.getId() to accomplish this. The method is safe to use across
various versions of Java.
Note: In future versions, this implementation may be updated to use Thread.threadId()
or another updated mechanism for obtaining the thread ID, as newer Java versions from version 19
deprecate the current approach.
public static String getPackageName(Class clazz)
This method uses Class.getPackageName() if running on Java 9 or newer.
For older versions, it uses a cached value determined by the class name.
clazz - the class whose package name is to be determinedCopyright © 2024. All rights reserved.