This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Threads - static variable and static/non static method execution Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Threads - static variable and static/non static method execution" Watch "Threads - static variable and static/non static method execution" New topic
Author

Threads - static variable and static/non static method execution

Kaur Manpreet
Ranch Hand

Joined: Feb 14, 2012
Posts: 30

Hi All,

The question is regaring the following code snippet:


This code compiles and executes successfully.
Doubt: Please advise why is it that the output PQPQ would never be part of the result.

My Understanding: As the run method is not synchronized, I believe that there is a possibility (maybe remote one) that Line 1 is executed by both the threads simultaneously resulting in the information that static variable id is zero.
Thanks
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Kaur Manpreet wrote:
Doubt: Please advise why is it that the output PQPQ would never be part of the result.


It could be. Just because you didn't happen to see it in your testing doesn't mean it's not possible.

My Understanding: As the run method is not synchronized, I believe that there is a possibility (maybe remote one) that Line 1 is executed by both the threads simultaneously resulting in the information that static variable id is zero.


Yes, that's correct. And, even if they don't execute it at the same time, since id is not volatile and not all access to it is synchronized, it's possible for each thread to have its own local copy of id, and one thread not to see the other's write that sets it to 0.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Threads - static variable and static/non static method execution
 
Similar Threads
Suspected Error in Answer for a Thread Question in "Practice Exams Java"
Doubt regarding Threads found in K&B OCP Java 6 Practice Exams Book
Please explain this problem from k&b
Threads question from K&B Practice Exams
Suspected Error in Answer for a Thread Question in Practice Exams Java