This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static synchronized

 
t capelle
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 400
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic