Implementing your own atomic object
Atomic variables were introduced in Java version 5; they provide atomic operations on single variables. When a thread does an operation with an atomic variable, the implementation of the class includes a mechanism to check that the operation is done atomically.
In this recipe, you will learn how to extend an atomic object and implement two operations that follow the mechanisms of the atomic objects to guarantee that all the operations are done in one step.
Getting ready
The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or a different IDE, such as NetBeans, open it and create a new Java project.
How to do it...
Follow these steps to implement the example:
- Create a class named
ParkingCounter
and specify that it extends theAtomicInteger
class:
public class ParkingCounter extends AtomicInteger {
- Declare a private
int
attribute namedmaxNumber
to store the maximum number of cars admitted into the parking lot:
...