In our app (written in Java for Android), we have a Thread
derived class that contains an int field:
public class MyThread extends Thread {
public int myValue = 0;
public void doWork() {
while (true) {
System.out.println(myValue);
}
}
}
// On some other thread
myThread.myValue = 42;
The MyThread
class only reads from the int field, while i'd like another thread to write to it (as in the example above).
As i know, primitive types such as int in Java are read/written atomically.
Should i protect the access to this int field (using the synchronized
keyword) ?
I've read here that according to the Java memory model, updates to memory shared by a few threads may not even be seen if not explicitly communicated
Quote: Without explicit communication, you can't guarantee which writes get seen by other threads
Should i protect the access to this field or can another thread update it (atomically) without any needed modification?
What you should do is declare it as volatile
. Refer to http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html .
how are you going to update the int variable? if it's direct-modify, so setting the variable as volatile is useful.
public volatile int myValue = 0;
but the update is read-modify
so you need synchronize threads with each other.
and [this link] would be useful for understanding volatile
primitive types such as int in Java are read/written atomically.
A thread always sees the value of a variable that was written by some thread; not some random value pulled out of thin air. Unless declared as volatile
, 64-bit numeric variables (long and double) do not have out-of-thin-air safety, because the JVM is permitted to treat 64-bit value as two 32-bit fetch operations. So even though you use primitive type you should use Volatile
.
One more thing in mutithreading there are two things: 1. atomicity 2. visibility
Volatile guarantee the visibility part not the atomicity part. so if you are incrementing a variable like K++
than you should synchronize
as well else you are not guaranteeing the atomicity
part.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.