Synchronized Collections


As I hinted earlier, the Server class contains a flaw with respect to the declaration of the queue as a LinkedList.

 public class Server extends Thread {    private List<Search> queue = new LinkedList<Search>();  // flaw! 

When you work with the Java 2 Collection Class Framework with classes such as ArrayList, LinkedList, and HashMap, you should be cognizant of the fact that they are not thread-safethe methods in these classes are not synchronized. The older collection classes, Vector and Hashtable, are synchronized by default. However, I recommend you do not use them if you need thread-safe collections.

Instead, you can use utility methods in the class java.util.Collections to enclose a collection instance in what is known as a synchronization wrapper. The synchronization wrapper obtains locks where necessary on the target collection and delegates all messages off to the collection for normal processing. Modify the Server class to wrap the queue reference in a synchronized list:

 public class Server extends Thread {    private List<Search> queue =       Collections.synchronizedList(new LinkedList<Search>());    // ...    public void run() {       while (true) {          if (!queue.isEmpty())             execute(queue.remove(0));          Thread.yield();       }    }    public void add(Search search) throws Exception {       queue.add(search);    }    // ... } 

Adding the synchronization wrapper doesn't require you to change any code that uses the queue reference.

Using a bit of analysis, it doesn't seem possible for there to be a synchronization problem with respect to the queue. The add method inserts to the end of the list; the run loop removes from the beginning of the queue only if the queue is not empty. There are no other methods that operate on the queue. However, there is a slim possibility that portions of the add and remove operations will execute at the same time. This concurrency could corrupt the integrity of the LinkedList instance. Using the synchronization wrappers will eliminate the defect.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net