How it works...

The ParkingCounter class extends the AtomicInteger class with two atomic operations: carIn() and carOut(). The example simulates a system that controls the number of cars inside a parking lot. The parking lot can admit a number of cars, represented by the maxNumber attribute.

The carIn() operation compares the actual number of cars in the parking lot with the maximum value. If they are equal, the car can't enter the parking lot and the method returns the false value. Otherwise, it uses the following structure of the atomic operations:

  • Get the value of the atomic object in a local variable.
  • Store the new value in a different variable.
  • Use the compareAndSet() method to try and replace the old value with the new one. If this ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.