-5
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?

Flory Li
  • 167
  • 7

1 Answers1

2

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • interesting, why are they using an int instead of boolean? – mre Jul 05 '17 at 11:53
  • 2
    @mre [JVMS](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.3.4): "Although the Java Virtual Machine defines a boolean type, it only provides very limited support for it. There are no Java Virtual Machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java Virtual Machine int data type." – Andy Turner Jul 05 '17 at 11:56
  • 1
    And the actual set operations are implemented internally using `Unsafe.compareAndSetInt(...)`, for which no equivalent `boolean` method exists. – Andy Turner Jul 05 '17 at 16:28