Can two instances be created at the same time?

View of the follow-up question Why can't Java constructors synchronize? : if the constructor of the object cannot be synchronized, does this mean that it is impossible to create two instances literally at the same time? For instance:

public class OutgoingMessage { public OutgoingMessage() { this.creationTime = new Date(); } Date creationTime; } 

Can creationDate.getTime() return a different value? I know the basics of multitasking / multithreading, but what about multiple processor cores? In this case, the operating system does not need to switch contexts, or am I wrong here?

+5
source share
2 answers

If the constructor of the object cannot be synchronized, does this mean that it is impossible to create two instances literally at the same time?

Not. Like the answers in another question, the constructor cannot be synchronized simply because nothing exists to synchronize before the constructor is called. You can do something like this:

 public OutgoingMessage(){ synchronized(this){ //synchronized constructor } } 

But then the question arises: how would two threads access the same constructor of the same instance at the same time? They could not, by definition, how designers work. That is why you cannot synchronize the constructor because it does not make any sense.

This is not saying that two instances of a class cannot be created at the same time.

+7
source

If you want to make sure that the code block inside your constructor is never executed by more than one thread at a time, you can synchronize it with the class, for example ...

 public class MyClass { public MyClass() { synchronized(MyClass.class) { // Thread unsafe code here! } } } 

You do not need to use "MyClass.class", if you do not want this, you may have a "LOCK" object, for example ...

 public class MyClass { private static final Object LOCK = new Object(); public MyClass() { synchronized(LOCK) { // Thread unsafe code here! } } } 
+1
source

All Articles