aspose file tools
The moose likes Threads and Synchronization and the fly likes Synchronize static variable Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Synchronize static variable" Watch "Synchronize static variable" New topic
Author

Synchronize static variable

Rams Senthiil
Greenhorn

Joined: Jan 29, 2003
Posts: 12
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

Joined: Dec 28, 2006
Posts: 893
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.


Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 370

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.


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronize static variable
 
Similar Threads
Is this thread safe? Simple question.
synchronizing on a class vs an instance of a class
Exam 9, Q24 Dan Chisholm
Synchronization on Threads in Java
Random question