1. public class Test42 {
    2. public static void main(String[] args) {
    3. Account.demo(new MyAtomicInteger(10000));
    4. }
    5. }
    6. class MyAtomicInteger implements Account {
    7. private volatile int value;
    8. private static final long valueOffset;
    9. private static final Unsafe UNSAFE;
    10. static {
    11. UNSAFE = UnsafeAccessor.getUnsafe();
    12. try {
    13. valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
    14. } catch (NoSuchFieldException e) {
    15. e.printStackTrace();
    16. throw new RuntimeException(e);
    17. }
    18. }
    19. public int getValue() {
    20. return value;
    21. }
    22. public void decrement(int amount) {
    23. while (true) {
    24. int prev = this.value;
    25. int next = prev - amount;
    26. if (UNSAFE.compareAndSwapInt(this, valueOffset, prev, next)) {
    27. break;
    28. }
    29. }
    30. }
    31. public MyAtomicInteger(int value) {
    32. this.value = value;
    33. }
    34. @Override
    35. public Integer getBalance() {
    36. return getValue();
    37. }
    38. @Override
    39. public void withdraw(Integer amount) {
    40. decrement(amount);
    41. }
    42. }
    1. public class UnsafeAccessor {
    2. private static final Unsafe unsafe;
    3. static {
    4. try {
    5. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
    6. theUnsafe.setAccessible(true);
    7. unsafe = (Unsafe) theUnsafe.get(null);
    8. } catch (NoSuchFieldException | IllegalAccessException e) {
    9. throw new Error(e);
    10. }
    11. }
    12. public static Unsafe getUnsafe() {
    13. return unsafe;
    14. }
    15. }