Saturday, April 15, 2017

Java | Probably the most unused keyword in Java | The "volatile" keyword

In multithreaded application the behavior or the result of some processes might look very strange to a new programmer. (including me when i write this post)

The Problem

In multi cores computers, different Threads can be run on different cores. It make sense since you want to get the advantages of having multi cores. The problem comes when you are using primitive data types to control processes that handled by different threads. Primitive data types are stored in cache (L1) of a core in your CPU. These data are not shared between the cores. So the data that are using in one core is not equals with the data that used in other cores. This will lead to unexpected result of your program.

The Solution

Decorate your variable with a keyword "volatile" like this <code>private volatile int someInteger;</code>

No comments:

Post a Comment