Java: Synchronizing ints

Learn
2 min readApr 17, 2022

--

int type is as basic as it gets in Java. Java language ensures atomicity in regard to read and write operations against the int data type.

Multiple threads can act on your int variable. One thread changes the value. Another thread reads that value. Java guarantees atomicity for read/write operations against int variables.

What does that guarantee really mean? If a thread is changing a number 8 to number 7, in binary it changes from 1000 to 0111. There are 4 bits that have changed state there. Let us it changes from 1000 to 0000 to 0001 to 0011 to 0111. None of the threads are going to see any of the intermediate values from 1000 to 0111. That is the atomicity guarantee.

Synchronization

You can use the “synchronized” key word to ensure that a particular block of code is executed by only one thread at a time.

The cost is that with a multi-core processor, the piece that is synchonized cannot take the advantage of the multiple cores on the system where the program is running.

Now, given that int read/write operations are guaranteed to be atomic by the language specification, Is it required to synchronize a simple increment operation on an innocent int variable?

private static int increment() {
return ++i;
}

The reason synchronization is required is that increment is not a single operation, there are two operations here, thread reads the current value from i, and writes the value of i + 1 into the variable i.

So, one thread would have read seven and made it eight, while the second thread still sees seven and missed out on the update made by the first thread.

That is the reason synchronization is required.

private static synchronized int increment() {
return ++i;
}

--

--

Learn
Learn

Written by Learn

On a continuing learning journey..

No responses yet