Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Two Threads with priorities

 
Ranch Hand
Posts: 42
Postgres Database Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello guys,
I'm having an issue with 2 threads that run with different priorities. The problem is that the program prints the 2 counters, but does not stop. YThread is similar to XThread. Thanks

 
Rancher
Posts: 43027
76
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not sure if that's the problem , but you may want to declare isRunning as volatile - indicating its value can be altered in different threads.

From what I remember - you shouldn't rely on thread priorities for doing anything meaningful. Their implementation is (or used to be) very uneven and sometimes changed between JVM versions, so it is better not to rely on them. Maybe Henry will chime in on this, he'd know for sure.
 
Alexandru Gifei
Ranch Hand
Posts: 42
Postgres Database Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Declaring the flags as volatile did the job. Thanks!
 
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Alexandru Gifei wrote:Declaring the flags as volatile did the job. Thanks!



True. I guess when the count is not volatile, the 2 threads tries to do code optimization by reading/writing the variable to cache/master location. Hence the 2 thread enter race condition and will not terminate.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic