• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Restrict access to static variable from non static synchronized and static synchronized method

 
Hariharan Thirumeni
Greenhorn
Posts: 3
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2 methods, one is static and another one is non static and both are synchronized. So both the methods can execute concurrently by two threads as one thread can use object lock to enter non static syn method and another one can use Class lock to enter static synchronized method. Suppose if i have a static variable, then both the thread can access this variable at the same time. So there will be a race condition. How can we restrict the access to this?


Thanks in advance
 
Stephan van Hulst
Bartender
Posts: 6316
77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the field contains an object reference, you can let both methods lock on it explicitly. If it contains a primitive, you can just make the field volatile.
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use an explicit lock for this object:
 
Stephan van Hulst
Bartender
Posts: 6316
77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to CodeRanch!
 
Hariharan Thirumeni
Greenhorn
Posts: 3
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks stephan.

Just assume that the static variable is an primitive int. Below is the program demonstrates the issue.
Sometimes the output is

Method1:Thread Name :Thread-0 Counter:1
Method2:Thread Name :Thread-0 Counter:3
Method1:Thread Name :Thread-1 Counter:3
Method2:Thread Name :Thread-1 Counter:4


I want the counter should increase sequentially as the variable is static and only one copy of it get stored per JVM....The output clearly shows that there is an conflict in accessing the variable. Volatile doesnt work as it is only for instance variables not for static.


 
Stephan van Hulst
Bartender
Posts: 6316
77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
volatile works fine with static, but I forgot it doesn't do much in the way of race conditions. Yes, the only way is to use a common lock:
Which reminds me. Rob Spoor's solutions shouldn't work in general, because subclasses may return a different class object when getClass() is being called. Static methods can't even use the getClass() method. Always use class literals (Classname.class).
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're very right of course.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic