Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a constructor be pre-empted?

Tags:

People also ask

Why constructor does not return any value?

Java For Testers No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.

What will happen if we give return type to constructor in java?

If we add a return type to a constructor, then it will become a method of the class. This is the way java runtime distinguish between a normal method and a constructor.

What if constructor has return type?

No, constructor does not have any return type in Java. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name.


Is it possible for a constructor to be pre-empted in C#?

For example, consider the code:

public class A
{
    public bool ready = true;

    public A()
    {
        ready = false; // Point #1
        // Other initialization stuff
        ready = true; // Point #2
    }
}

Somewhere else in the code two threads have access to a variable of type A, the first thread calls the constructor which is pre-empted at point #1. Then the second thread tests for ready and finds it to still be true therefore it does something bad.

Is this scenario possible?

More specifically:

  1. Can a constructor be pre-empted?
  2. If so, does this mean that there should be synchronization code such as lock in the constructor?
  3. Is the object being constructed only assigned to the shared variable after the constructor exits, thereby avoiding the question altogether?