gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Promotional Golf
Data Center Solutions
Domain registration
Home Improvement
Corporate Awards
KVM Switch over IP
Promote Your Website
Shop Online
Disney World Tickets
Memory Upgrades
Desktop Computers
Hurricane Shutters
Boat Donations
Best Price

 


Install What You Need with Windows Server 2008
Windows Server 2008 is Microsofts most full-featured server operating system yet, so it's ironic that one of its most exciting new features is an install option that cuts out most of the other features. Paul Rubens explores why a Server Core installation makes a great deal of sense in many instances. »

 
Identify Hardware and Software That Meet Microsoft Standards
The "Certified for Windows. Server 2008" logo identifies hardware and software solutions that meet Microsoft standards for compatibility and best practices with the Windows Server 2008 operating system. »

 
Windows Server Catalog: Certified Hardware Devices
Search the Windows Server 2008 catalog to find solutions to deploy with confidence. »

 
Windows Server Catalog: Certfied Servers
Search the Windows Server 2008 catalog to find servers you can deploy with confidence. »

 
Download the Windows Server 2008 Trial
With Windows Server 2008 you can develop, deliver, and manage rich user experiences and applications, provide a secure network infrastructure, and increase technological efficiency and value within your organization. »
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Simple Thread Control With Java's CountDownLatch
By Jeff Langr

Go to page: 1  2  Next  

The CountDownLatch is a simplified mechanism that allows waiting on a fixed number of threads to complete. It was introduced as part of the Java 5 concurrency API as one of a number of constructs designed to make multithreading code simpler and safer.

I test drove the development of a LineCounter class, as an example class to be used in the context of a multithreaded server. The purpose of this class is to calculate the number of source lines within a file. It's reasonably trivial code. The tests are shown in Listing 1; the source for LineCounter is in Listing 2. LineCounter supports threading via implementing the Runnable interface, but most of the tests have nothing to do with threading. They instead directly interact with the run method.

Listing 1: LineCounterTest.

import static org.junit.Assert.*;
import java.io.*;
import org.junit.*;

public class LineCounterTest {
   private BufferedReader reader;

   @Test
   public void returns0WhenEmpty() {
      write("");
      assertEquals(0, count());
   }

   @Test
   public void returns1WhenOneLine() {
      write("a");
      assertEquals(1, count());
   }

   @Test
   public void returns2WhenTwoLines() {
      write("a\na");
      assertEquals(2, count());
   }

   @Test
   public void returnsNForNLines() {
      write("a\nb\nc");
      assertEquals(3, count());
   }

   @Test
   public void countsMultipleEmptyLines() {
      write("a\nb\n\nc");
      assertEquals(4, count());
   }

   @Test
   public void handlesEndOfLineAsLastCharacter() {
      write("a\n");
      assertEquals(1, count());
   }

   @Test
   public void resetsCountOnException() {
      reader = new BufferedReader(new StringReader(" ") {
      }) {
         @Override
         public String readLine() throws IOException {
            throw new IOException();
         }
      };
      assertEquals(LineCounter.NOT_CALCULATED, count());
   }

   private void write(String contents) {
      reader = new BufferedReader(new StringReader(contents));
   }

   private int count() {
      LineCounter counter = new LineCounter(reader);
      counter.run();
      return counter.getCount();
   }

   @Test
   public void supportsFiles() throws IOException {
      File temp = File.createTempFile("LineCountTest", ".txt");
      BufferedWriter writer = null;
      try {
         writer = new BufferedWriter(new FileWriter(temp));
         writeLine(writer, "a");
         writeLine(writer, "b");
         writer.close();
         LineCounter counter = new LineCounter(temp);
         counter.run();
         assertEquals(2, counter.getCount());
      }
      finally {
         writer.close();
         temp.delete(); // risky!
      }
   }

   @Test(expected = FileNotFoundException.class)
   public void failsConstructionOnFileNotFound()
      throws FileNotFoundException {
      File unlikelyFile = new File("zzzzznotexisting");
      assertFalse(unlikelyFile.exists());
      new LineCounter(unlikelyFile);
   }

   @Test
   public void supportsMultithreading()
      throws InterruptedException {
      write("a\nb\nc");
      LineCounter counter = new LineCounter(reader);
      Thread thread = new Thread(counter);
      thread.start();
      thread.join();
      assertEquals(3, counter.getCount());
   }

   private void writeLine(BufferedWriter writer, String text)
      throws IOException {
      writer.write(text);
      writer.newLine();
   }
}

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Java Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Whitepaper: XML Processing in Applications--Take the Next Step
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Data Sheet: IBM Information Server Blade



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES