Kind of a follow up question to Why can't Java constructors be synchronized?: if an object's constructor can't be synchronized, does that mean it's impossible to create two instances at literally the same time? For instance:
public class OutgoingMessage {
public OutgoingMessage() {
this.creationTime = new Date();
}
Date creationTime;
}
Would creationDate.getTime()
always return a different value? I'm aware of the basics of multitasking/multithreading but what about multiple CPU cores? In that case the operating system doesn't have to switch contexts or am I wrong here?
One of the main characteristics of object oriented programming is the fact that you can create multiple instances of the same class. Each instance is created in a different place in the program memory and the values of instance attributes in one instance are independent from the values in other instances.
A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object.
If you just want to know wether two objects denode the same memory cell, so they are really the same, you cann use the equals operator: Object A = new Fruit("A"); Object B = new Fruit("A"); System. out. println(A == B);
if an object's constructor can't be synchronized, does that mean it's impossible to create two instances at literally the same time?
No. As the answers in the other question state, a constructor can't be synchronized simply because nothing exists to synchronize on before the constructor is called. You could do something like this:
public OutgoingMessage(){
synchronized(this){
//synchronized constructor
}
}
But then the question becomes: how on earth would two threads access the same constructor of the same instance at the same time? They couldn't, by the very definition of how constructors work. That's why you can't synchronize on a constructor- because it doesn't make any sense.
That is not saying that two instances of a class can't be constructed at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With