Recently I found when I use a boolean value in multiple threads, it is not thread-safe enough. For example, in one thread you are writing values for a boolean value, in another thread you are checking the boolean in order to process the thread. How does the program know the value when you check? This suitation also happens in other values not limited to boolean.

We should aviod checking and writing a value in multiple thread in the same time. Here is a simple solution I found: use java.util.concurrent.atomic package. Atomic Collections support lock-free thread-safe programming on single variables.

We can use classes in atomic packages like:

  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
  • AtomicIntegerArray, etc.

Use atomic classes is strightforward, you can set() or get() values. For example:

1
2
3
AtomicBoolean value = new AtomicBoolean();
value.set(true);
boolean b = value.get();