|
19 | 19 | import com.djrapitops.plan.utilities.java.Reflection; |
20 | 20 |
|
21 | 21 | import java.util.Optional; |
| 22 | +import java.util.concurrent.atomic.AtomicBoolean; |
22 | 23 |
|
23 | 24 | /** |
24 | 25 | * Accessor for the average MSPT field in MinecraftServer class which is a long[] array with 100 values. |
|
27 | 28 | */ |
28 | 29 | public class SpigotMspt { |
29 | 30 |
|
| 31 | + private static final AtomicBoolean PREPARED_SERVER = new AtomicBoolean(false); |
| 32 | + private static Reflection.FieldAccessor<long[]> msptField; |
| 33 | + private static Object server; |
| 34 | + |
| 35 | + private SpigotMspt() { |
| 36 | + /* Static method class */ |
| 37 | + } |
| 38 | + |
30 | 39 | public static Optional<long[]> getMspt() { |
31 | 40 | return Optional.ofNullable(getValue()); |
32 | 41 | } |
33 | 42 |
|
34 | 43 | private static long[] getValue() { |
35 | 44 | try { |
36 | | - Class<?> minecraftServerClass = Reflection.getMinecraftClass("MinecraftServer"); |
37 | | - Reflection.FieldAccessor<long[]> field = Reflection.findField(minecraftServerClass, long[].class); |
38 | | - return field.get(Reflection.getMinecraftServer().orElse(null)); |
| 45 | + prepField(); |
| 46 | + prepServer(); |
| 47 | + return msptField.get(server); |
39 | 48 | } catch (Exception | NoClassDefFoundError | NoSuchFieldError e) { |
40 | 49 | return null; |
41 | 50 | } |
42 | 51 | } |
43 | 52 |
|
| 53 | + private static void prepServer() { |
| 54 | + if (!PREPARED_SERVER.get()) { |
| 55 | + server = Reflection.getMinecraftServer().orElse(null); |
| 56 | + PREPARED_SERVER.set(true); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private static void prepField() { |
| 61 | + if (msptField == null) { |
| 62 | + Class<?> minecraftServerClass = Reflection.getMinecraftClass("MinecraftServer"); |
| 63 | + msptField = Reflection.findField(minecraftServerClass, long[].class); |
| 64 | + } |
| 65 | + } |
| 66 | + |
44 | 67 | } |
0 commit comments