All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.questdb.std.Unsafe Maven / Gradle / Ivy

The newest version!
/*******************************************************************************
 *     ___                  _   ____  ____
 *    / _ \ _   _  ___  ___| |_|  _ \| __ )
 *   | | | | | | |/ _ \/ __| __| | | |  _ \
 *   | |_| | |_| |  __/\__ \ |_| |_| | |_) |
 *    \__\_\\__,_|\___||___/\__|____/|____/
 *
 *  Copyright (c) 2014-2019 Appsicle
 *  Copyright (c) 2019-2020 QuestDB
 *
 *  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 io.questdb.std;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicLong;

public final class Unsafe {
    public static final long INT_OFFSET;
    public static final long INT_SCALE;
    public static final long LONG_OFFSET;
    public static final long LONG_SCALE;
    static final AtomicLong MEM_USED = new AtomicLong(0);
    private static final sun.misc.Unsafe UNSAFE;
    private static final AtomicLong MALLOC_COUNT = new AtomicLong(0);
    private static final AtomicLong FREE_COUNT = new AtomicLong(0);
    //JCP! if jdk.version!=8
//JCP>     private static final long OVERRIDE;
//JCP>     private static final Method implAddExports;
    //JCP! endif

    static {
        try {
            Field theUnsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            UNSAFE = (sun.misc.Unsafe) theUnsafe.get(null);

            INT_OFFSET = Unsafe.getUnsafe().arrayBaseOffset(int[].class);
            INT_SCALE = msb(Unsafe.getUnsafe().arrayIndexScale(int[].class));

            LONG_OFFSET = Unsafe.getUnsafe().arrayBaseOffset(long[].class);
            LONG_SCALE = msb(Unsafe.getUnsafe().arrayIndexScale(long[].class));
            //JCP! if jdk.version!=8
//JCP>             OVERRIDE = AccessibleObject_override_fieldOffset();
//JCP>             implAddExports = Module.class.getDeclaredMethod("implAddExports", String.class, Module.class);
            //JCP! endif
        } catch (ReflectiveOperationException e) {
            throw new ExceptionInInitializerError(e);
        }
        //JCP! if jdk.version!=8
//JCP>         makeAccessible(implAddExports);
        //JCP! endif
    }

    //JCP! if jdk.version!=8
//JCP>     private static long AccessibleObject_override_fieldOffset() {
//JCP>         if (isJava8Or11()) {
//JCP>             return getFieldOffset(AccessibleObject.class, "override");
//JCP>         }
//JCP>         // From Java 12 onwards, AccessibleObject#override is protected and cannot be accessed reflectively.
//JCP>         boolean is32BitJVM = is32BitJVM();
//JCP>         if (is32BitJVM) {
//JCP>             return 8L;
//JCP>         }
//JCP>         if (getOrdinaryObjectPointersCompressionStatus(is32BitJVM)) {
//JCP>             return 12L;
//JCP>         }
//JCP>         return 16L;
//JCP>     }
//JCP> 
//JCP>     private static boolean isJava8Or11() {
//JCP>         String javaVersion = System.getProperty("java.version");
//JCP>         return javaVersion.startsWith("11") || javaVersion.startsWith("1.8");
//JCP>     }
//JCP> 
//JCP>     private static boolean is32BitJVM() {
//JCP>         String sunArchDataModel = System.getProperty("sun.arch.data.model");
//JCP>         return sunArchDataModel.equals("32");
//JCP>     }
//JCP> 
//JCP>     private static boolean getOrdinaryObjectPointersCompressionStatus(boolean is32BitJVM) {
//JCP>         class Probe {
//JCP>             boolean probe() {
//JCP>                 long offset = getFieldOffset(Probe.class, "intField");
//JCP>                 if (offset == 8L) {
//JCP>                     assert is32BitJVM;
//JCP>                     return false;
//JCP>                 }
//JCP>                 if (offset == 12L) {
//JCP>                     return true;
//JCP>                 }
//JCP>                 if (offset == 16L) {
//JCP>                     return false;
//JCP>                 }
//JCP>                 throw new AssertionError(offset);
//JCP>             }
//JCP>         }
//JCP>         return new Probe().probe();
//JCP>     }
    //JCP! endif

    private Unsafe() {
    }

    public static long arrayGetVolatile(long[] array, int index) {
        assert index > -1 && index < array.length;
        return Unsafe.getUnsafe().getLongVolatile(array, LONG_OFFSET + ((long) index << LONG_SCALE));
    }

    public static void arrayPutOrdered(long[] array, int index, long value) {
        assert index > -1 && index < array.length;
        Unsafe.getUnsafe().putOrderedLong(array, LONG_OFFSET + ((long) index << LONG_SCALE), value);
    }

    public static long calloc(long size) {
        long ptr = malloc(size);
        Vect.memset(ptr, size, 0);
        return ptr;
    }

    public static boolean cas(Object o, long offset, long expected, long value) {
        return UNSAFE.compareAndSwapLong(o, offset, expected, value);
    }

    public static boolean cas(Object o, long offset, int expected, int value) {
        return UNSAFE.compareAndSwapInt(o, offset, expected, value);
    }

    public static boolean cas(long[] array, int index, long expected, long value) {
        assert index > -1 && index < array.length;
        return Unsafe.cas(array, Unsafe.LONG_OFFSET + (((long) index) << Unsafe.LONG_SCALE), expected, value);
    }

    public static void free(long ptr, long size) {
        getUnsafe().freeMemory(ptr);
        FREE_COUNT.incrementAndGet();
        recordMemAlloc(-size);
    }

    public static boolean getBool(long address) {
        return UNSAFE.getByte(address) == 1;
    }

    public static long getFieldOffset(Class clazz, String name) {
        try {
            return UNSAFE.objectFieldOffset(clazz.getDeclaredField(name));
        } catch (NoSuchFieldException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static long getFreeCount() {
        return FREE_COUNT.get();
    }

    public static long getMallocCount() {
        return MALLOC_COUNT.get();
    }

    public static long getMemUsed() {
        return MEM_USED.get();
    }

    public static sun.misc.Unsafe getUnsafe() {
        return UNSAFE;
    }

    public static long malloc(long size) {
        long ptr = getUnsafe().allocateMemory(size);
        recordMemAlloc(size);
        MALLOC_COUNT.incrementAndGet();
        return ptr;
    }

    public static long realloc(long address, long oldSize, long newSize) {
        long ptr = getUnsafe().reallocateMemory(address, newSize);
        recordMemAlloc(-oldSize + newSize);
        return ptr;
    }

    public static void recordMemAlloc(long size) {
        MEM_USED.addAndGet(size);
    }

    private static int msb(int value) {
        return 31 - Integer.numberOfLeadingZeros(value);
    }

    //JCP! if jdk.version!=8
//JCP>     /**
//JCP>      * Equivalent to {@link AccessibleObject#setAccessible(boolean) AccessibleObject.setAccessible(true)}, except that
//JCP>      * it does not produce an illegal access error or warning.
//JCP>      */
//JCP>     public static void makeAccessible(AccessibleObject accessibleObject) {
//JCP>         UNSAFE.putBooleanVolatile(accessibleObject, OVERRIDE, true);
//JCP>     }
//JCP> 
//JCP>     public static void addExports(Module from, Module to, String packageName) {
//JCP>         try {
//JCP>             implAddExports.invoke(from, packageName, to);
//JCP>         } catch (ReflectiveOperationException e) {
//JCP>             e.printStackTrace();
//JCP>         }
//JCP>     }
//JCP> 
//JCP>     public static final Module JAVA_BASE_MODULE = System.class.getModule();
    //JCP! endif
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy