O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required