Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two instances be created at the same time?

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?

like image 818
Miro Kropacek Avatar asked Apr 23 '15 16:04

Miro Kropacek


People also ask

Can you create multiple instances of a class?

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.

Can you instantiate more than one instance of the same class in one program?

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.

How can you tell if two objects are the same instance?

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);


1 Answers

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.

like image 89
Kevin Workman Avatar answered Sep 25 '22 02:09

Kevin Workman