@@ -67,25 +67,30 @@ public class GCInspector implements NotificationListener, GCInspectorMXBean
6767
6868 static
6969 {
70- Field totalTempField = null ;
71- Field maxTempField = null ;
72- Field reservedTempField = null ;
70+ Class <?> bitsClass = null ;
71+
7372 try
7473 {
75- Class <?> bitsClass = Class .forName ("java.nio.Bits" );
76- totalTempField = getField (bitsClass , "TOTAL_CAPACITY" );
77- // Returns the maximum amount of allocatable direct buffer memory.
78- maxTempField = getField (bitsClass , "MAX_MEMORY" );
79- reservedTempField = getField (bitsClass , "RESERVED_MEMORY" );
74+ bitsClass = Class .forName ("java.nio.Bits" );
8075 }
8176 catch (Throwable t )
8277 {
8378 logger .debug ("Error accessing field of java.nio.Bits" , t );
84- //Don't care, will just return the dummy value -1 if we can't get at the field in this JVM
8579 }
86- BITS_TOTAL_CAPACITY = totalTempField ;
87- BITS_MAX = maxTempField ;
88- BITS_RESERVED = reservedTempField ;
80+
81+ if (bitsClass != null )
82+ {
83+ BITS_TOTAL_CAPACITY = getField (bitsClass , "TOTAL_CAPACITY" );
84+ // Returns the maximum amount of allocatable direct buffer memory.
85+ BITS_MAX = getField (bitsClass , "MAX_MEMORY" );
86+ BITS_RESERVED = getField (bitsClass , "RESERVED_MEMORY" );
87+ }
88+ else
89+ {
90+ BITS_TOTAL_CAPACITY = null ;
91+ BITS_MAX = null ;
92+ BITS_RESERVED = null ;
93+ }
8994 }
9095
9196 static final class State
@@ -397,9 +402,15 @@ private static Field getField(Class<?> clazz, String fieldName)
397402 }
398403
399404 /**
405+ * Retrieves the value of a Field, handling both regular long fields and AtomicLong fields.
406+ *
400407 * From the implementation of java.nio.Bits, we can infer that TOTAL_CAPACITY/RESERVED_MEMORY is AtomicLong
401- * and MAX_MEMORY is long. This method works well with JDK 11/17
402- * */
408+ * and MAX_MEMORY is long.
409+ *
410+ * @param field the Field to retrieve the value from
411+ * @param isAtomicLong true if the field is an AtomicLong, false if it's a regular long
412+ * @return the field value, or -1 if retrieval fails or field is null.
413+ */
403414 private static long getFieldValue (Field field , boolean isAtomicLong )
404415 {
405416 if (field == null ) return -1 ;
0 commit comments