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
posted
0
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.
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