Reputation:
Does the code below violate intra-thread semantic?
static Integer sync;
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
@Override
public void run() {
sync = 6;
System.out.println("written thread 1");
try {
Thread.sleep(9999);
} catch (InterruptedException ex) {
Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sync);
}
};
Runnable t = new Runnable() {
@Override
public void run() {
sync = 2;
System.out.println("written thread 2");
try {
Thread.sleep(9999);
} catch (InterruptedException ex) {
Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sync);
}
};
Thread th1 = new Thread(r);
Thread th2 = new Thread(t);
th1.start();
th2.start();
}
Outcome is:
written thread 1
written thread 2
2
2 //!!!! Is intra-thread semantic violates?
JLS in 17.4 says:
[...]As previously mentioned, all threads need to obey the correct intra-thread semantics for Java programs.[...]
I thought that intra-thread semantic means that a thread will work as it was a single thread in a program. That is, the value assigned by th1
is observble for th1
only, and the similiar for th2
.
May I don't understand intra-thread semantic concept correctly?
Upvotes: 1
Views: 191
Reputation: 31053
The problem is, that you got yourself and "inter-thread" action here
An inter-thread action is an action performed by one thread that can be detected or directly influenced by another thread.
not an "intra-thread" action. Both threads share a common memory location (the variable sync
), and setting the value from one thread is an effect, that can be detected by the other. The deascription of "intra-thread" semantics says
The actions of each thread in isolation must behave as governed by the semantics of that thread, with the exception that the values seen by each read are determined by the memory model.
(emphasis mine, source)
Upvotes: 2
Reputation: 2205
Intra-thread semantics only refers to variables that are not shared between threads.
Therefore the output is consistent with the Java Memory Model (JMM).
On another note, your program is not properly synchronized because you have two threads writing to the same static variable (sync
) and therefore the program can produce both the output (6, 2) as well as (2, 2) and still fulfill the JMM.
Upvotes: 1