Why does Class AtomicBoolean be initialized not true but false by default constractor?

1.2k views Asked by At
java source code:

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicBoolean.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}

default constructor do nothing:

public AtomicBoolean() {
}

The variable 'valueOffset' means the offset location in memory? I don't understand why it initialized to 'false' by default constructor.How can i understand this?

1

There are 1 answers

3
Andy Turner On

As no value is set in the default constructor, the initial value is the initialized value of the value field - that's an int, with no explicit value, so it has the default value of zero.

Source code:

private volatile int value;

/**
 * Creates a new {@code AtomicBoolean} with the given initial value.
 *
 * @param initialValue the initial value
 */
public AtomicBoolean(boolean initialValue) {
    value = initialValue ? 1 : 0;
}

/**
 * Creates a new {@code AtomicBoolean} with initial value {@code false}.
 */
public AtomicBoolean() {
}

Setting it to false is consistent with an uninitialized boolean field.