Do I need to add a lock block here if I want to be sure that instance will be created only 1 time?
if (instance==null)
{
instance = new Class();
}
Since there is only 1 instruction within the IF I’m not 100% sure. In a case like below, I’m sure I’d need it but I wanted to double check if the same applies for the code above.
if (instance==null)
{
int i = 5;
int y = 78;
instance = new Class(i, y);
}
EDIT
Yes, I assume multithreading
Yes, you need a lock in both of your two examples. Let’s number the lines to make the explanation easier:
Now, assume you have two threads, A and B. Both threads are executing this code. First, A tests
instanceat line 1, and since it’s null it takes the true path – on to line 3. Then, you get a context switch before line 3 is executed and B does the same (true on line 1 and ends up at line 3). Now both threads are inside yourifstatement body, and you’ll get two assignments toinstance.