April 20, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Working With Design Patterns: Odds and Ends, Page 4

  • September 18, 2008
  • By Jeff Langr
  • Send Email »
  • More Articles »

A quick explanation of the code in Listing 4: ThreadPool initiates a number of WorkerThread objects, and also creates a master queue to hold on to incoming requests. It then accepts new Runnable "requests" using the enqueue method; these requests get added to the master queue. Each WorkerThread object waits until the queue has a request available. Once a request is available, it gets removed from the queue and executed. Once a request completes processing, the WorkerThread pool object loops back (it's in an infinite loop) to grab the next request. Use of the BlockingQueue makes the code dramatically simple!

Listing 4: The unnecessary but tiny thread pool.

import java.util.*;
import java.util.concurrent.*;

public class ThreadPool {
   private final BlockingQueue<Runnable> queue =
      new LinkedBlockingQueue<Runnable>();

   public ThreadPool(int size) {
      for (int i = 0; i < size; i++)
         new WorkerThread().start();
   }

   public void enqueue(Runnable runnable) {
      queue.add(runnable);
   }

   class WorkerThread extends Thread {
      @Override
      public void run() {
         while (true)
            nextRequest().run();
      }

      private Runnable nextRequest() {
         while (true)
            try {
               return queue.take();
            } catch (InterruptedException e) {
            }
      }
   }
}

Utility

A utility class is simply a collection of related stateless functions. For example, when writing unit tests, I often find myself needed helper methods to assert against collection contents. Here's one such CollectionsUtil class:

import java.util.*;
import junit.framework.*;

public class CollectionsUtil {
   static final String NO_ELEMENTS = "no elements";
   static final String MORE_THAN_ONE_ELEMENT =
      "more than one element";
   public static final String EXPECTED =
      "expected element not retrieved";

   public static <T> T soleElement(Collection<T>
         collection) {
      Iterator<T> it = collection.iterator();
      Assert.assertTrue(NO_ELEMENTS, it.hasNext());
      T sole = it.next();
      Assert.assertFalse(MORE_THAN_ONE_ELEMENT, it.hasNext());
      return sole;
   }

   public static <T> void assertSoleElement(Collection<T>
      collection, Object expected) {
      Iterator<T> it = collection.iterator();
      Assert.assertTrue(NO_ELEMENTS, it.hasNext());
      T first = it.next();
      Assert.assertFalse(MORE_THAN_ONE_ELEMENT, it.hasNext());
      Assert.assertEquals(expected, first);
   }

   public static <T> boolean containsExactly(Collection<T>
      collection, T... objects) {
      if (collection.size() != objects.length)
         return false;
      for (int i = 0; i < objects.length; i++)
         if (!collection.contains(objects[i]))
            return false;
      return true;
   }
}

By definition, then, a utility class is comprised only of static methods. It is not instantiated. Access is static-side only:

@Test
public void addBranch() {
   system.addBranch(BranchTest.NAME1);
   CollectionsUtil.assertSoleElement(system.branches(),
                                     BranchTest.BRANCH1);
}

You'll note that I did not introduce a private constructor, which would enforce the inability to instantiate CollectionsUtil. If it makes you feel better, add one, but generally there's no possible harm from someone attempting to access these static methods from an instance.

References

  • [Gamma] Gamma, E., et. al. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Professional, 1995.
  • [Fowler] Fowler, Martin. Refactoring: Improving the Design of Existing Code. Addision-Wesley, 1999.

About the Author

Jeff Langr is a veteran software developer with over a quarter century of professional software development experience. He's written two books, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. Jeff contributed to Uncle Bob Martin's new book, Clean Code (Prentice Hall, August 2008). Jeff has written over 80 articles on software development, with over forty appearing at Developer.com. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him via email at jeff at langrsoft dot com.





Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel