I was going through this tutorial and it mentioned that an "inconsistent state" will happen if we do not synchronize these 2 lines of code. I tried to reproduce this "inconsistent state" but I was not able to do so. Can you tell me exactly what is a "inconsistent state" ?
The tutorial stated, "the value of myColorInt won't match the value of myColorName".. but I did not seem to have any problem... can you explain what exactly is the problem they are trying to avoid?
The situation that is trying to be avoided is known as a race condition:
http://en.wikipedia.org/wiki/Race_condition
The result of the sequence
int myColorInt = color.getRGB(); //Statement 1
String myColorName = color.getName(); //Statement 2
depends on the timing with respect to this thread of code executing in other threads. If another thread sets the color in between these two statements, then the name stored in myColorName won't match the color stored in myColorInt. This is what the tutorial means by inconsistent state.
Synchronization is used to make certain guarantees about how mutable data is shared and accessible across threads. This block
synchronized (color) {
int myColorInt = color.getRGB();
String myColorName = color.getName();
}
uses synchronization to make sure the two statements are executed atomically; that is to say, to prevent another thread from changing the state of the color object while this thread is between the two statements (presuming that other threads are also using synchronization properly).
Concurrency and thread safety can be challenging to get correct, even for experts. Concurrency issues result in hard to diagnose, hard to reproduce, and sporadic problems. Since you're just starting out, I recommend avoiding concurrent programming for the time being if possible. Otherwise, the book Java Concurrency in Practice by Brian Goetz, et. al. is an excellent start.
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