|
| 1 | +package com.datadoghq.profiler; |
| 2 | + |
| 3 | +import sun.misc.Unsafe; |
| 4 | +import java.lang.reflect.Field; |
| 5 | + |
| 6 | + |
| 7 | +class ActiveBitmaps { |
| 8 | + private static final Unsafe UNSAFE; |
| 9 | + static { |
| 10 | + Unsafe unsafe = null; |
| 11 | + try { |
| 12 | + Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
| 13 | + f.setAccessible(true); |
| 14 | + unsafe = (Unsafe) f.get(null); |
| 15 | + } catch (Exception ignore) { } |
| 16 | + UNSAFE = unsafe; |
| 17 | + } |
| 18 | + |
| 19 | + private static long activeCountAddr = 0; |
| 20 | + |
| 21 | + private static final ThreadLocal<Long> Address = new ThreadLocal<Long>() { |
| 22 | + @Override protected Long initialValue() { |
| 23 | + return -1L; |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + public static void initialize() { |
| 28 | + activeCountAddr = getActiveCountAddr0(); |
| 29 | + } |
| 30 | + |
| 31 | + static long getBitmask(int tid) { |
| 32 | + int tmp = (tid >> 8) & 0xff ; |
| 33 | + int bits = 0; |
| 34 | + for (int index = 0; index < 7 ; index++) { |
| 35 | + if ((tmp & 0x01) == 0x01) { |
| 36 | + bits |= 0x01; |
| 37 | + } |
| 38 | + tmp >>= 1; |
| 39 | + bits <<= 1; |
| 40 | + } |
| 41 | + return 1L << (bits & 0x3f); |
| 42 | + } |
| 43 | + |
| 44 | + static void setActive(int tid, boolean active) { |
| 45 | + long addr = Address.get(); |
| 46 | + if (addr == -1) { |
| 47 | + addr = bitmapAddressFor0(tid); |
| 48 | + Address.set(addr); |
| 49 | + } |
| 50 | + long bitmask = getBitmask(tid); |
| 51 | + long value = UNSAFE.getLong(addr); |
| 52 | + long newVal; |
| 53 | + if (active) { |
| 54 | + newVal = value | bitmask; |
| 55 | + } else { |
| 56 | + newVal = value & ~bitmask; |
| 57 | + } |
| 58 | + while (!UNSAFE.compareAndSwapLong(null, addr, value, newVal)) { |
| 59 | + value = UNSAFE.getLong(addr); |
| 60 | + newVal = active ? (value | bitmask) : (value & ~bitmask); |
| 61 | + } |
| 62 | + int delta = active ? 1 : -1; |
| 63 | + assert activeCountAddr != 0; |
| 64 | + UNSAFE.getAndAddInt(null, activeCountAddr, delta); |
| 65 | + if (isActive0(tid) != active) { |
| 66 | + throw new RuntimeException("SetActive failed"); |
| 67 | + } |
| 68 | + |
| 69 | + assert isActive0(tid) == active; |
| 70 | + } |
| 71 | + |
| 72 | + // For verification |
| 73 | + private static native boolean isActive0(int tid); |
| 74 | + |
| 75 | + // Setup bitmap and active count locations |
| 76 | + private static native long bitmapAddressFor0(int tid); |
| 77 | + private static native long getActiveCountAddr0(); |
| 78 | +} |
| 79 | + |
0 commit comments