View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.internal;
17  
18  import io.netty.util.internal.logging.InternalLogger;
19  import io.netty.util.internal.logging.InternalLoggerFactory;
20  import jdk.jfr.FlightRecorder;
21  import org.jctools.queues.MpmcArrayQueue;
22  import org.jctools.queues.MpscArrayQueue;
23  import org.jctools.queues.MpscChunkedArrayQueue;
24  import org.jctools.queues.MpscUnboundedArrayQueue;
25  import org.jctools.queues.SpscLinkedQueue;
26  import org.jctools.queues.atomic.MpmcAtomicArrayQueue;
27  import org.jctools.queues.atomic.MpscAtomicArrayQueue;
28  import org.jctools.queues.atomic.MpscChunkedAtomicArrayQueue;
29  import org.jctools.queues.atomic.MpscUnboundedAtomicArrayQueue;
30  import org.jctools.queues.atomic.SpscLinkedAtomicQueue;
31  import org.jctools.queues.atomic.unpadded.MpscAtomicUnpaddedArrayQueue;
32  import org.jctools.queues.unpadded.MpscUnpaddedArrayQueue;
33  import org.jctools.queues.varhandle.MpmcVarHandleArrayQueue;
34  import org.jctools.queues.varhandle.MpscChunkedVarHandleArrayQueue;
35  import org.jctools.queues.varhandle.MpscUnboundedVarHandleArrayQueue;
36  import org.jctools.queues.varhandle.MpscVarHandleArrayQueue;
37  import org.jctools.queues.varhandle.SpscLinkedVarHandleQueue;
38  import org.jctools.queues.varhandle.unpadded.MpscVarHandleUnpaddedArrayQueue;
39  import org.jctools.util.Pow2;
40  import org.jctools.util.UnsafeAccess;
41  
42  import java.io.BufferedReader;
43  import java.io.File;
44  import java.io.IOException;
45  import java.io.InputStreamReader;
46  import java.lang.invoke.MethodHandles;
47  import java.lang.invoke.VarHandle;
48  import java.lang.reflect.Field;
49  import java.nio.ByteBuffer;
50  import java.nio.ByteOrder;
51  import java.nio.charset.StandardCharsets;
52  import java.nio.file.Files;
53  import java.nio.file.Path;
54  import java.nio.file.Paths;
55  import java.security.AccessController;
56  import java.security.PrivilegedAction;
57  import java.util.Arrays;
58  import java.util.Collections;
59  import java.util.Deque;
60  import java.util.LinkedHashSet;
61  import java.util.Locale;
62  import java.util.Map;
63  import java.util.Queue;
64  import java.util.Random;
65  import java.util.Set;
66  import java.util.SplittableRandom;
67  import java.util.concurrent.ConcurrentHashMap;
68  import java.util.concurrent.ConcurrentLinkedDeque;
69  import java.util.concurrent.ConcurrentMap;
70  import java.util.concurrent.ThreadLocalRandom;
71  import java.util.concurrent.atomic.AtomicLong;
72  import java.util.regex.Matcher;
73  import java.util.regex.Pattern;
74  
75  import static io.netty.util.internal.PlatformDependent0.HASH_CODE_ASCII_SEED;
76  import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C1;
77  import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C2;
78  import static io.netty.util.internal.PlatformDependent0.hashCodeAsciiSanitize;
79  import static io.netty.util.internal.PlatformDependent0.unalignedAccess;
80  import static java.lang.Math.max;
81  import static java.lang.Math.min;
82  
83  /**
84   * Utility that detects various properties specific to the current runtime
85   * environment, such as Java version and the availability of the
86   * {@code sun.misc.Unsafe} object.
87   * <p>
88   * You can disable the use of {@code sun.misc.Unsafe} if you specify
89   * the system property <strong>io.netty.noUnsafe</strong>.
90   */
91  public final class PlatformDependent {
92  
93      private static final InternalLogger logger = InternalLoggerFactory.getInstance(PlatformDependent.class);
94  
95      private static final boolean MAYBE_SUPER_USER;
96  
97      private static final boolean CAN_ENABLE_TCP_NODELAY_BY_DEFAULT = !isAndroid();
98  
99      private static final Throwable UNSAFE_UNAVAILABILITY_CAUSE = unsafeUnavailabilityCause0();
100     private static final boolean IS_J9_JVM = isJ9Jvm0();
101     private static final boolean IS_IVKVM_DOT_NET = isIkvmDotNet0();
102     private static final boolean DIRECT_BUFFER_PREFERRED;
103     private static final boolean EXPLICIT_NO_PREFER_DIRECT;
104     private static final long MAX_DIRECT_MEMORY = estimateMaxDirectMemory();
105 
106     private static final int MPSC_CHUNK_SIZE =  1024;
107     private static final int MIN_MAX_MPSC_CAPACITY =  MPSC_CHUNK_SIZE * 2;
108     private static final int MAX_ALLOWED_MPSC_CAPACITY = Pow2.MAX_POW2;
109 
110     private static final long BYTE_ARRAY_BASE_OFFSET = byteArrayBaseOffset0();
111 
112     private static final File TMPDIR = tmpdir0();
113 
114     private static final int BIT_MODE = bitMode0();
115     private static final String NORMALIZED_ARCH = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
116     private static final String NORMALIZED_OS = normalizeOs(SystemPropertyUtil.get("os.name", ""));
117 
118     private static final Set<String> LINUX_OS_CLASSIFIERS;
119 
120     private static final boolean IS_WINDOWS = isWindows0();
121     private static final boolean IS_OSX = isOsx0();
122 
123     private static final int ADDRESS_SIZE = addressSize0();
124     private static final AtomicLong DIRECT_MEMORY_COUNTER;
125     private static final long DIRECT_MEMORY_LIMIT;
126     private static final Cleaner CLEANER;
127     private static final Cleaner LEGACY_CLEANER;
128     private static final boolean HAS_ALLOCATE_UNINIT_ARRAY;
129     private static final String LINUX_ID_PREFIX = "ID=";
130     private static final String LINUX_ID_LIKE_PREFIX = "ID_LIKE=";
131     public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
132     private static final boolean IGNORE_EXPENSIVE_CLEAN =
133             SystemPropertyUtil.getBoolean("io.netty.ignoreExpensiveClean", false);
134 
135     private static final boolean JFR;
136     private static final boolean VAR_HANDLE;
137 
138     private static final Cleaner NOOP = new Cleaner() {
139         @Override
140         public CleanableDirectBuffer allocate(int capacity) {
141             return new CleanableDirectBuffer() {
142                 private final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(capacity);
143 
144                 @Override
145                 public ByteBuffer buffer() {
146                     return byteBuffer;
147                 }
148 
149                 @Override
150                 public void clean() {
151                     // NOOP
152                 }
153 
154                 @Override
155                 public boolean hasMemoryAddress() {
156                     return hasDirectByteBufferAddress(byteBuffer);
157                 }
158 
159                 @Override
160                 public long memoryAddress() {
161                     return directBufferAddress(byteBuffer);
162                 }
163             };
164         }
165 
166         @Override
167         public void freeDirectBuffer(ByteBuffer buffer) {
168             // NOOP
169         }
170 
171         @Override
172         public boolean hasExpensiveClean() {
173             return false;
174         }
175     };
176 
177     static {
178         // Here is how the system property is used:
179         //
180         // * <  0  - Don't use cleaner, and inherit max direct memory from java. In this case the
181         //           "practical max direct memory" would be 2 * max memory as defined by the JDK.
182         // * == 0  - Use cleaner, Netty will not enforce max memory, and instead will defer to JDK.
183         // * >  0  - Don't use cleaner. This will limit Netty's total direct memory
184         //           (note: that JDK's direct memory limit is independent of this).
185         long maxDirectMemory = SystemPropertyUtil.getLong("io.netty.maxDirectMemory", -1);
186 
187         // Initialize the direct memory counter independently of Unsafe availability,
188         // so that io.netty.maxDirectMemory is enforced even when Unsafe is not available (e.g. Java 25+).
189         if (maxDirectMemory == 0) {
190             DIRECT_MEMORY_COUNTER = null;
191         } else if (maxDirectMemory < 0) {
192             maxDirectMemory = MAX_DIRECT_MEMORY;
193             if (maxDirectMemory <= 0) {
194                 DIRECT_MEMORY_COUNTER = null;
195             } else {
196                 DIRECT_MEMORY_COUNTER = new AtomicLong();
197             }
198         } else {
199             DIRECT_MEMORY_COUNTER = new AtomicLong();
200         }
201         logger.debug("-Dio.netty.maxDirectMemory: {} bytes", maxDirectMemory);
202         DIRECT_MEMORY_LIMIT = maxDirectMemory >= 1 ? maxDirectMemory : MAX_DIRECT_MEMORY;
203         HAS_ALLOCATE_UNINIT_ARRAY = javaVersion() >= 9 && PlatformDependent0.hasAllocateArrayMethod();
204 
205         MAYBE_SUPER_USER = maybeSuperUser0();
206 
207         if (!isAndroid()) {
208             // only direct to method if we are not running on android.
209             // See https://github.com/netty/netty/issues/2604
210             if (javaVersion() >= 9) {
211                 // Try Java 9 cleaner first, because it's based on Unsafe and can skip a few steps.
212                 if (CleanerJava9.isSupported()) {
213                     LEGACY_CLEANER = new CleanerJava9();
214                 } else if (CleanerJava24Linker.isSupported()) {
215                     // On Java 24+ we'd like to not use Unsafe because it produces warnings. We have MemorySegment,
216                     // but we cannot use "shared" arenas due to JDK bugs.
217                     // If the "linker" implementation is supported, then we have native access permissions
218                     // in the "io.netty.common" module, and we can link directly to the process' malloc() and free().
219                     LEGACY_CLEANER = new CleanerJava24Linker();
220                 } else if (CleanerJava25.isSupported()) {
221                     // On Java 25+ we can't use Unsafe, but we have functioning MemorySegment support.
222                     // We don't have native access permissions to link malloc() and free() directly, but we can
223                     // use shared memory segment instances.
224                     LEGACY_CLEANER = new CleanerJava25();
225                 } else {
226                     LEGACY_CLEANER = NOOP;
227                 }
228             } else {
229                 LEGACY_CLEANER = CleanerJava6.isSupported() ? new CleanerJava6() : NOOP;
230             }
231         } else {
232             LEGACY_CLEANER = NOOP;
233         }
234         if (maxDirectMemory != 0 && hasUnsafe() && PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
235             CLEANER = new DirectCleaner();
236         } else {
237             CLEANER = LEGACY_CLEANER;
238         }
239 
240         EXPLICIT_NO_PREFER_DIRECT = SystemPropertyUtil.getBoolean("io.netty.noPreferDirect", false);
241         // We should always prefer direct buffers by default if we can use a Cleaner to release direct buffers.
242         DIRECT_BUFFER_PREFERRED = CLEANER != NOOP
243                                   && !EXPLICIT_NO_PREFER_DIRECT;
244         if (logger.isDebugEnabled()) {
245             logger.debug("-Dio.netty.noPreferDirect: {}", EXPLICIT_NO_PREFER_DIRECT);
246         }
247 
248         logger.debug("-Dio.netty.ignoreExpensiveClean: {}", IGNORE_EXPENSIVE_CLEAN);
249 
250         /*
251          * We do not want to log this message if unsafe is explicitly disabled. Do not remove the explicit no unsafe
252          * guard.
253          */
254         if (CLEANER == NOOP && !PlatformDependent0.isExplicitNoUnsafe()) {
255             logger.info(
256                     "Your platform does not provide complete low-level API for accessing direct buffers reliably. " +
257                     "Unless explicitly requested, heap buffer will always be preferred to avoid potential system " +
258                     "instability.");
259         }
260 
261         final Set<String> availableClassifiers = new LinkedHashSet<>();
262 
263         if (!addPropertyOsClassifiers(availableClassifiers)) {
264             addFilesystemOsClassifiers(availableClassifiers);
265         }
266         LINUX_OS_CLASSIFIERS = Collections.unmodifiableSet(availableClassifiers);
267 
268         // Read the property first, so that disabling JFR support keeps Netty away from jdk.jfr entirely.
269         boolean jfr = SystemPropertyUtil.getBoolean("io.netty.jfr.enabled", true);
270         Throwable jfrFailure = null;
271         if (jfr) {
272             try {
273                 //noinspection Since15
274                 jfr = FlightRecorder.isAvailable();
275             } catch (Throwable t) {
276                 jfrFailure = t;
277                 jfr = false;
278             }
279         }
280         JFR = jfr;
281         if (logger.isTraceEnabled() && jfrFailure != null) {
282             logger.debug("-Dio.netty.jfr.enabled: {}", JFR, jfrFailure);
283         } else if (logger.isDebugEnabled()) {
284             logger.debug("-Dio.netty.jfr.enabled: {}", JFR);
285         }
286         VAR_HANDLE = initializeVarHandle();
287     }
288 
289     private static boolean initializeVarHandle() {
290         if (isUnaligned() || javaVersion() < 9 ||
291                 PlatformDependent0.isNativeImage()) {
292             return false;
293         }
294         boolean varHandleAvailable = false;
295         Throwable varHandleFailure;
296         try {
297             VarHandle.storeStoreFence();
298             varHandleAvailable = VarHandleFactory.isSupported();
299             varHandleFailure = VarHandleFactory.unavailableCause();
300         } catch (Throwable t) {
301             // no-op
302             varHandleFailure = t;
303         }
304         if (varHandleFailure != null) {
305             logger.debug("java.lang.invoke.VarHandle: unavailable, reason: {}", varHandleFailure.toString());
306         } else {
307             logger.debug("java.lang.invoke.VarHandle: available");
308         }
309         boolean varHandleEnabled = varHandleAvailable &&
310                 SystemPropertyUtil.getBoolean("io.netty.varHandle.enabled", varHandleAvailable);
311         if (logger.isTraceEnabled() && varHandleFailure != null) {
312             logger.debug("-Dio.netty.varHandle.enabled: {}", varHandleEnabled, varHandleFailure);
313         } else if (logger.isDebugEnabled()) {
314             logger.debug("-Dio.netty.varHandle.enabled: {}", varHandleEnabled);
315         }
316         return varHandleEnabled;
317     }
318 
319     // For specifications, see https://www.freedesktop.org/software/systemd/man/os-release.html
320     static void addFilesystemOsClassifiers(final Set<String> availableClassifiers) {
321         if (processOsReleaseFile("/etc/os-release", availableClassifiers)) {
322             return;
323         }
324         processOsReleaseFile("/usr/lib/os-release", availableClassifiers);
325     }
326 
327     private static boolean processOsReleaseFile(String osReleaseFileName, Set<String> availableClassifiers) {
328         Path file = Paths.get(osReleaseFileName);
329         return AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
330             try {
331                 if (Files.exists(file)) {
332                     try (BufferedReader reader = new BufferedReader(new InputStreamReader(
333                             new BoundedInputStream(Files.newInputStream(file)), StandardCharsets.UTF_8))) {
334                         String line;
335                         while ((line = reader.readLine()) != null) {
336                             if (line.startsWith(LINUX_ID_PREFIX)) {
337                                 String id = normalizeOsReleaseVariableValue(
338                                         line.substring(LINUX_ID_PREFIX.length()));
339                                 addClassifier(availableClassifiers, id);
340                             } else if (line.startsWith(LINUX_ID_LIKE_PREFIX)) {
341                                 line = normalizeOsReleaseVariableValue(
342                                         line.substring(LINUX_ID_LIKE_PREFIX.length()));
343                                 addClassifier(availableClassifiers, line.split(" "));
344                             }
345                         }
346                     } catch (SecurityException e) {
347                         logger.debug("Unable to read {}", osReleaseFileName, e);
348                     } catch (IOException e) {
349                         logger.debug("Error while reading content of {}", osReleaseFileName, e);
350                     }
351                     // specification states we should only fall back if /etc/os-release does not exist
352                     return true;
353                 }
354             } catch (SecurityException e) {
355                 logger.debug("Unable to check if {} exists", osReleaseFileName, e);
356             }
357             return false;
358         });
359     }
360 
361     static boolean addPropertyOsClassifiers(Set<String> availableClassifiers) {
362         // empty: -Dio.netty.osClassifiers (no distro specific classifiers for native libs)
363         // single ID: -Dio.netty.osClassifiers=ubuntu
364         // pair ID, ID_LIKE: -Dio.netty.osClassifiers=ubuntu,debian
365         // illegal otherwise
366         String osClassifiersPropertyName = "io.netty.osClassifiers";
367         String osClassifiers = SystemPropertyUtil.get(osClassifiersPropertyName);
368         if (osClassifiers == null) {
369             return false;
370         }
371         if (osClassifiers.isEmpty()) {
372             // let users omit classifiers with just -Dio.netty.osClassifiers
373             return true;
374         }
375         String[] classifiers = osClassifiers.split(",");
376         if (classifiers.length == 0) {
377             throw new IllegalArgumentException(
378                     osClassifiersPropertyName + " property is not empty, but contains no classifiers: "
379                             + osClassifiers);
380         }
381         // at most ID, ID_LIKE classifiers
382         if (classifiers.length > 2) {
383             throw new IllegalArgumentException(
384                     osClassifiersPropertyName + " property contains more than 2 classifiers: " + osClassifiers);
385         }
386         for (String classifier : classifiers) {
387             addClassifier(availableClassifiers, classifier);
388         }
389         return true;
390     }
391 
392     public static long byteArrayBaseOffset() {
393         return BYTE_ARRAY_BASE_OFFSET;
394     }
395 
396     public static boolean hasDirectBufferNoCleanerConstructor() {
397         return PlatformDependent0.hasDirectBufferNoCleanerConstructor();
398     }
399 
400     public static byte[] allocateUninitializedArray(int size) {
401         return HAS_ALLOCATE_UNINIT_ARRAY ?  PlatformDependent0.allocateUninitializedArray(size) : new byte[size];
402     }
403 
404     /**
405      * Returns {@code true} if and only if the current platform is Android
406      */
407     public static boolean isAndroid() {
408         return PlatformDependent0.isAndroid();
409     }
410 
411     /**
412      * Return {@code true} if the JVM is running on Windows
413      */
414     public static boolean isWindows() {
415         return IS_WINDOWS;
416     }
417 
418     /**
419      * Return {@code true} if the JVM is running on OSX / MacOS
420      */
421     public static boolean isOsx() {
422         return IS_OSX;
423     }
424 
425     /**
426      * Return {@code true} if the current user may be a super-user. Be aware that this is just an hint and so it may
427      * return false-positives.
428      */
429     public static boolean maybeSuperUser() {
430         return MAYBE_SUPER_USER;
431     }
432 
433     /**
434      * Return the version of Java under which this library is used.
435      */
436     public static int javaVersion() {
437         return PlatformDependent0.javaVersion();
438     }
439 
440     /**
441      * @param thread The thread to be checked.
442      * @return {@code true} if this {@link Thread} is a virtual thread, {@code false} otherwise.
443      */
444     public static boolean isVirtualThread(Thread thread) {
445         return PlatformDependent0.isVirtualThread(thread);
446     }
447 
448     /**
449      * Returns {@code true} if and only if it is fine to enable TCP_NODELAY socket option by default.
450      */
451     public static boolean canEnableTcpNoDelayByDefault() {
452         return CAN_ENABLE_TCP_NODELAY_BY_DEFAULT;
453     }
454 
455     /**
456      * Return {@code true} if {@code sun.misc.Unsafe} was found on the classpath and can be used for accelerated
457      * direct memory access.
458      */
459     public static boolean hasUnsafe() {
460         return UNSAFE_UNAVAILABILITY_CAUSE == null;
461     }
462 
463     /**
464      * Return the reason (if any) why {@code sun.misc.Unsafe} was not available.
465      */
466     public static Throwable getUnsafeUnavailabilityCause() {
467         return UNSAFE_UNAVAILABILITY_CAUSE;
468     }
469 
470     /**
471      * {@code true} if and only if the platform supports unaligned access.
472      *
473      * @see <a href="https://en.wikipedia.org/wiki/Segmentation_fault#Bus_error">Wikipedia on segfault</a>
474      */
475     public static boolean isUnaligned() {
476         return PlatformDependent0.isUnaligned();
477     }
478 
479     /**
480      * Returns {@code true} if the platform has reliable low-level direct buffer access API and a user has not specified
481      * {@code -Dio.netty.noPreferDirect} option.
482      */
483     public static boolean directBufferPreferred() {
484         return DIRECT_BUFFER_PREFERRED;
485     }
486 
487     /**
488      * Returns {@code true} if user has specified
489      * {@code -Dio.netty.noPreferDirect=true} option.
490      */
491     public static boolean isExplicitNoPreferDirect() {
492         return EXPLICIT_NO_PREFER_DIRECT;
493     }
494 
495     /**
496      * Return {@code true} if the selected cleaner can free direct buffers in a controlled way. This guarantee only
497      * applies for buffers allocated via {@link #allocateDirect(int)} and when using the {@code clean} method of the
498      * returned {@link CleanableDirectBuffer}.
499      */
500     public static boolean canReliabilyFreeDirectBuffers() {
501         return CLEANER != NOOP;
502     }
503 
504     /**
505      * Returns the maximum memory reserved for direct buffer allocation.
506      */
507     public static long maxDirectMemory() {
508         return DIRECT_MEMORY_LIMIT;
509     }
510 
511     /**
512      * Returns the current memory reserved for direct buffer allocation.
513      * This method returns -1 in case that a value is not available.
514      *
515      * @see #maxDirectMemory()
516      */
517     public static long usedDirectMemory() {
518         return DIRECT_MEMORY_COUNTER != null ? DIRECT_MEMORY_COUNTER.get() : -1;
519     }
520 
521     /**
522      * Returns the temporary directory.
523      */
524     public static File tmpdir() {
525         return TMPDIR;
526     }
527 
528     /**
529      * Returns the bit mode of the current VM (usually 32 or 64.)
530      */
531     public static int bitMode() {
532         return BIT_MODE;
533     }
534 
535     /**
536      * Return the address size of the OS.
537      * 4 (for 32 bits systems ) and 8 (for 64 bits systems).
538      */
539     public static int addressSize() {
540         return ADDRESS_SIZE;
541     }
542 
543     public static long allocateMemory(long size) {
544         return PlatformDependent0.allocateMemory(size);
545     }
546 
547     public static void freeMemory(long address) {
548         PlatformDependent0.freeMemory(address);
549     }
550 
551     public static long reallocateMemory(long address, long newSize) {
552         return PlatformDependent0.reallocateMemory(address, newSize);
553     }
554 
555     /**
556      * Raises an exception bypassing compiler checks for checked exceptions.
557      */
558     public static void throwException(Throwable t) {
559         PlatformDependent0.throwException(t);
560     }
561 
562     /**
563      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
564      * @deprecated please use new ConcurrentHashMap<K, V>() directly.
565      */
566     @Deprecated
567     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap() {
568         return new ConcurrentHashMap<>();
569     }
570 
571     /**
572      * Creates a new fastest {@link LongCounter} implementation for the current platform.
573      * @deprecated please use {@link java.util.concurrent.atomic.LongAdder} instead.
574      */
575     @Deprecated
576     public static LongCounter newLongCounter() {
577         return new LongAdderCounter();
578     }
579 
580     /**
581      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
582      * @deprecated please use new ConcurrentHashMap<K, V>() directly.
583      */
584     @Deprecated
585     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity) {
586         return new ConcurrentHashMap<>(initialCapacity);
587     }
588 
589     /**
590      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
591      * @deprecated please use new ConcurrentHashMap<K, V>() directly.
592      */
593     @Deprecated
594     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity, float loadFactor) {
595         return new ConcurrentHashMap<>(initialCapacity, loadFactor);
596     }
597 
598     /**
599      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
600      * @deprecated please use new ConcurrentHashMap<K, V>() directly.
601      */
602     @Deprecated
603     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(
604             int initialCapacity, float loadFactor, int concurrencyLevel) {
605         return new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel);
606     }
607 
608     /**
609      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
610      * @deprecated please use new ConcurrentHashMap<K, V>() directly.
611      */
612     @Deprecated
613     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(Map<? extends K, ? extends V> map) {
614         return new ConcurrentHashMap<>(map);
615     }
616 
617     /**
618      * Allocate a direct {@link ByteBuffer} of the given capacity, and return it alongside its deallocation mechanism.
619      * @param capacity The desired capacity of the direct byte buffer.
620      * @return The {@link CleanableDirectBuffer} instance that contain the buffer and its deallocation mechanism.
621      */
622     public static CleanableDirectBuffer allocateDirect(int capacity) {
623         return allocateDirect(capacity, false);
624     }
625 
626     /**
627      * Allocate a direct {@link ByteBuffer} of the given capacity, and return it alongside its deallocation mechanism.
628      * @param capacity The desired capacity of the direct byte buffer.
629      * @param permitExpensiveClean Whether to allow expensive clean operations or not. If expensive clean operations
630      * are not permitted ({@code false}), then the buffer cleaning may instead be delegated to the GC and reference
631      * processing. Pooling allocators would typically permit expensive clean operations, while unpooled buffers
632      * would not.
633      * @return The {@link CleanableDirectBuffer} instance that contain the buffer and its deallocation mechanism.
634      */
635     public static CleanableDirectBuffer allocateDirect(int capacity, boolean permitExpensiveClean) {
636         if (!IGNORE_EXPENSIVE_CLEAN && !permitExpensiveClean && CLEANER.hasExpensiveClean()) {
637             return NOOP.allocate(capacity);
638         }
639         return CLEANER.allocate(capacity);
640     }
641 
642     /**
643      * Reallocate a direct buffer with the given new capacity.
644      * The old buffer is invalidated and must not be used after this call.
645      *
646      * @param buffer The old buffer to reallocate.
647      * @param newCapacity The desired new capacity.
648      * @return The new {@link CleanableDirectBuffer} with the given capacity.
649      */
650     public static CleanableDirectBuffer reallocateDirect(CleanableDirectBuffer buffer, int newCapacity) {
651         return CLEANER.reallocate(buffer, newCapacity);
652     }
653 
654     /**
655      * Try to deallocate the specified direct {@link ByteBuffer}. Please note this method does nothing if
656      * the current platform does not support this operation or the specified buffer is not a direct buffer.
657      *
658      * @deprecated Use the {@link CleanableDirectBuffer#clean()} from {@link #allocateDirect(int)} instead.
659      */
660     @Deprecated
661     public static void freeDirectBuffer(ByteBuffer buffer) {
662         LEGACY_CLEANER.freeDirectBuffer(buffer);
663     }
664 
665     /**
666      * Check if it is possible to call {@link #directBufferAddress(ByteBuffer)} on the given buffer.
667      * @param buffer The specific buffer instance to check for.
668      * @return {@code true} if {@link #directBufferAddress(ByteBuffer)} can be called on the given buffer,
669      * otherwise {@code false}.
670      */
671     public static boolean hasDirectByteBufferAddress(ByteBuffer buffer) {
672         return PlatformDependent0.hasDirectByteBufferAddress(buffer);
673     }
674 
675     /**
676      * Obtain the native memory address of the given direct byte buffer, or throw an exception if it's not possible.
677      * @param buffer The buffer to get the native memory address for.
678      * @return The native memory address of the give buffer.
679      */
680     public static long directBufferAddress(ByteBuffer buffer) {
681         return PlatformDependent0.directBufferAddress(buffer);
682     }
683 
684     public static ByteBuffer directBuffer(long memoryAddress, int size) {
685         if (PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
686             return PlatformDependent0.newDirectBuffer(memoryAddress, size);
687         }
688         throw new UnsupportedOperationException(
689                 "sun.misc.Unsafe or java.nio.DirectByteBuffer.<init>(long, int) not available");
690     }
691 
692     public static boolean hasVarHandle() {
693         return VAR_HANDLE;
694     }
695 
696     static boolean hasJctoolsVarHandle() {
697         return javaVersion() >= 11;
698     }
699 
700     /**
701      * {@code true} if {@code VarHandle} should be used for multi-byte access.
702      *
703      * The multi-byte access strategy is determined as follows:
704      * 1) If the platform supports unaligned access natively, use {@code Unsafe} as the fastest option.
705      * 2) Otherwise, if {@code VarHandle} is available, use it as a fallback.
706      * 3) Otherwise, fall back to manual byte-by-byte access.
707      */
708     public static boolean useVarHandleForMultiByteAccess() {
709         return !isUnaligned() && VAR_HANDLE;
710     }
711 
712     /**
713      * {@code true} if multi-byte access at arbitrary offsets is possible, either natively through {@code Unsafe}
714      * or via {@code VarHandle} where the JVM handles alignment and byte ordering internally.
715      */
716     public static boolean canUnalignedAccess() {
717         return isUnaligned() || VAR_HANDLE;
718     }
719 
720     public static VarHandle findVarHandleOfIntField(MethodHandles.Lookup lookup, Class<?> type, String fieldName) {
721         if (VAR_HANDLE) {
722             return VarHandleFactory.privateFindVarHandle(lookup, type, fieldName, int.class);
723         }
724         return null;
725     }
726 
727     public static VarHandle intBeArrayView() {
728         if (VAR_HANDLE) {
729             return VarHandleFactory.intBeArrayView();
730         }
731         return null;
732     }
733 
734     public static VarHandle intLeArrayView() {
735         if (VAR_HANDLE) {
736             return VarHandleFactory.intLeArrayView();
737         }
738         return null;
739     }
740 
741     public static VarHandle longBeArrayView() {
742         if (VAR_HANDLE) {
743             return VarHandleFactory.longBeArrayView();
744         }
745         return null;
746     }
747 
748     public static VarHandle longLeArrayView() {
749         if (VAR_HANDLE) {
750             return VarHandleFactory.longLeArrayView();
751         }
752         return null;
753     }
754 
755     public static VarHandle shortBeArrayView() {
756         if (VAR_HANDLE) {
757             return VarHandleFactory.shortBeArrayView();
758         }
759         return null;
760     }
761 
762     public static VarHandle shortLeArrayView() {
763         if (VAR_HANDLE) {
764             return VarHandleFactory.shortLeArrayView();
765         }
766         return null;
767     }
768 
769     public static VarHandle longBeByteBufferView() {
770         if (VAR_HANDLE) {
771             return VarHandleFactory.longBeByteBufferView();
772         }
773         return null;
774     }
775 
776     public static VarHandle longLeByteBufferView() {
777         if (VAR_HANDLE) {
778             return VarHandleFactory.longLeByteBufferView();
779         }
780         return null;
781     }
782 
783     public static VarHandle intBeByteBufferView() {
784         if (VAR_HANDLE) {
785             return VarHandleFactory.intBeByteBufferView();
786         }
787         return null;
788     }
789 
790     public static VarHandle intLeByteBufferView() {
791         if (VAR_HANDLE) {
792             return VarHandleFactory.intLeByteBufferView();
793         }
794         return null;
795     }
796 
797     public static VarHandle shortBeByteBufferView() {
798         if (VAR_HANDLE) {
799             return VarHandleFactory.shortBeByteBufferView();
800         }
801         return null;
802     }
803 
804     public static VarHandle shortLeByteBufferView() {
805         if (VAR_HANDLE) {
806             return VarHandleFactory.shortLeByteBufferView();
807         }
808         return null;
809     }
810 
811     public static Object getObject(Object object, long fieldOffset) {
812         return PlatformDependent0.getObject(object, fieldOffset);
813     }
814 
815     public static int getVolatileInt(Object object, long fieldOffset) {
816         return PlatformDependent0.getIntVolatile(object, fieldOffset);
817     }
818 
819     public static int getInt(Object object, long fieldOffset) {
820         return PlatformDependent0.getInt(object, fieldOffset);
821     }
822 
823     public static void putOrderedInt(Object object, long fieldOffset, int value) {
824         PlatformDependent0.putOrderedInt(object, fieldOffset, value);
825     }
826 
827     public static int getAndAddInt(Object object, long fieldOffset, int delta) {
828         return PlatformDependent0.getAndAddInt(object, fieldOffset, delta);
829     }
830 
831     public static boolean compareAndSwapInt(Object object, long fieldOffset, int expected, int value) {
832         return PlatformDependent0.compareAndSwapInt(object, fieldOffset, expected, value);
833     }
834 
835     static void safeConstructPutInt(Object object, long fieldOffset, int value) {
836         PlatformDependent0.safeConstructPutInt(object, fieldOffset, value);
837     }
838 
839     public static byte getByte(long address) {
840         return PlatformDependent0.getByte(address);
841     }
842 
843     public static short getShort(long address) {
844         return PlatformDependent0.getShort(address);
845     }
846 
847     public static int getInt(long address) {
848         return PlatformDependent0.getInt(address);
849     }
850 
851     public static long getLong(long address) {
852         return PlatformDependent0.getLong(address);
853     }
854 
855     public static byte getByte(byte[] data, int index) {
856         return hasUnsafe() ? PlatformDependent0.getByte(data, index) : data[index];
857     }
858 
859     public static byte getByte(byte[] data, long index) {
860         return hasUnsafe() ? PlatformDependent0.getByte(data, index) : data[toIntExact(index)];
861     }
862 
863     public static short getShort(byte[] data, int index) {
864         return hasUnsafe() ? PlatformDependent0.getShort(data, index) : data[index];
865     }
866 
867     public static int getInt(byte[] data, int index) {
868         return hasUnsafe() ? PlatformDependent0.getInt(data, index) : data[index];
869     }
870 
871     public static int getInt(int[] data, long index) {
872         return hasUnsafe() ? PlatformDependent0.getInt(data, index) : data[toIntExact(index)];
873     }
874 
875     public static long getLong(byte[] data, int index) {
876         return hasUnsafe() ? PlatformDependent0.getLong(data, index) : data[index];
877     }
878 
879     public static long getLong(long[] data, long index) {
880         return hasUnsafe() ? PlatformDependent0.getLong(data, index) : data[toIntExact(index)];
881     }
882 
883     private static int toIntExact(long value) {
884         return Math.toIntExact(value);
885     }
886 
887     private static long getLongSafe(byte[] bytes, int offset) {
888         if (BIG_ENDIAN_NATIVE_ORDER) {
889             return (long) bytes[offset] << 56 |
890                     ((long) bytes[offset + 1] & 0xff) << 48 |
891                     ((long) bytes[offset + 2] & 0xff) << 40 |
892                     ((long) bytes[offset + 3] & 0xff) << 32 |
893                     ((long) bytes[offset + 4] & 0xff) << 24 |
894                     ((long) bytes[offset + 5] & 0xff) << 16 |
895                     ((long) bytes[offset + 6] & 0xff) <<  8 |
896                     (long) bytes[offset + 7] & 0xff;
897         }
898         return (long) bytes[offset] & 0xff |
899                 ((long) bytes[offset + 1] & 0xff) << 8 |
900                 ((long) bytes[offset + 2] & 0xff) << 16 |
901                 ((long) bytes[offset + 3] & 0xff) << 24 |
902                 ((long) bytes[offset + 4] & 0xff) << 32 |
903                 ((long) bytes[offset + 5] & 0xff) << 40 |
904                 ((long) bytes[offset + 6] & 0xff) << 48 |
905                 (long) bytes[offset + 7] << 56;
906     }
907 
908     private static int getIntSafe(byte[] bytes, int offset) {
909         if (BIG_ENDIAN_NATIVE_ORDER) {
910             return bytes[offset] << 24 |
911                     (bytes[offset + 1] & 0xff) << 16 |
912                     (bytes[offset + 2] & 0xff) << 8 |
913                     bytes[offset + 3] & 0xff;
914         }
915         return bytes[offset] & 0xff |
916                 (bytes[offset + 1] & 0xff) << 8 |
917                 (bytes[offset + 2] & 0xff) << 16 |
918                 bytes[offset + 3] << 24;
919     }
920 
921     private static short getShortSafe(byte[] bytes, int offset) {
922         if (BIG_ENDIAN_NATIVE_ORDER) {
923             return (short) (bytes[offset] << 8 | (bytes[offset + 1] & 0xff));
924         }
925         return (short) (bytes[offset] & 0xff | (bytes[offset + 1] << 8));
926     }
927 
928     /**
929      * Identical to {@link PlatformDependent0#hashCodeAsciiCompute(long, int)} but for {@link CharSequence}.
930      */
931     private static int hashCodeAsciiCompute(CharSequence value, int offset, int hash) {
932         if (BIG_ENDIAN_NATIVE_ORDER) {
933             return hash * HASH_CODE_C1 +
934                     // Low order int
935                     hashCodeAsciiSanitizeInt(value, offset + 4) * HASH_CODE_C2 +
936                     // High order int
937                     hashCodeAsciiSanitizeInt(value, offset);
938         }
939         return hash * HASH_CODE_C1 +
940                 // Low order int
941                 hashCodeAsciiSanitizeInt(value, offset) * HASH_CODE_C2 +
942                 // High order int
943                 hashCodeAsciiSanitizeInt(value, offset + 4);
944     }
945 
946     /**
947      * Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(int)} but for {@link CharSequence}.
948      */
949     private static int hashCodeAsciiSanitizeInt(CharSequence value, int offset) {
950         if (BIG_ENDIAN_NATIVE_ORDER) {
951             // mimic a unsafe.getInt call on a big endian machine
952             return (value.charAt(offset + 3) & 0x1f) |
953                    (value.charAt(offset + 2) & 0x1f) << 8 |
954                    (value.charAt(offset + 1) & 0x1f) << 16 |
955                    (value.charAt(offset) & 0x1f) << 24;
956         }
957         return (value.charAt(offset + 3) & 0x1f) << 24 |
958                (value.charAt(offset + 2) & 0x1f) << 16 |
959                (value.charAt(offset + 1) & 0x1f) << 8 |
960                (value.charAt(offset) & 0x1f);
961     }
962 
963     /**
964      * Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(short)} but for {@link CharSequence}.
965      */
966     private static int hashCodeAsciiSanitizeShort(CharSequence value, int offset) {
967         if (BIG_ENDIAN_NATIVE_ORDER) {
968             // mimic a unsafe.getShort call on a big endian machine
969             return (value.charAt(offset + 1) & 0x1f) |
970                     (value.charAt(offset) & 0x1f) << 8;
971         }
972         return (value.charAt(offset + 1) & 0x1f) << 8 |
973                 (value.charAt(offset) & 0x1f);
974     }
975 
976     /**
977      * Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(byte)} but for {@link CharSequence}.
978      */
979     private static int hashCodeAsciiSanitizeByte(char value) {
980         return value & 0x1f;
981     }
982 
983     public static void putByte(long address, byte value) {
984         PlatformDependent0.putByte(address, value);
985     }
986 
987     public static void putShort(long address, short value) {
988         PlatformDependent0.putShort(address, value);
989     }
990 
991     public static void putInt(long address, int value) {
992         PlatformDependent0.putInt(address, value);
993     }
994 
995     public static void putLong(long address, long value) {
996         PlatformDependent0.putLong(address, value);
997     }
998 
999     public static void putByte(byte[] data, int index, byte value) {
1000         PlatformDependent0.putByte(data, index, value);
1001     }
1002 
1003     public static void putByte(Object data, long offset, byte value) {
1004         PlatformDependent0.putByte(data, offset, value);
1005     }
1006 
1007     public static void putShort(byte[] data, int index, short value) {
1008         PlatformDependent0.putShort(data, index, value);
1009     }
1010 
1011     public static void putInt(byte[] data, int index, int value) {
1012         PlatformDependent0.putInt(data, index, value);
1013     }
1014 
1015     public static void putLong(byte[] data, int index, long value) {
1016         PlatformDependent0.putLong(data, index, value);
1017     }
1018 
1019     public static void putObject(Object o, long offset, Object x) {
1020         PlatformDependent0.putObject(o, offset, x);
1021     }
1022 
1023     public static long objectFieldOffset(Field field) {
1024         return PlatformDependent0.objectFieldOffset(field);
1025     }
1026 
1027     public static void copyMemory(long srcAddr, long dstAddr, long length) {
1028         PlatformDependent0.copyMemory(srcAddr, dstAddr, length);
1029     }
1030 
1031     public static void copyMemory(byte[] src, int srcIndex, long dstAddr, long length) {
1032         PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, dstAddr, length);
1033     }
1034 
1035     public static void copyMemory(byte[] src, int srcIndex, byte[] dst, int dstIndex, long length) {
1036         PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex,
1037                                       dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
1038     }
1039 
1040     public static void copyMemory(long srcAddr, byte[] dst, int dstIndex, long length) {
1041         PlatformDependent0.copyMemory(null, srcAddr, dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
1042     }
1043 
1044     public static void setMemory(byte[] dst, int dstIndex, long bytes, byte value) {
1045         PlatformDependent0.setMemory(dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, bytes, value);
1046     }
1047 
1048     public static void setMemory(long address, long bytes, byte value) {
1049         PlatformDependent0.setMemory(address, bytes, value);
1050     }
1051 
1052     public static boolean hasAlignDirectByteBuffer() {
1053         return hasUnsafe() || PlatformDependent0.hasAlignSliceMethod();
1054     }
1055 
1056     public static ByteBuffer alignDirectBuffer(ByteBuffer buffer, int alignment) {
1057         if (!buffer.isDirect()) {
1058             throw new IllegalArgumentException("Cannot get aligned slice of non-direct byte buffer.");
1059         }
1060         if (PlatformDependent0.hasAlignSliceMethod()) {
1061             return PlatformDependent0.alignSlice(buffer, alignment);
1062         }
1063         if (hasUnsafe()) {
1064             long address = directBufferAddress(buffer);
1065             long aligned = align(address, alignment);
1066             buffer.position((int) (aligned - address));
1067             return buffer.slice();
1068         }
1069         // We don't have enough information to be able to align any buffers.
1070         throw new UnsupportedOperationException("Cannot align direct buffer. " +
1071                 "Needs either Unsafe or ByteBuffer.alignSlice method available.");
1072     }
1073 
1074     public static long align(long value, int alignment) {
1075         return Pow2.align(value, alignment);
1076     }
1077 
1078     public static ByteBuffer offsetSlice(ByteBuffer buffer, int index, int length) {
1079         if (PlatformDependent0.hasOffsetSliceMethod()) {
1080             return PlatformDependent0.offsetSlice(buffer, index, length);
1081         } else {
1082             return ((ByteBuffer) buffer.duplicate().clear().position(index).limit(index + length)).slice();
1083         }
1084     }
1085 
1086     public static ByteBuffer absolutePut(ByteBuffer dst, int dstOffset, byte[] src, int srcOffset, int length) {
1087         if (PlatformDependent0.hasAbsolutePutArrayMethod()) {
1088             return PlatformDependent0.absolutePut(dst, dstOffset, src, srcOffset, length);
1089         } else {
1090             ByteBuffer tmp = (ByteBuffer) dst.duplicate().clear().position(dstOffset).limit(dstOffset + length);
1091             tmp.put(ByteBuffer.wrap(src, srcOffset, length));
1092             return dst;
1093         }
1094     }
1095 
1096     public static ByteBuffer absolutePut(ByteBuffer dst, int dstOffset, ByteBuffer src, int srcOffset, int length) {
1097         if (PlatformDependent0.hasAbsolutePutBufferMethod()) {
1098             return PlatformDependent0.absolutePut(dst, dstOffset, src, srcOffset, length);
1099         } else {
1100             ByteBuffer a = (ByteBuffer) dst.duplicate().clear().position(dstOffset).limit(dstOffset + length);
1101             ByteBuffer b = (ByteBuffer) src.duplicate().clear().position(srcOffset).limit(srcOffset + length);
1102             a.put(b);
1103             return dst;
1104         }
1105     }
1106 
1107     static void incrementMemoryCounter(int capacity) {
1108         if (DIRECT_MEMORY_COUNTER != null) {
1109             long newUsedMemory = DIRECT_MEMORY_COUNTER.addAndGet(capacity);
1110             if (newUsedMemory > DIRECT_MEMORY_LIMIT) {
1111                 DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
1112                 throw new OutOfDirectMemoryError("failed to allocate " + capacity
1113                         + " byte(s) of direct memory (used: " + (newUsedMemory - capacity)
1114                         + ", max: " + DIRECT_MEMORY_LIMIT + ')');
1115             }
1116         }
1117     }
1118 
1119     static void decrementMemoryCounter(int capacity) {
1120         if (DIRECT_MEMORY_COUNTER != null) {
1121             long usedMemory = DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
1122             assert usedMemory >= 0;
1123         }
1124     }
1125 
1126     public static boolean useDirectBufferNoCleaner() {
1127         return CLEANER instanceof DirectCleaner;
1128     }
1129 
1130     /**
1131      * Compare two {@code byte} arrays for equality. For performance reasons no bounds checking on the
1132      * parameters is performed.
1133      *
1134      * @param bytes1 the first byte array.
1135      * @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
1136      * @param bytes2 the second byte array.
1137      * @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
1138      * @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
1139      * by the caller.
1140      */
1141     public static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
1142         if (javaVersion() > 8 && (startPos2 | startPos1 | (bytes1.length - length) | bytes2.length - length) == 0) {
1143             return Arrays.equals(bytes1, bytes2);
1144         }
1145         return !hasUnsafe() || !unalignedAccess() ?
1146                   equalsSafe(bytes1, startPos1, bytes2, startPos2, length) :
1147                   PlatformDependent0.equals(bytes1, startPos1, bytes2, startPos2, length);
1148     }
1149 
1150     /**
1151      * Determine if a subsection of an array is zero.
1152      * @param bytes The byte array.
1153      * @param startPos The starting index (inclusive) in {@code bytes}.
1154      * @param length The amount of bytes to check for zero.
1155      * @return {@code false} if {@code bytes[startPos:startsPos+length)} contains a value other than zero.
1156      */
1157     public static boolean isZero(byte[] bytes, int startPos, int length) {
1158         return !hasUnsafe() || !unalignedAccess() ?
1159                 isZeroSafe(bytes, startPos, length) :
1160                 PlatformDependent0.isZero(bytes, startPos, length);
1161     }
1162 
1163     /**
1164      * Compare two {@code byte} arrays for equality without leaking timing information.
1165      * For performance reasons no bounds checking on the parameters is performed.
1166      * <p>
1167      * The {@code int} return type is intentional and is designed to allow cascading of constant time operations:
1168      * <pre>
1169      *     byte[] s1 = new {1, 2, 3};
1170      *     byte[] s2 = new {1, 2, 3};
1171      *     byte[] s3 = new {1, 2, 3};
1172      *     byte[] s4 = new {4, 5, 6};
1173      *     boolean equals = (equalsConstantTime(s1, 0, s2, 0, s1.length) &
1174      *                       equalsConstantTime(s3, 0, s4, 0, s3.length)) != 0;
1175      * </pre>
1176      * @param bytes1 the first byte array.
1177      * @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
1178      * @param bytes2 the second byte array.
1179      * @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
1180      * @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
1181      * by the caller.
1182      * @return {@code 0} if not equal. {@code 1} if equal.
1183      */
1184     public static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
1185         return !hasUnsafe() || !unalignedAccess() ?
1186                   ConstantTimeUtils.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) :
1187                   PlatformDependent0.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length);
1188     }
1189 
1190     /**
1191      * Calculate a hash code of a byte array assuming ASCII character encoding.
1192      * The resulting hash code will be case insensitive.
1193      * @param bytes The array which contains the data to hash.
1194      * @param startPos What index to start generating a hash code in {@code bytes}
1195      * @param length The amount of bytes that should be accounted for in the computation.
1196      * @return The hash code of {@code bytes} assuming ASCII character encoding.
1197      * The resulting hash code will be case insensitive.
1198      */
1199     public static int hashCodeAscii(byte[] bytes, int startPos, int length) {
1200         return !hasUnsafe() || !unalignedAccess() || BIG_ENDIAN_NATIVE_ORDER ?
1201                 hashCodeAsciiSafe(bytes, startPos, length) :
1202                 PlatformDependent0.hashCodeAscii(bytes, startPos, length);
1203     }
1204 
1205     /**
1206      * Calculate a hash code of a byte array assuming ASCII character encoding.
1207      * The resulting hash code will be case insensitive.
1208      * <p>
1209      * This method assumes that {@code bytes} is equivalent to a {@code byte[]} but just using {@link CharSequence}
1210      * for storage. The upper most byte of each {@code char} from {@code bytes} is ignored.
1211      * @param bytes The array which contains the data to hash (assumed to be equivalent to a {@code byte[]}).
1212      * @return The hash code of {@code bytes} assuming ASCII character encoding.
1213      * The resulting hash code will be case insensitive.
1214      */
1215     public static int hashCodeAscii(CharSequence bytes) {
1216         final int length = bytes.length();
1217         final int remainingBytes = length & 7;
1218         int hash = HASH_CODE_ASCII_SEED;
1219         // Benchmarking shows that by just naively looping for inputs 8~31 bytes long we incur a relatively large
1220         // performance penalty (only achieve about 60% performance of loop which iterates over each char). So because
1221         // of this we take special provisions to unroll the looping for these conditions.
1222         if (length >= 32) {
1223             for (int i = length - 8; i >= remainingBytes; i -= 8) {
1224                 hash = hashCodeAsciiCompute(bytes, i, hash);
1225             }
1226         } else if (length >= 8) {
1227             hash = hashCodeAsciiCompute(bytes, length - 8, hash);
1228             if (length >= 16) {
1229                 hash = hashCodeAsciiCompute(bytes, length - 16, hash);
1230                 if (length >= 24) {
1231                     hash = hashCodeAsciiCompute(bytes, length - 24, hash);
1232                 }
1233             }
1234         }
1235         if (remainingBytes == 0) {
1236             return hash;
1237         }
1238         int offset = 0;
1239         if (remainingBytes != 2 & remainingBytes != 4 & remainingBytes != 6) { // 1, 3, 5, 7
1240             hash = hash * HASH_CODE_C1 + hashCodeAsciiSanitizeByte(bytes.charAt(0));
1241             offset = 1;
1242         }
1243         if (remainingBytes != 1 & remainingBytes != 4 & remainingBytes != 5) { // 2, 3, 6, 7
1244             hash = hash * (offset == 0 ? HASH_CODE_C1 : HASH_CODE_C2)
1245                     + hashCodeAsciiSanitize(hashCodeAsciiSanitizeShort(bytes, offset));
1246             offset += 2;
1247         }
1248         if (remainingBytes >= 4) { // 4, 5, 6, 7
1249             return hash * ((offset == 0 | offset == 3) ? HASH_CODE_C1 : HASH_CODE_C2)
1250                     + hashCodeAsciiSanitizeInt(bytes, offset);
1251         }
1252         return hash;
1253     }
1254 
1255     private static final class Mpsc {
1256         private static final boolean USE_MPSC_CHUNKED_ARRAY_QUEUE;
1257 
1258         static {
1259             Object unsafe = null;
1260             if (hasUnsafe()) {
1261                 // jctools goes through its own process of initializing unsafe; of
1262                 // course, this requires permissions which might not be granted to calling code, so we
1263                 // must mark this block as privileged too
1264                 unsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
1265                     @Override
1266                     public Object run() {
1267                         // force JCTools to initialize unsafe
1268                         return UnsafeAccess.UNSAFE;
1269                     }
1270                 });
1271             }
1272 
1273             if (unsafe == null) {
1274                 logger.debug("org.jctools-core.MpscChunkedArrayQueue: unavailable");
1275                 USE_MPSC_CHUNKED_ARRAY_QUEUE = false;
1276             } else {
1277                 logger.debug("org.jctools-core.MpscChunkedArrayQueue: available");
1278                 USE_MPSC_CHUNKED_ARRAY_QUEUE = true;
1279             }
1280         }
1281 
1282         static <T> Queue<T> newMpscQueue(final int maxCapacity) {
1283             // Calculate the max capacity which can not be bigger than MAX_ALLOWED_MPSC_CAPACITY.
1284             // This is forced by the MpscChunkedArrayQueue implementation as will try to round it
1285             // up to the next power of two and so will overflow otherwise.
1286             final int capacity = max(min(maxCapacity, MAX_ALLOWED_MPSC_CAPACITY), MIN_MAX_MPSC_CAPACITY);
1287             return newChunkedMpscQueue(MPSC_CHUNK_SIZE, capacity);
1288         }
1289 
1290         static <T> Queue<T> newChunkedMpscQueue(final int chunkSize, final int capacity) {
1291             if (USE_MPSC_CHUNKED_ARRAY_QUEUE) {
1292                 return new MpscChunkedArrayQueue<T>(chunkSize, capacity);
1293             }
1294             return hasJctoolsVarHandle() ?
1295                     VarHandleQueueHolder.newMpscChunkedQueue(chunkSize, capacity) :
1296                     new MpscChunkedAtomicArrayQueue<T>(chunkSize, capacity);
1297         }
1298 
1299         static <T> Queue<T> newMpscQueue() {
1300             if (USE_MPSC_CHUNKED_ARRAY_QUEUE) {
1301                 return new MpscUnboundedArrayQueue<T>(MPSC_CHUNK_SIZE);
1302             }
1303             return hasJctoolsVarHandle() ?
1304                     VarHandleQueueHolder.newMpscUnboundedQueue(MPSC_CHUNK_SIZE) :
1305                     new MpscUnboundedAtomicArrayQueue<T>(MPSC_CHUNK_SIZE);
1306         }
1307     }
1308 
1309     private static final class VarHandleQueueHolder {
1310         static <T> Queue<T> newMpscChunkedQueue(final int chunkSize, final int capacity) {
1311             return new MpscChunkedVarHandleArrayQueue<T>(chunkSize, capacity);
1312         }
1313 
1314         static <T> Queue<T> newMpscUnboundedQueue(final int chunkSize) {
1315             return new MpscUnboundedVarHandleArrayQueue<T>(chunkSize);
1316         }
1317 
1318         static <T> Queue<T> newSpscQueue() {
1319             return new SpscLinkedVarHandleQueue<T>();
1320         }
1321 
1322         static <T> Queue<T> newFixedMpscQueue(final int capacity) {
1323             return new MpscVarHandleArrayQueue<T>(capacity);
1324         }
1325 
1326         static <T> Queue<T> newFixedMpscUnpaddedQueue(final int capacity) {
1327             return new MpscVarHandleUnpaddedArrayQueue<T>(capacity);
1328         }
1329 
1330         static <T> Queue<T> newFixedMpmcQueue(final int capacity) {
1331             return new MpmcVarHandleArrayQueue<T>(capacity);
1332         }
1333     }
1334 
1335     /**
1336      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1337      * consumer (one thread!).
1338      * @return A MPSC queue which may be unbounded.
1339      */
1340     public static <T> Queue<T> newMpscQueue() {
1341         return Mpsc.newMpscQueue();
1342     }
1343 
1344     /**
1345      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1346      * consumer (one thread!).
1347      */
1348     public static <T> Queue<T> newMpscQueue(final int maxCapacity) {
1349         return Mpsc.newMpscQueue(maxCapacity);
1350     }
1351 
1352     /**
1353      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1354      * consumer (one thread!).
1355      * The queue will grow and shrink its capacity in units of the given chunk size.
1356      */
1357     public static <T> Queue<T> newMpscQueue(final int chunkSize, final int maxCapacity) {
1358         return Mpsc.newChunkedMpscQueue(chunkSize, maxCapacity);
1359     }
1360 
1361     /**
1362      * Create a new {@link Queue} which is safe to use for single producer (one thread!) and a single
1363      * consumer (one thread!).
1364      */
1365     public static <T> Queue<T> newSpscQueue() {
1366         if (hasUnsafe()) {
1367             return new SpscLinkedQueue<T>();
1368         }
1369         return hasJctoolsVarHandle() ?
1370                 VarHandleQueueHolder.newSpscQueue() :
1371                 new SpscLinkedAtomicQueue<T>();
1372     }
1373 
1374     /**
1375      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1376      * consumer (one thread!) with the given fixes {@code capacity}.
1377      */
1378     public static <T> Queue<T> newFixedMpscQueue(int capacity) {
1379         if (hasUnsafe()) {
1380             return new MpscArrayQueue<T>(capacity);
1381         }
1382         return hasJctoolsVarHandle() ?
1383                 VarHandleQueueHolder.newFixedMpscQueue(capacity) :
1384                 new MpscAtomicArrayQueue<T>(capacity);
1385     }
1386 
1387     /**
1388      * Create a new un-padded {@link Queue} which is safe to use for multiple producers (different threads) and a single
1389      * consumer (one thread!) with the given fixes {@code capacity}.<br>
1390      * This should be preferred to {@link #newFixedMpscQueue(int)} when the queue is not to be heavily contended.
1391      */
1392     public static <T> Queue<T> newFixedMpscUnpaddedQueue(int capacity) {
1393         if (hasUnsafe()) {
1394             return new MpscUnpaddedArrayQueue<T>(capacity);
1395         }
1396         return hasJctoolsVarHandle() ?
1397                 VarHandleQueueHolder.newFixedMpscUnpaddedQueue(capacity) :
1398                 new MpscAtomicUnpaddedArrayQueue<T>(capacity);
1399     }
1400 
1401     /**
1402      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and multiple
1403      * consumers with the given fixes {@code capacity}.
1404      */
1405     public static <T> Queue<T> newFixedMpmcQueue(int capacity) {
1406         if (hasUnsafe()) {
1407             return new MpmcArrayQueue<T>(capacity);
1408         }
1409         return hasJctoolsVarHandle() ?
1410                 VarHandleQueueHolder.newFixedMpmcQueue(capacity) :
1411                 new MpmcAtomicArrayQueue<T>(capacity);
1412     }
1413 
1414     /**
1415      * Return the {@link ClassLoader} for the given {@link Class}.
1416      */
1417     public static ClassLoader getClassLoader(final Class<?> clazz) {
1418         return PlatformDependent0.getClassLoader(clazz);
1419     }
1420 
1421     /**
1422      * Return the context {@link ClassLoader} for the current {@link Thread}.
1423      */
1424     public static ClassLoader getContextClassLoader() {
1425         return PlatformDependent0.getContextClassLoader();
1426     }
1427 
1428     /**
1429      * Return the system {@link ClassLoader}.
1430      */
1431     public static ClassLoader getSystemClassLoader() {
1432         return PlatformDependent0.getSystemClassLoader();
1433     }
1434 
1435     /**
1436      * Returns a new concurrent {@link Deque}.
1437      */
1438     public static <C> Deque<C> newConcurrentDeque() {
1439         return new ConcurrentLinkedDeque<C>();
1440     }
1441 
1442     /**
1443      * Return a {@link Random} which is not-threadsafe and so can only be used from the same thread.
1444      * @deprecated Use ThreadLocalRandom.current() instead.
1445      */
1446     @Deprecated
1447     public static Random threadLocalRandom() {
1448         return ThreadLocalRandom.current();
1449     }
1450 
1451     public static void splittableRandomNextBytes(SplittableRandom rng, byte[] data) {
1452         if (javaVersion() >= 10) {
1453             PlatformDependent0.splittableRandomNextBytes(rng, data);
1454         } else {
1455             splittableRandomNextBytesFallback(rng, data);
1456         }
1457     }
1458 
1459     /**
1460      * Fills {@code data} the way {@code SplittableRandom.nextBytes(byte[])} (Java 10+) does.
1461      */
1462     static void splittableRandomNextBytesFallback(SplittableRandom rng, byte[] data) {
1463         int i = 0;
1464         int len = data.length;
1465         int longs = len >>> 3;
1466         while (longs-- > 0) {
1467             long val = rng.nextLong();
1468             for (int j = 0; j < Long.BYTES; j++) {
1469                 data[i++] = (byte) val;
1470                 val = val >>> Byte.SIZE;
1471             }
1472         }
1473         if (i < len) {
1474             long val = rng.nextLong();
1475             for (; i < len; i++) {
1476                 data[i] = (byte) val;
1477                 val = val >>> Byte.SIZE;
1478             }
1479         }
1480     }
1481 
1482     private static boolean isWindows0() {
1483         boolean windows = "windows".equals(NORMALIZED_OS);
1484         if (windows) {
1485             logger.debug("Platform: Windows");
1486         }
1487         return windows;
1488     }
1489 
1490     private static boolean isOsx0() {
1491         boolean osx = "osx".equals(NORMALIZED_OS);
1492         if (osx) {
1493             logger.debug("Platform: MacOS");
1494         }
1495         return osx;
1496     }
1497 
1498     private static boolean maybeSuperUser0() {
1499         String username = SystemPropertyUtil.get("user.name");
1500         if (isWindows()) {
1501             return "Administrator".equals(username);
1502         }
1503         // Check for root and toor as some BSDs have a toor user that is basically the same as root.
1504         return "root".equals(username) || "toor".equals(username);
1505     }
1506 
1507     private static Throwable unsafeUnavailabilityCause0() {
1508         if (isAndroid()) {
1509             logger.debug("sun.misc.Unsafe: unavailable (Android)");
1510             return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (Android)");
1511         }
1512 
1513         if (isIkvmDotNet()) {
1514             logger.debug("sun.misc.Unsafe: unavailable (IKVM.NET)");
1515             return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (IKVM.NET)");
1516         }
1517 
1518         Throwable cause = PlatformDependent0.getUnsafeUnavailabilityCause();
1519         if (cause != null) {
1520             return cause;
1521         }
1522 
1523         try {
1524             boolean hasUnsafe = PlatformDependent0.hasUnsafe();
1525             logger.debug("sun.misc.Unsafe: {}", hasUnsafe ? "available" : "unavailable");
1526             return null;
1527         } catch (Throwable t) {
1528             logger.trace("Could not determine if Unsafe is available", t);
1529             // Probably failed to initialize PlatformDependent0.
1530             return new UnsupportedOperationException("Could not determine if Unsafe is available", t);
1531         }
1532     }
1533 
1534     /**
1535      * Returns {@code true} if the running JVM is either <a href="https://developer.ibm.com/javasdk/">IBM J9</a> or
1536      * <a href="https://www.eclipse.org/openj9/">Eclipse OpenJ9</a>, {@code false} otherwise.
1537      */
1538     public static boolean isJ9Jvm() {
1539         return IS_J9_JVM;
1540     }
1541 
1542     private static boolean isJ9Jvm0() {
1543         String vmName = SystemPropertyUtil.get("java.vm.name", "").toLowerCase();
1544         return vmName.startsWith("ibm j9") || vmName.startsWith("eclipse openj9");
1545     }
1546 
1547     /**
1548      * Returns {@code true} if the running JVM is <a href="https://www.ikvm.net">IKVM.NET</a>, {@code false} otherwise.
1549      */
1550     public static boolean isIkvmDotNet() {
1551         return IS_IVKVM_DOT_NET;
1552     }
1553 
1554     private static boolean isIkvmDotNet0() {
1555         String vmName = SystemPropertyUtil.get("java.vm.name", "").toUpperCase(Locale.US);
1556         return vmName.equals("IKVM.NET");
1557     }
1558 
1559     /**
1560      * Compute an estimate of the maximum amount of direct memory available to this JVM.
1561      * <p>
1562      * The computation is not cached, so you probably want to use {@link #maxDirectMemory()} instead.
1563      * <p>
1564      * This will produce debug log output when called.
1565      *
1566      * @return The estimated max direct memory, in bytes.
1567      */
1568     @SuppressWarnings("unchecked")
1569     public static long estimateMaxDirectMemory() {
1570         long maxDirectMemory = PlatformDependent0.bitsMaxDirectMemory();
1571         if (maxDirectMemory > 0) {
1572             return maxDirectMemory;
1573         }
1574 
1575         if (!isAndroid() && !ignoreMaxDirectMemorySize()) {
1576             maxDirectMemory = RuntimeJvmArgs.parseMaxDirectMemorySize(maxDirectMemory);
1577         }
1578 
1579         if (maxDirectMemory <= 0) {
1580             maxDirectMemory = Runtime.getRuntime().maxMemory();
1581             logger.debug("maxDirectMemory: {} bytes (maybe)", maxDirectMemory);
1582         } else {
1583             logger.debug("maxDirectMemory: {} bytes", maxDirectMemory);
1584         }
1585 
1586         return maxDirectMemory;
1587     }
1588 
1589     private static boolean ignoreMaxDirectMemorySize() {
1590         return SystemPropertyUtil.getBoolean("io.netty.ignoreMaxDirectMemorySize", false);
1591     }
1592 
1593     private static File tmpdir0() {
1594         File f;
1595         try {
1596             f = toDirectory(SystemPropertyUtil.get("io.netty.tmpdir"));
1597             if (f != null) {
1598                 logger.debug("-Dio.netty.tmpdir: {}", f);
1599                 return f;
1600             }
1601 
1602             f = toDirectory(SystemPropertyUtil.get("java.io.tmpdir"));
1603             if (f != null) {
1604                 logger.debug("-Dio.netty.tmpdir: {} (java.io.tmpdir)", f);
1605                 return f;
1606             }
1607 
1608             // This shouldn't happen, but just in case ..
1609             if (isWindows()) {
1610                 f = toDirectory(System.getenv("TEMP"));
1611                 if (f != null) {
1612                     logger.debug("-Dio.netty.tmpdir: {} (%TEMP%)", f);
1613                     return f;
1614                 }
1615 
1616                 String userprofile = System.getenv("USERPROFILE");
1617                 if (userprofile != null) {
1618                     f = toDirectory(userprofile + "\\AppData\\Local\\Temp");
1619                     if (f != null) {
1620                         logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\AppData\\Local\\Temp)", f);
1621                         return f;
1622                     }
1623 
1624                     f = toDirectory(userprofile + "\\Local Settings\\Temp");
1625                     if (f != null) {
1626                         logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\Local Settings\\Temp)", f);
1627                         return f;
1628                     }
1629                 }
1630             } else {
1631                 f = toDirectory(System.getenv("TMPDIR"));
1632                 if (f != null) {
1633                     logger.debug("-Dio.netty.tmpdir: {} ($TMPDIR)", f);
1634                     return f;
1635                 }
1636             }
1637         } catch (Throwable ignored) {
1638             // Environment variable inaccessible
1639         }
1640 
1641         // Last resort.
1642         if (isWindows()) {
1643             f = new File("C:\\Windows\\Temp");
1644         } else {
1645             f = new File("/tmp");
1646         }
1647 
1648         logger.warn("Failed to get the temporary directory; falling back to: {}", f);
1649         return f;
1650     }
1651 
1652     @SuppressWarnings("ResultOfMethodCallIgnored")
1653     private static File toDirectory(String path) {
1654         if (path == null) {
1655             return null;
1656         }
1657 
1658         File f = new File(path);
1659         f.mkdirs();
1660 
1661         if (!f.isDirectory()) {
1662             return null;
1663         }
1664 
1665         try {
1666             return f.getAbsoluteFile();
1667         } catch (Exception ignored) {
1668             return f;
1669         }
1670     }
1671 
1672     private static int bitMode0() {
1673         // Check user-specified bit mode first.
1674         int bitMode = SystemPropertyUtil.getInt("io.netty.bitMode", 0);
1675         if (bitMode > 0) {
1676             logger.debug("-Dio.netty.bitMode: {}", bitMode);
1677             return bitMode;
1678         }
1679 
1680         // And then the vendor specific ones which is probably most reliable.
1681         bitMode = SystemPropertyUtil.getInt("sun.arch.data.model", 0);
1682         if (bitMode > 0) {
1683             logger.debug("-Dio.netty.bitMode: {} (sun.arch.data.model)", bitMode);
1684             return bitMode;
1685         }
1686         bitMode = SystemPropertyUtil.getInt("com.ibm.vm.bitmode", 0);
1687         if (bitMode > 0) {
1688             logger.debug("-Dio.netty.bitMode: {} (com.ibm.vm.bitmode)", bitMode);
1689             return bitMode;
1690         }
1691 
1692         // os.arch also gives us a good hint.
1693         String arch = SystemPropertyUtil.get("os.arch", "").toLowerCase(Locale.US).trim();
1694         if ("amd64".equals(arch) || "x86_64".equals(arch)) {
1695             bitMode = 64;
1696         } else if ("i386".equals(arch) || "i486".equals(arch) || "i586".equals(arch) || "i686".equals(arch)) {
1697             bitMode = 32;
1698         }
1699 
1700         if (bitMode > 0) {
1701             logger.debug("-Dio.netty.bitMode: {} (os.arch: {})", bitMode, arch);
1702         }
1703 
1704         // Last resort: guess from VM name and then fall back to most common 64-bit mode.
1705         String vm = SystemPropertyUtil.get("java.vm.name", "").toLowerCase(Locale.US);
1706         Pattern bitPattern = Pattern.compile("([1-9][0-9]+)-?bit");
1707         Matcher m = bitPattern.matcher(vm);
1708         if (m.find()) {
1709             return Integer.parseInt(m.group(1));
1710         } else {
1711             return 64;
1712         }
1713     }
1714 
1715     private static int addressSize0() {
1716         if (!hasUnsafe()) {
1717             return -1;
1718         }
1719         return PlatformDependent0.addressSize();
1720     }
1721 
1722     private static long byteArrayBaseOffset0() {
1723         if (!hasUnsafe()) {
1724             return -1;
1725         }
1726         return PlatformDependent0.byteArrayBaseOffset();
1727     }
1728 
1729     private static boolean equalsSafe(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
1730         final int end = startPos1 + length;
1731         for (; startPos1 < end; ++startPos1, ++startPos2) {
1732             if (bytes1[startPos1] != bytes2[startPos2]) {
1733                 return false;
1734             }
1735         }
1736         return true;
1737     }
1738 
1739     private static boolean isZeroSafe(byte[] bytes, int startPos, int length) {
1740         final int end = startPos + length;
1741         for (; startPos < end; ++startPos) {
1742             if (bytes[startPos] != 0) {
1743                 return false;
1744             }
1745         }
1746         return true;
1747     }
1748 
1749     /**
1750      * Package private for testing purposes only!
1751      */
1752     static int hashCodeAsciiSafe(byte[] bytes, int startPos, int length) {
1753         int hash = HASH_CODE_ASCII_SEED;
1754         final int remainingBytes = length & 7;
1755         final int end = startPos + remainingBytes;
1756         for (int i = startPos - 8 + length; i >= end; i -= 8) {
1757             hash = PlatformDependent0.hashCodeAsciiCompute(getLongSafe(bytes, i), hash);
1758         }
1759         switch(remainingBytes) {
1760         case 7:
1761             return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
1762                           * HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1)))
1763                           * HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 3));
1764         case 6:
1765             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos)))
1766                          * HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 2));
1767         case 5:
1768             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
1769                          * HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 1));
1770         case 4:
1771             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos));
1772         case 3:
1773             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
1774                          * HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1));
1775         case 2:
1776             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos));
1777         case 1:
1778             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]);
1779         default:
1780             return hash;
1781         }
1782     }
1783 
1784     public static String normalizedArch() {
1785         return NORMALIZED_ARCH;
1786     }
1787 
1788     public static String normalizedOs() {
1789         return NORMALIZED_OS;
1790     }
1791 
1792     public static Set<String> normalizedLinuxClassifiers() {
1793         return LINUX_OS_CLASSIFIERS;
1794     }
1795 
1796     public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
1797         if (directory == null) {
1798             return Files.createTempFile(prefix, suffix).toFile();
1799         }
1800         return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();
1801     }
1802 
1803     /**
1804      * Adds only those classifier strings to <tt>dest</tt> which are present in <tt>allowed</tt>.
1805      *
1806      * @param dest             destination set
1807      * @param maybeClassifiers potential classifiers to add
1808      */
1809     private static void addClassifier(Set<String> dest, String... maybeClassifiers) {
1810         for (String id : maybeClassifiers) {
1811             if (isAllowedClassifier(id)) {
1812                 dest.add(id);
1813             }
1814         }
1815     }
1816     // keep in sync with maven's pom.xml via os.detection.classifierWithLikes!
1817     private static boolean isAllowedClassifier(String classifier) {
1818         switch (classifier) {
1819             case "fedora":
1820             case "suse":
1821             case "arch":
1822                 return true;
1823             default:
1824                 return false;
1825         }
1826     }
1827 
1828     //replaces value.trim().replaceAll("[\"']", "") to avoid regexp overhead
1829     private static String normalizeOsReleaseVariableValue(String value) {
1830         String trimmed = value.trim();
1831         StringBuilder sb = new StringBuilder(trimmed.length());
1832         for (int i = 0; i < trimmed.length(); i++) {
1833             char c = trimmed.charAt(i);
1834             if (c != '"' && c != '\'') {
1835                 sb.append(c);
1836             }
1837         }
1838         return sb.toString();
1839     }
1840 
1841     //replaces value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "") to avoid regexp overhead
1842     private static String normalize(String value) {
1843         StringBuilder sb = new StringBuilder(value.length());
1844         for (int i = 0; i < value.length(); i++) {
1845             char c = Character.toLowerCase(value.charAt(i));
1846             if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
1847                 sb.append(c);
1848             }
1849         }
1850         return sb.toString();
1851     }
1852 
1853     private static String normalizeArch(String value) {
1854         value = normalize(value);
1855         switch (value) {
1856             case "x8664":
1857             case "amd64":
1858             case "ia32e":
1859             case "em64t":
1860             case "x64":
1861                 return "x86_64";
1862 
1863             case "x8632":
1864             case "x86":
1865             case "i386":
1866             case "i486":
1867             case "i586":
1868             case "i686":
1869             case "ia32":
1870             case "x32":
1871                 return "x86_32";
1872 
1873             case "ia64":
1874             case "itanium64":
1875                 return "itanium_64";
1876 
1877             case "sparc":
1878             case "sparc32":
1879                 return "sparc_32";
1880 
1881             case "sparcv9":
1882             case "sparc64":
1883                 return "sparc_64";
1884 
1885             case "arm":
1886             case "arm32":
1887                 return "arm_32";
1888 
1889             case "aarch64":
1890                 return "aarch_64";
1891 
1892             case "riscv64":
1893                 return "riscv64";
1894 
1895             case "ppc":
1896             case "ppc32":
1897                 return "ppc_32";
1898 
1899             case "ppc64":
1900                 return "ppc_64";
1901 
1902             case "ppc64le":
1903                 return "ppcle_64";
1904 
1905             case "s390":
1906                 return "s390_32";
1907 
1908             case "s390x":
1909                 return "s390_64";
1910 
1911             case "loongarch64":
1912                 return "loongarch_64";
1913 
1914             default:
1915                 return "unknown";
1916         }
1917     }
1918 
1919     private static String normalizeOs(String value) {
1920         value = normalize(value);
1921         if (value.startsWith("aix")) {
1922             return "aix";
1923         }
1924         if (value.startsWith("hpux")) {
1925             return "hpux";
1926         }
1927         if (value.startsWith("os400")) {
1928             // Avoid the names such as os4000
1929             if (value.length() <= 5 || !Character.isDigit(value.charAt(5))) {
1930                 return "os400";
1931             }
1932         }
1933         if (value.startsWith("linux")) {
1934             return "linux";
1935         }
1936         if (value.startsWith("macosx") || value.startsWith("osx") || value.startsWith("darwin")) {
1937             return "osx";
1938         }
1939         if (value.startsWith("freebsd")) {
1940             return "freebsd";
1941         }
1942         if (value.startsWith("openbsd")) {
1943             return "openbsd";
1944         }
1945         if (value.startsWith("netbsd")) {
1946             return "netbsd";
1947         }
1948         if (value.startsWith("solaris") || value.startsWith("sunos")) {
1949             return "sunos";
1950         }
1951         if (value.startsWith("windows")) {
1952             return "windows";
1953         }
1954 
1955         return "unknown";
1956     }
1957 
1958     /**
1959      * Check if JFR events are supported on this platform.
1960      */
1961     public static boolean isJfrEnabled() {
1962         return JFR;
1963     }
1964 
1965     private PlatformDependent() {
1966         // only static method supported
1967     }
1968 }