I use an integer as counter. The integer will only be increased, and surely more than one thread will increase it at the same time. The value of this counter is read at the end of program execution when no other thread will try to access its value.
I assume that I don't have to use a lock or any kind of synchronization for this kind of increment-only counter. Is this right? I code in Java if that makes any difference.
The need for synchronization originates when processes need to execute concurrently. The main purpose of synchronization is the sharing of resources without interference using mutual exclusion. The other purpose is the coordination of the process interactions in an operating system.
We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource. If an Object is shared by multiple threads then there is need of synchronization in order to avoid the Object's state to be getting corrupted. Synchronization is needed when Object is mutable.
If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
If you just used an int
or long
variable then you would need synchronization - incrementing involves read / increment-locally / write, which is far from an atomic operation. (Even if the variable is volatile
to avoid memory model concerns of staleness, you'd still have three distinct operations, with the possibility of being pre-empted between any pair of them.)
Fortunately Java provides AtomicInteger
and AtomicLong
which can be used without any synchronization:
private final AtomicLong counter = new AtomicLong(); ... counter.incrementAndGet(); // No need for synchronization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With