aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static synchronized" Watch "static synchronized" New topic
Author

static synchronized

t capelle
Greenhorn

Joined: Apr 23, 2001
Posts: 3
Given the following code, can it be guaranteed that the instances will be given id's in the order in which they are created?
class Test {

public int id;
private static int currentID = 0;

public Test() {
id = newId();
}

public static synchronized int newId() {
return ++currentID;
}
}
denish mehta
Ranch Hand

Joined: Dec 21, 2000
Posts: 135
Well in my humble opinion i think they should, isee no reason why they should'nt
I am open for any comments
Regards
Denish
Stevie Kaligis
Ranch Hand

Joined: Feb 04, 2001
Posts: 400
I think....
guaranteed that the instances will have the unique currentID: "Yes",
but guaranteed order serialization (1,2,3,4,5,etc...) : "No",
since the method is static, it can be access without creating the instance.
but if you change your code with :
class Test {
public int id;
private static int currentID = 0;
public Test() { //future,it's nice if this is also be private,
++currentID;
}
public static synchronized Test newId() { //change int with Test
return new Test(); //create an object
}
}
every instance will be given id's in the order in which they are created, even you access it through the Test.newId().
any comment are always welcome !
stevie
t capelle
Greenhorn

Joined: Apr 23, 2001
Posts: 3
I guess my question really centers on whether a constructor gets any kind of lock on the class. If not, I would say that in my example (ignoring accessing newId() from outside of the constructor), we could not guarantee that the instances are given id's in the order they are created. So now that I see my question more clearly, let me be specific: Does a constructor get the lock on a class when called?
kaushik banerjee
Ranch Hand

Joined: Mar 11, 2001
Posts: 56
Hi,
The monitor of a class is a totally different entity & is no way related to a monitor of the object of that class . Therefore there is no reason why Test() cannot call newID().Also since the constructor cannot complete untill the call to newID() returns , I feel that the IDs would be allotted serially.
What do u say?

Waiting for AJITH or JANE to finally clear up the confusion.
Regards,
Kaushik
 
wood burning stoves
 
subject: static synchronized