-
Notifications
You must be signed in to change notification settings - Fork 128
/
Jvm.java
1705 lines (1530 loc) · 63.9 KB
/
Jvm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.core;
import net.openhft.chronicle.core.annotation.DontChain;
import net.openhft.chronicle.core.internal.util.DirectBufferUtil;
import net.openhft.chronicle.core.onoes.*;
import net.openhft.chronicle.core.util.ObjectUtils;
import net.openhft.chronicle.core.util.ThrowingSupplier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import sun.misc.Unsafe;
import sun.nio.ch.Interruptible;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.lang.Runtime.getRuntime;
import static java.lang.management.ManagementFactory.getRuntimeMXBean;
import static java.util.stream.Collectors.toList;
import static net.openhft.chronicle.core.Bootstrap.*;
import static net.openhft.chronicle.core.OS.*;
import static net.openhft.chronicle.core.UnsafeMemory.UNSAFE;
import static net.openhft.chronicle.core.internal.util.MapUtil.entry;
import static net.openhft.chronicle.core.internal.util.MapUtil.ofUnmodifiable;
/**
* Utility class to access information in the JVM.
*/
public final class Jvm {
// These are the exception handlers used initially, and restored when resetExceptionHandlers() is called
private static final ExceptionHandler DEFAULT_ERROR_EXCEPTION_HANDLER = Slf4jExceptionHandler.ERROR;
private static final ExceptionHandler DEFAULT_WARN_EXCEPTION_HANDLER = Slf4jExceptionHandler.WARN;
private static final ExceptionHandler DEFAULT_PERF_EXCEPTION_HANDLER = Slf4jExceptionHandler.PERF;
private static final ExceptionHandler DEFAULT_DEBUG_EXCEPTION_HANDLER = Slf4jExceptionHandler.DEBUG;
// Suppresses default constructor, ensuring non-instantiability.
private Jvm() {
}
private static final String PROC = "/proc";
private static final String PROC_SELF = "/proc/self";
public static final String JAVA_CLASS_PATH = "java.class.path";
public static final String SYSTEM_PROPERTIES = "system.properties";
private static final List<String> INPUT_ARGUMENTS = getRuntimeMXBean().getInputArguments();
private static final String INPUT_ARGUMENTS2 = " " + String.join(" ", INPUT_ARGUMENTS);
private static final boolean IS_DEBUG = Jvm.getBoolean("debug", INPUT_ARGUMENTS2.contains("jdwp"));
// e.g-verbose:gc -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=dumponexit=true,filename=myrecording.jfr,settings=profile -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
private static final boolean IS_FLIGHT_RECORDER = Jvm.getBoolean("jfr", INPUT_ARGUMENTS2.contains(" -XX:+FlightRecorder"));
private static final boolean IS_COVERAGE = INPUT_ARGUMENTS2.contains("coverage");
private static final int COMPILE_THRESHOLD = getCompileThreshold0();
private static final boolean REPORT_UNOPTIMISED;
private static final Supplier<Long> reservedMemory;
private static final boolean IS_64BIT = is64bit0();
private static final int PROCESS_ID = getProcessId0();
private static final boolean IS_AZUL_ZING = Bootstrap.isAzulZing0();
private static final boolean IS_AZUL_ZULU = Bootstrap.isAzulZulu0();
@NotNull
private static final ThreadLocalisedExceptionHandler ERROR = new ThreadLocalisedExceptionHandler(DEFAULT_ERROR_EXCEPTION_HANDLER);
@NotNull
private static final ThreadLocalisedExceptionHandler WARN = new ThreadLocalisedExceptionHandler(DEFAULT_WARN_EXCEPTION_HANDLER);
@NotNull
private static final ThreadLocalisedExceptionHandler PERF = new ThreadLocalisedExceptionHandler(DEFAULT_PERF_EXCEPTION_HANDLER);
@NotNull
private static final ThreadLocalisedExceptionHandler DEBUG = new ThreadLocalisedExceptionHandler(DEFAULT_DEBUG_EXCEPTION_HANDLER);
private static final long MAX_DIRECT_MEMORY;
private static final boolean SAFEPOINT_ENABLED;
private static final boolean IS_ARM = Bootstrap.isArm0();
private static final boolean IS_MAC_ARM = Bootstrap.isMacArm0();
private static final Map<Class<?>, ClassMetrics> CLASS_METRICS_MAP = new ConcurrentHashMap<>();
private static final Map<Class<?>, Integer> PRIMITIVE_SIZE = ofUnmodifiable(
entry(boolean.class, 1),
entry(byte.class, Byte.BYTES),
entry(char.class, Character.BYTES),
entry(short.class, Short.BYTES),
entry(int.class, Integer.BYTES),
entry(float.class, Float.BYTES),
entry(long.class, Long.BYTES),
entry(double.class, Double.BYTES)
);
private static final MethodHandle setAccessible0_Method;
private static final MethodHandle onSpinWaitMH;
private static final ChainedSignalHandler signalHandlerGlobal;
private static final boolean RESOURCE_TRACING;
private static final boolean PROC_EXISTS = new File(PROC).exists();
private static final int OBJECT_HEADER_SIZE;
private static final boolean ASSERT_ENABLED;
static {
boolean debug = false;
assert debug = true;
ASSERT_ENABLED = debug;
final Field[] declaredFields = ObjectHeaderSizeChecker.class.getDeclaredFields();
// get this here before we call getField
setAccessible0_Method = getSetAccessible0Method();
MAX_DIRECT_MEMORY = maxDirectMemory0();
OBJECT_HEADER_SIZE = (int) UnsafeMemory.INSTANCE.getFieldOffset(declaredFields[0]);
Supplier<Long> reservedMemoryGetter;
try {
final Class<?> bitsClass = Class.forName("java.nio.Bits");
final Field firstTry = getFieldOrNull(bitsClass, "reservedMemory");
final Field f = firstTry != null ? firstTry : getField(bitsClass, "RESERVED_MEMORY");
if (f.getType() == AtomicLong.class) {
AtomicLong reservedMemory = (AtomicLong) f.get(null);
reservedMemoryGetter = reservedMemory::get;
} else {
reservedMemoryGetter = ThrowingSupplier.asSupplier(() -> f.getLong(null));
}
} catch (Exception e) {
System.err.println(Jvm.class.getName() + ": Unable to determine the reservedMemory value, will always report 0");
reservedMemoryGetter = () -> 0L;
}
reservedMemory = reservedMemoryGetter;
signalHandlerGlobal = new ChainedSignalHandler();
MethodHandle onSpinWait = null;
if (IS_JAVA_9_PLUS) {
try {
onSpinWait = MethodHandles.lookup()
.findStatic(Thread.class, "onSpinWait", MethodType.methodType(Void.TYPE));
} catch (Exception ignored) {
// Ignore
}
}
onSpinWaitMH = onSpinWait;
findAndLoadSystemProperties();
boolean disablePerfInfo = Jvm.getBoolean("disable.perf.info");
if (disablePerfInfo)
PERF.defaultHandler(NullExceptionHandler.NOTHING);
SAFEPOINT_ENABLED = Jvm.getBoolean("jvm.safepoint.enabled");
RESOURCE_TRACING = Jvm.getBoolean("jvm.resource.tracing");
Logger logger = LoggerFactory.getLogger(Jvm.class);
if (logger.isInfoEnabled())
logger.info("Chronicle core loaded from " + Jvm.class.getProtectionDomain().getCodeSource().getLocation());
if (RESOURCE_TRACING && !Jvm.getBoolean("disable.resource.warning"))
logger.warn("Resource tracing is turned on. If you are performance testing or running in PROD you probably don't want this");
REPORT_UNOPTIMISED = Jvm.getBoolean("report.unoptimised");
}
public static void reportUnoptimised() {
if (!REPORT_UNOPTIMISED)
return;
final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
int i = 0;
while (i < stes.length)
if (stes[i++].getMethodName().equals("reportUnoptimised"))
break;
while (i < stes.length)
if (stes[i++].getMethodName().equals("<clinit>"))
break;
Jvm.warn().on(Jvm.class, "Reporting usage of unoptimised method " + stes[i]);
}
private static void findAndLoadSystemProperties() {
String systemProperties = Jvm.getProperty(SYSTEM_PROPERTIES);
boolean wasSet = true;
if (systemProperties == null) {
if (new File(SYSTEM_PROPERTIES).exists())
systemProperties = SYSTEM_PROPERTIES;
else if (new File("../" + SYSTEM_PROPERTIES).exists())
systemProperties = "../" + SYSTEM_PROPERTIES;
else {
systemProperties = SYSTEM_PROPERTIES;
wasSet = false;
}
}
loadSystemProperties(systemProperties, wasSet);
}
private static MethodHandle getSetAccessible0Method() {
if (!IS_JAVA_9_PLUS) {
return null;
}
final MethodType signature = MethodType.methodType(boolean.class, boolean.class);
try {
// Access privateLookupIn() reflectively to support compilation with JDK 8
Method privateLookupIn = MethodHandles.class.getDeclaredMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class);
MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupIn.invoke(null, AccessibleObject.class, MethodHandles.lookup());
return lookup.findVirtual(AccessibleObject.class, "setAccessible0", signature);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
throw new ExceptionInInitializerError(e);
}
}
public static void init() {
// force static initialisation
ChronicleInit.init();
}
private static void loadSystemProperties(final String name, final boolean wasSet) {
try {
final ClassLoader classLoader = Jvm.class.getClassLoader();
InputStream is0 = classLoader == null ? null : classLoader.getResourceAsStream(name);
if (is0 == null) {
File file = new File(name);
if (file.exists())
is0 = new FileInputStream(file);
}
try (InputStream is = is0) {
if (is == null) {
(wasSet ? Slf4jExceptionHandler.WARN : Slf4jExceptionHandler.DEBUG)
.on(Jvm.class, "No " + name + " file found");
} else {
final Properties prop = new Properties();
prop.load(is);
// if user has specified a property using -D then don't overwrite it from system.properties
prop.forEach((o, o2) -> System.getProperties().putIfAbsent(o, o2));
Slf4jExceptionHandler.DEBUG.on(Jvm.class, "Loaded " + name + " with " + prop);
}
}
} catch (Exception e) {
Slf4jExceptionHandler.WARN.on(Jvm.class, "Error loading " + name, e);
}
}
private static int getCompileThreshold0() {
for (String inputArgument : INPUT_ARGUMENTS) {
final String prefix = "-XX:CompileThreshold=";
if (inputArgument.startsWith(prefix)) {
try {
return Integer.parseInt(inputArgument.substring(prefix.length()));
} catch (NumberFormatException nfe) {
// ignore
}
}
}
return 10_000;
}
/**
* Returns the compile threshold for the JVM or else an
* estimate thereof (e.g. 10_000).
* <p>
* The compile threshold can be explicitly set using the command
* line parameter "-XX:CompileThreshold="
*
* @return the compile threshold for the JVM or else an
* estimate thereof (e.g. 10_000)
*/
public static int compileThreshold() {
return COMPILE_THRESHOLD;
}
/**
* Returns the major Java version (e.g. 8, 11 or 17)
*
* @return the major Java version (e.g. 8, 11 or 17)
*/
public static int majorVersion() {
return JVM_JAVA_MAJOR_VERSION;
}
/**
* Returns if the major Java version is 9 or higher.
*
* @return if the major Java version is 9 or higher
*/
public static boolean isJava9Plus() {
return IS_JAVA_9_PLUS;
}
/**
* Returns if the major Java version is 12 or higher.
*
* @return if the major Java version is 12 or higher
*/
public static boolean isJava12Plus() {
return IS_JAVA_12_PLUS;
}
/**
* Returns if the major Java version is 14 or higher.
*
* @return if the major Java version is 14 or higher
*/
public static boolean isJava14Plus() {
return IS_JAVA_14_PLUS;
}
/**
* Returns if the major Java version is 14 or higher.
*
* @return if the major Java version is 14 or higher
*/
public static boolean isJava15Plus() {
return IS_JAVA_15_PLUS;
}
private static boolean is64bit0() {
String systemProp;
systemProp = Jvm.getProperty("com.ibm.vm.bitmode");
if (systemProp != null) {
return "64".equals(systemProp);
}
systemProp = Jvm.getProperty("sun.arch.data.model");
if (systemProp != null) {
return "64".equals(systemProp);
}
systemProp = System.getProperty("java.vm.version");
return systemProp != null && systemProp.contains("_64");
}
/**
* Returns the current process id.
*
* @return the current process id or, if the process id cannot be determined, 1 is used.
*/
// Todo: Discuss the rational behind the random number. Alternately, 0 could be returned or perhaps -1
public static int getProcessId() {
return PROCESS_ID;
}
private static int getProcessId0() {
String pid = null;
final File self = new File(PROC_SELF);
try {
if (self.exists()) {
pid = self.getCanonicalFile().getName();
}
} catch (IOException ignored) {
// Ignore
}
if (pid == null) {
pid = getRuntimeMXBean().getName().split("@", 0)[0];
}
if (pid != null) {
try {
return Integer.parseInt(pid);
} catch (NumberFormatException nfe) {
// ignore
}
}
int rpid = 1;
System.err.println(Jvm.class.getName() + ": Unable to determine PID, picked 1 as a PID");
return rpid;
}
/**
* Cast any Throwable (e.g. a checked exception) to a RuntimeException.
*
* @param throwable to cast
* @param <T> the type of the Throwable
* @return this method will never return a Throwable instance, it will just throw it.
* @throws T the throwable as an unchecked throwable
*/
@NotNull
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
/**
* Append the provided {@code StackTraceElements} to the provided {@code stringBuilder} trimming some internal methods.
*
* @param stringBuilder to append to
* @param stackTraceElements stack trace elements
*/
public static void trimStackTrace(@NotNull final StringBuilder stringBuilder, @NotNull final StackTraceElement... stackTraceElements) {
final int first = trimFirst(stackTraceElements);
final int last = trimLast(first, stackTraceElements);
for (int i = first; i <= last; i++)
stringBuilder.append("\n\tat ").append(stackTraceElements[i]);
}
static int trimFirst(@NotNull final StackTraceElement[] stes) {
if (stes.length > 2 && stes[1].getMethodName().endsWith("afepoint"))
return 2;
int first = 0;
for (; first < stes.length; first++)
if (!isInternal(stes[first].getClassName()))
break;
return Math.max(0, first - 2);
}
public static int trimLast(final int first, @NotNull final StackTraceElement[] stes) {
int last = stes.length - 1;
for (; first < last; last--)
if (!isInternal(stes[last].getClassName()))
break;
if (last < stes.length - 1) last++;
return last;
}
static boolean isInternal(@NotNull final String className) {
return className.startsWith("jdk.") || className.startsWith("sun.") || className.startsWith("java.");
}
/**
* Returns if the JVM is running in debug mode.
*
* @return if the JVM is running in debug mode
*/
@SuppressWarnings("SameReturnValue")
public static boolean isDebug() {
return IS_DEBUG;
}
/**
* Returns if the JVM is running in flight recorder mode.
*
* @return if the JVM is running in flight recorder mode
*/
@SuppressWarnings("SameReturnValue")
public static boolean isFlightRecorder() {
return IS_FLIGHT_RECORDER;
}
/**
* Returns if the JVM is running in code coverage mode.
*
* @return if the JVM is running in code coverage mode
*/
public static boolean isCodeCoverage() {
return IS_COVERAGE;
}
/**
* Silently pause for the provided {@code durationMs} milliseconds.
* <p>
* If the provided {@code durationMs} is positive, then the
* current thread sleeps.
* <p>
* If the provided {@code durationMs} is zero, then the
* current thread yields.
*
* @param durationMs to sleep for.
*/
public static void pause(final long durationMs) {
if (durationMs <= 0) {
Thread.yield();
return;
}
try {
Thread.sleep(durationMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* Pause in a busy loop for a very short time.
*/
public static void nanoPause() {
if (onSpinWaitMH == null) {
if (IS_JAVA_9_PLUS)
Safepoint.force(); // 1 ns on Java 11
else
Compiler.enable(); // 5 ns on Java 8
} else {
try {
onSpinWaitMH.invokeExact();
} catch (Throwable throwable) {
throw new AssertionError(throwable);
}
}
}
/**
* Pause in a busy loop for the provided {@code durationUs} microseconds.
* <p>
* This method is designed to be used when the time to be waited is very small,
* typically under a millisecond (@{code durationUs < 1_000}).
*
* @param durationUs Time in durationUs
*/
public static void busyWaitMicros(final long durationUs) {
busyWaitUntil(System.nanoTime() + (durationUs * 1_000));
}
/**
* Pauses the current thread in a busy loop until the provided {@code waitUntilNs} time is reached.
* <p>
* 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}).
*
* @param waitUntilNs nanosecond precision counter value to await.
*/
public static void busyWaitUntil(final long waitUntilNs) {
while (waitUntilNs > System.nanoTime()) {
Jvm.nanoPause();
}
}
/**
* Returns the Field for the provided {@code clazz} and the provided {@code fieldName} or
* throws an Exception if no such Field exists.
*
* @param clazz to get the field for
* @param fieldName of the field
* @return the Field.
* @throws AssertionError if no such Field exists
*/
// Todo: Should not throw an AssertionError but rather a RuntimeException
@NotNull
public static Field getField(@NotNull final Class<?> clazz, @NotNull final String fieldName) {
return getField0(clazz, fieldName, true);
}
static Field getField0(@NotNull final Class<?> clazz,
@NotNull final String name,
final boolean error) {
try {
final Field field = clazz.getDeclaredField(name);
setAccessible(field);
return field;
} catch (NoSuchFieldException e) {
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
final Field field = getField0(superclass, name, false);
if (field != null)
return field;
}
if (error)
throw new AssertionError(e);
return null;
}
}
/**
* Returns the Field for the provided {@code clazz} and the provided {@code fieldName} or {@code null}
* if no such Field exists.
*
* @param clazz to get the field for
* @param fieldName of the field
* @return the Field.
* @throws AssertionError if no such Field exists
*/
@Nullable
public static Field getFieldOrNull(@NotNull final Class<?> clazz, @NotNull final String fieldName) {
return getField0(clazz, fieldName, false);
}
/**
* Returns the Method for the provided {@code clazz}, {@code methodName} and
* {@code argTypes} or throws an Exception.
* <p>
* if it exists or throws {@link AssertionError}.
* <p>
* Default methods are not detected unless the class explicitly overrides it
*
* @param clazz class
* @param methodName methodName
* @param argTypes argument types
* @return method
* @throws AssertionError if no such Method exists
*/
// Todo: Should not throw an AssertionError but rather a RuntimeException
@NotNull
public static Method getMethod(@NotNull final Class<?> clazz,
@NotNull final String methodName,
final Class... argTypes) {
return getMethod0(clazz, methodName, argTypes, true);
}
private static Method getMethod0(@NotNull final Class<?> clazz,
@NotNull final String name,
final Class[] args,
final boolean first) {
try {
final Method method = clazz.getDeclaredMethod(name, args);
if (!Modifier.isPublic(method.getModifiers()) ||
!Modifier.isPublic(method.getDeclaringClass().getModifiers()))
setAccessible(method);
return method;
} catch (NoSuchMethodException e) {
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null)
try {
final Method m = getMethod0(superclass, name, args, false);
if (m != null)
return m;
} catch (Exception ignored) {
// Ignore
}
if (first)
throw new AssertionError(e);
return null;
}
}
/**
* Set the accessible flag for the provided {@code accessibleObject} indicating that
* the reflected object should suppress Java language access checking when it is used.
* <p>
* The setting of the accessible flag might be subject to security manager approval.
*
* @param accessibleObject to modify
* @throws SecurityException – if the request is denied.
* @see SecurityManager#checkPermission
* @see RuntimePermission
*/
public static void setAccessible(@NotNull final AccessibleObject accessibleObject) {
if (IS_JAVA_9_PLUS)
try {
boolean newFlag = (boolean) setAccessible0_Method.invokeExact(accessibleObject, true);
assert newFlag;
} catch (Throwable throwable) {
throw Jvm.rethrow(throwable);
}
else
accessibleObject.setAccessible(true);
}
/**
* Returns the value of the provided {@code fieldName} extracted from the provided {@code target}.
* <p>
* The provided {@code fieldName} can denote fields of arbitrary depth (e.g. foo.bar.baz, whereby
* the foo value will be extracted from the provided {@code target} and then the bar value
* will be extracted from the foo value and so on).
*
* @param target used for extraction
* @param fieldName denoting the field(s) to extract
* @param <V> return type
* @return the value of the provided {@code fieldName} extracted from the provided {@code target}
*/
@Nullable
public static <V> V getValue(@NotNull Object target, @NotNull final String fieldName) {
Class<?> aClass = target.getClass();
for (String n : fieldName.split("/")) {
Field f = getField(aClass, n);
try {
target = f.get(target);
if (target == null)
return null;
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new AssertionError(e);
}
aClass = target.getClass();
}
return (V) target;
}
/**
* Log the stack trace of the thread holding a lock.
*
* @param lock to log
* @return the lock.toString plus a stack trace.
*/
public static String lockWithStack(@NotNull final ReentrantLock lock) {
final Thread t = getValue(lock, "sync/exclusiveOwnerThread");
if (t == null) {
return lock.toString();
}
final StringBuilder ret = new StringBuilder();
ret.append(lock).append(" running at");
trimStackTrace(ret, t.getStackTrace());
return ret.toString();
}
/**
* @param clazz the class for which you want to get field from [ it wont see inherited fields ]
* @param fieldName the name of the field
* @return the offset
*/
public static long fieldOffset(final Class<?> clazz, final String fieldName) {
try {
return UNSAFE.objectFieldOffset(clazz.getDeclaredField(fieldName));
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
}
/**
* Returns the accumulated amount of memory in bytes used by direct ByteBuffers
* or 0 if the value cannot be determined.
* <p>
* (i.e. ever allocated via ByteBuffer.allocateDirect())
*
* @return the accumulated amount of memory in bytes used by direct ByteBuffers
* or 0 if the value cannot be determined
*/
public static long usedDirectMemory() {
return reservedMemory.get();
}
/**
* Returns the accumulated amount of memory used in bytes by UnsafeMemory.allocate().
*
* @return the accumulated amount of memory used in bytes by UnsafeMemory.allocate()
*/
public static long usedNativeMemory() {
return UnsafeMemory.INSTANCE.nativeMemoryUsed();
}
/**
* Returns the maximum direct memory in bytes that can ever be allocated or 0 if the
* value cannot be determined.
* (i.e. ever allocated via ByteBuffer.allocateDirect())
*
* @return the maximum direct memory in bytes that can ever be allocated or 0 if the
* value cannot be determined
*/
public static long maxDirectMemory() {
return MAX_DIRECT_MEMORY;
}
/**
* Returns if the JVM runs in 64 bit mode.
*
* @return if the JVM runs in 64 bit mode
*/
public static boolean is64bit() {
return IS_64BIT;
}
public static void resetExceptionHandlers() {
setErrorExceptionHandler(DEFAULT_ERROR_EXCEPTION_HANDLER);
setWarnExceptionHandler(DEFAULT_WARN_EXCEPTION_HANDLER);
setDebugExceptionHandler(DEFAULT_DEBUG_EXCEPTION_HANDLER);
setPerfExceptionHandler(DEFAULT_PERF_EXCEPTION_HANDLER);
}
public static void setErrorExceptionHandler(ExceptionHandler exceptionHandler) {
ERROR.defaultHandler(exceptionHandler).resetThreadLocalHandler();
}
public static void setWarnExceptionHandler(ExceptionHandler exceptionHandler) {
WARN.defaultHandler(exceptionHandler).resetThreadLocalHandler();
}
public static void setDebugExceptionHandler(ExceptionHandler exceptionHandler) {
DEBUG.defaultHandler(exceptionHandler).resetThreadLocalHandler();
}
public static void setPerfExceptionHandler(ExceptionHandler exceptionHandler) {
PERF.defaultHandler(exceptionHandler).resetThreadLocalHandler();
}
public static void disableDebugHandler() {
setDebugExceptionHandler(null);
}
public static void disablePerfHandler() {
setPerfExceptionHandler(null);
}
public static void disableWarnHandler() {
setWarnExceptionHandler(null);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions() {
return recordExceptions(true);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(boolean debug) {
return recordExceptions(debug, false);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(boolean debug, boolean exceptionsOnly) {
return recordExceptions(debug, exceptionsOnly, true);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(final boolean debug,
final boolean exceptionsOnly,
final boolean logToSlf4j) {
final Map<ExceptionKey, Integer> map = Collections.synchronizedMap(new LinkedHashMap<>());
setErrorExceptionHandler(recordingExceptionHandler(LogLevel.ERROR, map, exceptionsOnly, logToSlf4j));
setWarnExceptionHandler(recordingExceptionHandler(LogLevel.WARN, map, exceptionsOnly, logToSlf4j));
setPerfExceptionHandler(debug
? recordingExceptionHandler(LogLevel.PERF, map, exceptionsOnly, logToSlf4j)
: logToSlf4j ? Slf4jExceptionHandler.PERF : NullExceptionHandler.NOTHING);
setDebugExceptionHandler(debug
? recordingExceptionHandler(LogLevel.DEBUG, map, exceptionsOnly, logToSlf4j)
: logToSlf4j ? Slf4jExceptionHandler.DEBUG : NullExceptionHandler.NOTHING);
return map;
}
private static ExceptionHandler recordingExceptionHandler(final LogLevel logLevel,
final Map<ExceptionKey, Integer> map,
final boolean exceptionsOnly,
final boolean logToSlf4j) {
final ExceptionHandler eh = new RecordingExceptionHandler(logLevel, map, exceptionsOnly);
if (logToSlf4j)
return new ChainedExceptionHandler(eh, Slf4jExceptionHandler.valueOf(logLevel));
return eh;
}
public static boolean hasException(@NotNull final Map<ExceptionKey, Integer> exceptions) {
final Iterator<ExceptionKey> iterator = exceptions.keySet().iterator();
while (iterator.hasNext()) {
final ExceptionKey k = iterator.next();
if (k.level() != LogLevel.DEBUG && k.level() != LogLevel.PERF)
return true;
}
return false;
}
public static void setExceptionHandlers(@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
ERROR.defaultHandler(error);
WARN.defaultHandler(warn);
DEBUG.defaultHandler(debug);
}
public static void setExceptionHandlers(@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setExceptionHandlers(error, warn, debug);
PERF.defaultHandler(perf);
}
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
ERROR.threadLocalHandler(error);
WARN.threadLocalHandler(warn);
DEBUG.threadLocalHandler(debug);
}
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setThreadLocalExceptionHandlers(error, warn, debug);
PERF.threadLocalHandler(perf);
}
/**
* Returns an ExceptionHandler for errors, this prints as System.err or ERROR level logging.
* In tests these messages are usually captured and checked that the error expected and only those expected are produced.
*
* @return the ERROR exception handler
*/
@NotNull
public static ExceptionHandler error() {
return ERROR;
}
/**
* Returns an ExceptionHandler for warnings, this prints as System.out or WARN level logging.
* In tests these messages are usually captured and checked that the warning expected and only those expected are produced.
*
* @return the WARN exception handler
*/
@NotNull
public static ExceptionHandler warn() {
return WARN;
}
/**
* Returns an ExceptionHandler for startup messages, this prints as System.out or INFO level logging.
* In tests these messages are generally not captured for checking.
*
* @return the STARTUP exception handler
*/
@NotNull
public static ExceptionHandler startup() {
// TODO, add a startup level?
return PERF;
}
/**
* Returns an ExceptionHandler for performance messages, this prints as System.out or INFO level logging.
* In tests these messages are generally not captured for checking, but a few tests may check performance metrics are reported.
*
* @return the PERF exception handler
*/
@NotNull
public static ExceptionHandler perf() {
return PERF;
}
/**
* Returns an ExceptionHandler for debug messages, this prints as System.out or DEBUG level logging.
* In tests these messages are generally not captured for checking.
*
* @return the DEBUG exception handler
*/
@NotNull
public static ExceptionHandler debug() {
return DEBUG;
}
public static void dumpException(@NotNull final Map<ExceptionKey, Integer> exceptions) {
final Slf4jExceptionHandler warn = Slf4jExceptionHandler.WARN;
for (@NotNull Entry<ExceptionKey, Integer> entry : exceptions.entrySet()) {
final ExceptionKey key = entry.getKey();
warn.on(Jvm.class, key.level() + " " + key.clazz().getSimpleName() + " " + key.message(), key.throwable());
final Integer value = entry.getValue();
if (value > 1)
warn.on(Jvm.class, "Repeated " + value + " times");
}
resetExceptionHandlers();
}
public static boolean isDebugEnabled(final Class<?> aClass) {
return DEBUG.isEnabled(aClass);
}
public static boolean isPerfEnabled(final Class<?> aClass) {
return PERF.isEnabled(aClass);
}
private static long maxDirectMemory0() {
try {
final Class<?> clz;
if (IS_JAVA_9_PLUS) {
clz = Class.forName("jdk.internal.misc.VM");
} else {
clz = Class.forName("sun.misc.VM");
}
final Field f = getField(clz, "directMemory");
return f.getLong(null);
} catch (Exception e) {
// ignore
}
System.err.println(Jvm.class.getName() + ": Unable to determine max direct memory");
return 0L;
}
/**
* Adds the provided {@code signalHandler} to an internal chain of handlers that will be invoked
* upon detecting system signals (e.g. HUP, INT, TERM).
* <p>
* Not all signals are available on all operating systems.
*
* @param signalHandler to call on a signal
*/
public static void addSignalHandler(final SignalHandler signalHandler) {
final SignalHandler signalHandler2 = signal -> {
Jvm.warn().on(signalHandler.getClass(), "Signal " + signal + " triggered for " + signalHandler);
signalHandler.handle(signal);
};
signalHandlerGlobal.handlers2.add(signalHandler2);
InitSignalHandlers.init();
}
/**
* Inserts a low-cost Java safe-point in the code path.
*/
public static void safepoint() {