Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need synchronization for an increment-only counter?

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.

like image 529
qinsoon Avatar asked Oct 04 '11 10:10

qinsoon


People also ask

Where synchronization is needed and why?

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.

Why is synchronization necessary in multithreaded programming?

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.

What is synchronization how is it achieved with examples?

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.


1 Answers

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 
like image 182
Jon Skeet Avatar answered Oct 04 '22 06:10

Jon Skeet