Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronize static variable  RSS feed

 
Rams Senthiil
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can any one help me to clear my doubt
Say i have a class like this

class producer extends {
private static int invoiceNo = 0;
private synchronized int getInvoiceNo(){
return invoiceNo++;
}
}
Since invoiceNo is static it's shared and it would be accssed only through synchronized method shall i assume a thread requires class level lock to execute getInvoiceNo() method. It's some thing similar to declare a method like
static synchronized int getInvoice()?
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's true static methods get a lock for the whole class.

This lock is defined within instance of the java.lang.Class and is used to protect static methods of the class.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First the code doesn't compile , extends what ??

2nd its almost certainly wrong i.e. yes the getInvoiceNo gets the wrong lock if more that one instance of your class exists, it won't implicitly get the class lock its only gets its object lock. Two objects are free to alter invoiceNo at the same time which obviously wasn't suggested change the code as suggested.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!