Which code segment should you use?

You are writing a method that returns an ArrayList named al.
You need to ensure that changes to the ArrayList are performed in a thread-safe manner.
Which code segment should you use?

You are writing a method that returns an ArrayList named al.
You need to ensure that changes to the ArrayList are performed in a thread-safe manner.
Which code segment should you use?

A.
ArrayList al = new ArrayList();
lock (al.SyncRoot){
return al;
}

B.
ArrayList al = new ArrayList();
lock (al.SyncRoot.GetType()){
return al;
}

C.
ArrayList al = new ArrayList();
Monitor.Enter(al);
Monitor.Exit(al);
return al;

D.
ArrayList al = new ArrayList();
ArrayList sync_al = ArrayList.Synchronized(al);
return sync_al;

Explanation:
A & C the lock will be released when the method returns.
B Does not lock the arraylist but attempts to lock its type.



Leave a Reply 1

Your email address will not be published. Required fields are marked *


mr_tienvu

mr_tienvu

I agree with the answer. D