Singletons vs.
class (un)loading - JavaWorld - May
1998
Tutorial Details:
Java Tip 52: Singletons vs. class (un)loading
Java Tip 52: Singletons vs. class (un)loading
By: By John D. Mitchell and Bill Foote
Find out how Java 1.2 changes the way we load and unload classes in Java
ave you written any classes adhering to the Singleton pattern? Have you run into odd bugs where your singleton objects just seem to vanish? Are you confused about when classes can be reloaded? If you answered yes to these questions, you're reading the right article!
Coders trying to implement and test the Singleton pattern (see Resources ) in Java 1.1 often complained that their singleton classes were getting garbage collected; that is, the runtime unloaded the classes right out from under them! Fortunately, the upcoming Java 1.2 specification clarifies the rules for loading and unloading classes, making writing singletons much simpler.
This tip explores implementing singletons in Java and describes what we need to do to make them work in the various versions of Java floating around.
Singletons defined
A singleton is a class for which only one instance can exist within a program. In other words, only one, single object of that particular class can be created in a program.
Here's a simple, quick-and-dirty singleton class:
public class SimpleSingleton
{
// Create the single instance, make it available statically, and
// don't let it be redefined.
private static final SimpleSingleton instance = new SimpleSingleton();
// Allow subclasses to override the constructor, if necessary.
protected SimpleSingleton()
{
// Whatever...
}
// Accessor only.
public static SimpleSingleton getInstance()
{
return instance;
}
// Methods on the object to actually do something useful.
public void doSomething()
{
// Whatever.
}
}
All we ever need to do to actually use the various methods of the SimpleSingleton class is to access the static instance member and use it to invoke our method of choice, like this:
SimpleSingleton.getInstance().doSomething();
With such a class, we never need to create and store the SimpleSingleton instance object anywhere, or worry about passing the object reference around.
Singletons in Java 1.0 and 1.1
All Java specifications require us to keep a reference to the singleton object, or lose it to the garbage collector. But, in pre-1.2 Java specifications, the garbage collector was not only free to collect the singleton object but also the SimpleSingleton class! . This garbage collection of an actual class is also known as "class unloading."
Actually, in Java 1.0.x class unloading wasn't implemented, so our SimpleSingleton implementation would work just fine. Unfortunately, in Java 1.1.x even system classes were allowed to be unloaded. Typical workarounds for this inadvertent unloading of the singleton class include:
Keeping a reference to the singleton as a local variable in your main() method (or the run() method for thread classes).
Keeping a reference to the singleton as an instance variable in the class in which you define your main() method (or the run() method of a thread class).
Although these techniques work, they are problematic if you use third-party libraries and can't get to the singleton (as that particular class might be an internal helper class).
Singletons in Java 1.2
After a good bit of debate on the 'Net, combined with a number of complaints, the powers that be at Sun decided to clear up the problem by slightly modifying the Java language specification.
The new rules for determining when a class may or may not be unloaded are wonderfully simple:
All classes loaded through the local, system classloader will never be unloaded.
All classes loaded through other classloaders will be unloaded only when the classloader is unloaded.
So, for the vast majority of developers, this remedy gets rid of a relatively subtle, but annoying problem -- and we never have to lift a finger!
Dynamic loading and unloading of classes
For those of you who need to deal with loading and unloading classes on the fly, these new rules makes life a little clearer. Just load classes that you wish to later reload in your own classloader. When you want to reload the classes, nuke the classloader and then load the class through a newly created classloader.
Alas, there is not, at this time, any way to use classloaders in a secure environment from within an untrusted applet (as an untrusted applet is prevented from implementing classloaders). A RFE (um, er, request for enhancement) has been filed with Sun to create a constrained, untrusted classloader for use in untrusted applets.
This page formated for crawlers and browsers that don't support scripts and tables.
Home
EZone
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Singletons vs.
class (un)loading - JavaWorld - May
1998
View Tutorial: Singletons vs.
class (un)loading - JavaWorld - May
1998
Related
Tutorials:
Object-oriented
language basics, Part
7
Object-oriented
language basics, Part
7 |
Good
introduction to JDO
Good
introduction to JDO |
Comparison between the two major JDO architectures
Comparison between the two major JDO architectures |
Check out three
collections libraries
Check out three
collections libraries |
Profiling CPU
usage from within a Java application
Profiling CPU
usage from within a Java application |
Got
resources?
Got
resources? |
Software Download Central
compatible.
GNU getopt - Java port
A while back I found myself in need of a Java command line option parser. Unsatisfied with free versions I was able to find on the net, I volunteered to port the GNU getopt family of functions from C to Java. The current release |
Inside Class Loaders: Debugging
Inside Class Loaders: Debugging
This article will show how to solve class-loading problems and to overcome some debugging limitations of the JDK class loaders.
|
JLAN Server v3.3
JLAN Server v3.3
JLAN Server is a high performance JavaTM based file server supporting Windows file sharing (SMB/CIFS), NFS and FTP protocols.
Write your own virtual filesystems with the core server handling all protocol exchanges with the client.
Incl |
Mandarax
Mandarax is an open source java class library for deduction rules. It provides an infrastructure for defining, managing and querying rule bases. |
Java Resources
There are all Java freebies. Some of these are old, and not under maintenance. Download and use them at your risk. In case of queries, mail subrahmanyam_avb@technologist.com or varalakshmi_a@techie.com. |
Compare JavaServer Pages: Tag Libraries vs. JavaBeans
Java provides developers with JavaServer Pages (JSPs) and Servlets as a superior alternative to traditional CGI programs. The architecture of JSPs provide support for a logical and physical separation between the HTML page designers and the component deve |
Using JConsole to Monitor Applications
JConsole is the Java Monitoring and Management Console, a new graphical tool shipped in J2SE JDK 5.0. This article describes how JConsole can be used to observe information about an application running on the Java platform, with an overview of the J2SE 5. |
Understanding Network Class Loaders Class loaders
One of the cornerstones of Java dynamics, determine when and how classes can be added to a running Java environment. |
Internals of Java Class Loading
When are two classes not the same? When they're loaded by different class loaders. This is just one of many curious side effects of Java's class-loading system. Binildas Christudas shows how different class loaders relate to one another and how (and why) |
First Step towards JDBC!
First Step towards JDBC!
First Step towards JDBC
Introduction
T his article introduce you with JDBC and shows you how to create a database application to access the databases. For the shake of simplicity, in very first example Access database and |
Accessing Database from servlets through JDBC!
Accessing Database from servlets through JDBC!
Accessing Access Database From Servlet
T his article shows you how to access database from servlets. Here I am assuming that you are using win95/98/2000 and running Java Web Server. For the sake of |
Introduction to the JDBC
Introduction to the JDBC
Introduction to the JDBC
Introduction
T his article introduce you with JDBC and shows you how to our search engine with database.
What is JDBC?
J ava Database Connectivity or JDBC for short is set of Java API's that |
Complete Webhosting Guide, Search Web hosts, Find Plans
Complete Webhosting Guide, Search Web hosts, Find Plans
The Complete Web Hosting Guide
RoseIndia.net is the complete beginner's guide to finding a web hosting company.
Introduction to Web Hosting
What is Web Hosting? Linux vs. Windows |
Easy Emulation With New NetBeans Mobility Pack 4.0
With the click of a button, switch back and forth between different emulation environments while developing one set of code. It's never been this easy to take advantage of Java technology's cross-platform capabilities. |
|
|
|