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 Pens
Dental Insurance
Phone Cards
Online Shopping
Condos For Sale
Logo Design
Shop Online
Memory
Prepaid Phone Card
Imprinted Promotions
Memory Upgrades
Domain registration
Career Education
GPS

 

Search
The Business Internet


  Generate Revenue Through IT Using Business Service Management
Sponsored by HP
Making sure that your business applications are available to their end users is an important part of running your business smoothly. Business operations have evolved to where IT must now broaden its focus to help the company attract, retain and grow customer relationships and increase customer satisfaction. Business service management (BSM) helps lay the foundation by managing services in dynamic support of business requirements. »
 
  Managing the Modern Network
Sponsored by HP
Networks are more than vehicles to transport e-mail and Web pages. In a global economy where information crosses the globe in an instant, and where Web-based applications power business, it's more important than ever to ensure your network is safe from threats and optimized to deliver the data your business needs. »
 
  Storage Networking 2, Configuration and Planning
Sponsored by HP
In Part 1, we discussed storage area networks (SANs) and fibre channel. In Part 2, delve into best practices and cover the general concepts you must know before configuring SAN-attached storage. The most critical, sometimes tedious, part of setting up a SAN is configuring each individual disk array. This guide examines configurations for SAN-attached servers and disk arrays, and also includes a look at the future of IP storage. »
 
  Is Your Disaster Recovery Plan Good Enough? Get Disaster Recovery Right
Sponsored by HP
Preparing for a disaster is more often than not part of the storage planning process, and without question it is one of the most difficult task, since it includes local hardware and software, networking equipment, and a test plan to ensure that you can recover from the disaster. Learn how to put your organization on the proper disaster recovery plan, now. »
 
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 -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Threads Versus The Singleton Pattern
By Rob Lybarger

Go to page: 1  2  3  Next  

Given the recent uptake in the application of the singleton design pattern, it bears noting that certain applications of this pattern might not play nicely should they be utilized in a threaded program. That is to say, there are times when your design intent is that the "singleton" concept should be applied to a user or a transaction, and not simply to the application itself. You are rather likely to encounter this very situation if you write J2EE code because each request is typically processed from its own thread. Depending on how long some JDBC operations take for your application, you might inadvertently have a singleton helper class step on itself while dealing with two (or more) requests. Although you probably could address some of these issues with the judicious use of synchronized blocks, do not overlook the utility of the ThreadLocal class. In this article, I will demonstrate the risk of not accounting for Threads when using a singleton pattern and show how simple it is to address.

ThreadLocal Overview

The java.lang.ThreadLocal class has been present in the standard J2SE API since the 1.2 release, but it hasn't received much publicity in articles. (At least not quite as much as the singleton pattern has recently, in my opinion.) To quote from the API documentation:

"This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread."

In other words, whereas an ordinary "static" variable is shared across all instances of its class everywhere throughout the application, a "static ThreadLocal" is shared across all instance of its class only within the context of a particular thread. Because ThreadLocal itself is a type (specifically, a class) and not simply a modifier, you will initialize it an object that holds the value you otherwise would have created directly. (Make use of the primitive wrapper classes as needed.) I recommend reading the more official descriptions from the standard API, but to paraphrase, the methods are:

public Object initialValue() Functionally similar to a delayed constructor for your value object that is called the first time the get() method is called. Will return null unless you override.
public void set(Object) Setter method for the value object inside the ThreadLocal.
public Object get() Getter method for the value object inside the ThreadLocal.
public void remove() Removes the value object. If get() is called again, the initialValue() method is again triggered.

Also note that ThreadLocal itself has been "genericized." This article will show such utilization. (If you are a little weak on Java generics, this lesson, part of Sun's online Java tutorial, is a good place to start.)

Modification of a factory class that naively passes out references to a singleton to instead be thread-saavy is fairly simple. But first, you should set up a demonstration to illustrate the danger of not doing so.

Problem Demonstration

The Helper Class

First, you will define a class called Helper, whose job is to maintain some notion of state, and more specifically, the progression of changes to that state:

public class Helper {

   public static final int BEGINNING=0;
   public static final int MIDDLE=1;
   public static final int END=2;
   public static final int DONE=3;

   private int state = BEGINNING;

   public void setState(int newState) {
      state = newState;
   }

   public int getState() {
      return state;
   }

   public String toString() {
      return "Helper has state "+state;
   }
}

Usage Illustration

The usage pattern for this class is that some external section of code obtains a reference to a Helper object and, depending on the Helper's state, performs some conditional operation (and then updates the Helper's state). Note that, for the immediately following example, a singleton pattern is not yet employed. (You will get to that shortly.) This is also a fairly contrived example, and as such it sleeps (briefly) to simulate effects of long-running operations:

public class Demo1 {
   public static void main(String[] args) {
      Helper helper = new Helper();
      do {
         try {
            Thread.sleep((long)(250*Math.random()));
         } catch (InterruptedException e) {
            break;
         }
         switch (helper.getState()) {
         case Helper.BEGINNING:
            System.out.println(helper);
            System.out.println("Beginning operation finished.");
            helper.setState(Helper.MIDDLE);
            break;
         case Helper.MIDDLE:
            System.out.println(helper);
            System.out.println("Middle operation finished.");
            helper.setState(Helper.END);
            break;
         case Helper.END:
            System.out.println(helper);
            System.out.println("End operation finished.");
            helper.setState(Helper.DONE);
            break;
         }
      } while (helper.getState() != Helper.DONE);
      System.out.println("Code section finished.");
   }
}

The expectation is that the output you see on the screen is:

Helper has state 0
Beginning operation finished.
Helper has state 1
Middle operation finished.
Helper has state 2
End operation finished.
Code section finished.

... and when your code (or at least everything related to the existence and usage of the Helper object) is single-threaded, this works fine. But, for some reason (related to experience or design requirements), you drag a factory-with-singleton design into the picture.

Go to page: 1  2  3  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


Enterprise Java Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Whitepaper: Embeddable Content Platform for OEM's
Intel Go Parallel Portal: Translating Multicore Power into Application Performance
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Whitepaper: XML Processing in Applications--Take the Next Step



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