DRAG DROP
You are developing an application that includes a class named Warehouse. The Warehouse
class includes a static property named Inventory- The Warehouse class is defined by the
following code segment. (Line numbers are included for reference only.)
You have the following requirements:
Initialize the _inventory field to an Inventory instance.
Initialize the _inventory field only once.
Ensure that the application code acquires a lock only when the _inventory object must be
instantiated.
You need to meet the requirements.
Which three code segments should you insert in sequence at line 09? (To answer, move the
appropriate code segments from the list of code segments to the answer area and arrange
them in the correct order.)

Check if _inventory variable is null.
Box 2:![]()
If _inventory is null we first lock it (before initializing it).
Box 3:![]()
Then we initialize the variable (if it is not already initialized, ie if it has a null value).
Answer is wrong.
Correct Answer:
1. if(_inventory == null) _inventory = new Inventory();
//if null, create an instance
2. if(_inventory != null)
3. lock(_lock)
//lock only if it is not null
1
9
Are you kidding? https://msdn.microsoft.com/en-us/library/ff650316.aspx
2
1
Nice ref to: Implementing Singleton in C#
0
0
Answer is correct
0
0
Oh man… amsami, do you understand what are locks for?
The correct answer is:
public static Inventory Inventory
{
get
{
if (_inventory == null)
{
lock (_lock)
{
if (_inventory == null) _inventory = new Inventory();
}
}
return _inventory;
}
}
this is a back-to-school example of multithread singleton approach.
first, you check if the inventory is null, if so, you lock it to avoid other threads to change it.
second, you check again for the null, as in the tiny millisecond between check for null and locking could another thread get it.
finally you create the instance and release the lock
10
0
So good explanation! ++
1
0