• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Threads - static variable and static/non static method execution

 
Ranch Hand
Posts: 30
Oracle Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!