Synchronization

Java has the legacy of the classic collections (Hashtable, Vector, and so forth) and the new collections that were introduced in Java 1.2 (HashMap, ArrayList, and so forth). Although some implementation differences exist, the main change was that none of the methods in the new collections are synchronized, but the classic collections are all thread-safe.

.NET has a different approach to thread-safe collections. All of the concrete classes contained in the System.Collections namespace are concurrently safe for multiple readers and a single writer. Multiple concurrent writers will cause problems.

A synchronized (thread-safe) implementation of a concrete collection can be obtained by calling the Synchronized method, which returns a wrapped version of the collection, just like calling java.util.Collections.synchronizedCollection. This wrapped version is thread safe and can be used by concurrent writers.

In addition, the ICollection interface provides a method to determine whether a collection is synchronized, and it provides an object that can be used for locking when writing thread-safe wrappers or using monitors.

More Info

See Chapter 13, for more information about synchronization in .NET.

Here’s an example:

Hashtable x_unsafe = new Hashtable();
Console.WriteLine("Sync state: " + x_unsafe.IsSynchronized);
Hashtable x_safe = Hashtable.Synchronized(x_unsafe);
Console.WriteLine("Sync state: " + x_safe.IsSynchronized);

The result of these statements is shown below:

Sync state: False
Sync state: True

Even though it’s possible to generate a thread-safe collection, enumerators are still troublesome. .NET enumerators are backed by the underlying collection, and any changes to the elements can cause problems. .NET takes the approach—in common with Java—of throwing an exception if the elements are changed during the life of an enumerator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset