Singletons and Static class behavior

Hi all and thanks for taking a look at this,
I was playing around with a Singleton class today and it raised raised a few questions around Static methods in the singleton. When my class is instatiated I load some data into a HashMap map that I want to make available for read only purposes through other methods in my singleton.
I really wanted to just call a static method to look up the value, so I followed the standard model. I had a private static HashMap that is loaded with data when the Contructor is called from the getInstance(). I included the standard model example for you if you wanted to refer to it.
I ran my code making a static MyClass.getData() call to see what would happen. The static call did not return a value, I wasn't surprised. Then I added a call to MyClass.getInstance() followed by the static MyClass.getData() call and this returned the appropriate value.
Then I changed my Singleton as follows and was wondering if there were any issues that might result because of this and I was wondering what the process that is followed by java when calling a static method (what does it use, where does it look).
My Code:
public class MyClass {
private static MyClass instance;
private static HashMap myData;
private MyClass() {
myData = new HashMap();
myData.put("1", "value 1");
myData.put("2", "value 2");
private static synchronized void getInstance() {
if (instance == null)
instance = new MyClass();
public static String getData(String key) {
if (myData == null)
getInstance();
return (String)myData.get(key);
The standard singleton model class:
public class MyClass {
private static MyClass instance;
private MyClass() { }
public static synchronized MyClass getInstance() {
if (instance == null)
instance = new MyClass();
return instance;
... rest of methods (not static)
}

Thanks for the reply,
Really my only reason for making it static was so the calling class would not have to get a handle to the actual MyClass Instance. Therefore avoiding the Synchronization method.
I was attempting to aviod the famous broken double check locking by having the checks in different methods. I am assuming from you warning that keeping the methods seperate and synchronizing the getInstance is really no different than putting a synchronize(this) block around the second check and the constructor call?
Really my objective is to retrive data once, not really create a single access point for getting the data. As an alternative, I tried the following code and it seems to work, any issues you can see with this?
public class MyClass {
private static HashMap hm;
static {
hm = new HashMap();
// code to get Data into HashMap
public static String getData(String key) {
return hm.get(key);

Similar Messages

  • Singleton pattern class and static class

    Hi,
    what is difference between the singleton pattern class and static class ?
    in singleton pattern, we declare a static member[which hold one value at a time] ,static method[ which return static member value] and a private constructor[not allow to direct instantiation]. My words are -- as a singleton pattern we implement static class .
    so can we say a singleton pattern is static class it means both are same or is any difference between these two ??

    malcolmmc wrote:
    On several occasions I've had to convert a static (never instanceated) class to a singleton type, for example because I realise I need an instance per thread, or I decide to make a program more modular, with more than one configuration.
    I've never done the opposite.
    So generally I favour the singleton if there any "state" involved, because it's more flexible in unanticipated directions. It also gives extra flexibility when building tests, especially if you program to an interface.Total agreement; if anything it is dead hard to override static method logic with mock code in unit tests (I had to do it by keeping the static methods in place but making them internally use a singleton instance of itself of which the instance variable could be overwritten with a mock implementation for unit testing purposes...).
    'Static classes' and/or methods are great for very simple util functions, but I wouldn't use them for anything other than that.

  • What's the differences between a singleton and a class with static methods

    Hi everybody.
    My question is in the subject. Perhaps "differences" is not the good word. The positive and negative points ?
    Imagine you have to write a connection pool, sure you gonna choose a singleton but why ?
    Thank you very much.

    A class is a class. Java doesn't have (and I wish it
    did) a static outer class. Any class can extend
    another class or implement an interface.A Class object cannot extend or implement anything - it is not under programmer control in any way. You can create a class which implements interfaces, but calling static methods is completely unrelated. Interfaces only affect instance methods, not class ones. I think all of your comparison to C++ is actually confusing you more. In Java, there is a real class object at runtime, as opposed to C++.
    YATArchivist makes a good point about being able to
    serialize, altho I've not met that desire in practice.
    Maybe a concrete example would help.
    mattbunch makes another point that I don't understand.
    A class can implement an interface whether it sticks
    its data in statics or in a dobject, so I guess I
    still don't get that one.See my comment above. Static methods are free from all contractual obligations.
    I prefer instance singletons to singleton classes because they are more flexible to change. For instance I created a thread pool singleton which worked by passing the instance around, but later I needed two thread pools so I made a slight modification to the class and poof! no more singleton and 99% of my code compiled cleanly against it.
    When possible, I prefer to hand the instance off from object to object rather than have everything call Singleton.instance() since it makes changes like I mentioned earlier more feasible.

  • Singleton Vs Static Class

    Hi,
    Kindly excuse if my question annoys anyone in the forum.
    Compared to a singleton class we can always have a class and all methods as static?
    Wouldnt that be the same as Singleton.
    Also looking at Runtime class, its a Singleton. Just thinking if Runtime class could be a class with this static methods instead of making the constructor private .

    I thought I read somewhere that however you implement your singletons, client code shouldn't break if later you decide that you don't need/want a singleton for that class anymore.I agree with that principle.
    This requires that the client code never calls the getInstance() method, and the best way to make sure of that is that the client code does not depend on the singleton class, but on an interface that the singleton class implements.
    (Speaking for myself, I can assure you that I never thought that deeply about it, but continuing...)I have thought a lot about Singletons, specifically when contemplating flaying myself alive for putting them prematurely where they weren't really needed (not to mention some of my colleagues' choice, for fear my message would deserve editing out by moderators).
    I have come to the conclusion that Singleton is overhyped, probably because it's one of the simplest patterns, and the first one people are taught as a way to illustrate the very concept of "design pattern". And overused because it feels so natural to use the first and simplest pattern one has learnt.
    I'm not claiming Singleton has no merits (I used to claim that on this forums). I'm claiming most usages I've seen of Singleton were not based on a careful consideration of the real merits.
    If we implement our singletons (who have state) as "static classes", aren't we violating this?Ah, OK, I get it now: if someday you need to have several copies of the states with different values, you could always "de-singletonize" the singleton, with minimal impact for properly-written client-code, as you point out, whereas you couldn't justas easily "de-staticize" the static calls.
    Indeed that's an argument when evaluating whether making a method static: it statically (1) binds the client code to the implementation class.
    (1) not a pun, merely the very justification for the term static as a keyword.
    J.

  • Singleton Vs Static Classes

    What is the Difference b/w implementing a singleton pattern and
    making a class Static?

    If you implement a (the?) singleton pattern, references to the resulting
    object can be passed around as method arguments, and it can
    belong to a class which implements useful interfaces or extends
    some useful base class.

  • Custom Taglets and static class fields/methods...

    Hey all,
    I have a curiosity question (running winxp + j2sdk 1.4.2_04).
    I have written a few stand-alone and inline taglets to help me document my code. I had some problems initially getting the HTML to output correctly (and I don't know how to run javadoc in the debugger) so I wrote a simple class with only static methods/members that tracks the nesting level of the current tag and allows me to pad (prefix) the output based on the nesting level (rudimentary I know). I wasn't sure if the javadoc process was multi-threaded or not, so all methods are synchronized.
    My problem is that the static initializer is being called 6 different times during the execution of javadoc.exe, resulting in what I would term as 6 "static" instances. Now, the only reason I can think of for this is that it is spinning off new process for each type of taglet it encounters. However, processing seems sequential and I don't see any other processes in Windows Task Manager. Here is the static initializer code:
         static {
              ic = new IndentControl();
              System.out.println("static: " + Thread.currentThread() + " ic instance: " + ic);
    and here is the output of javadoc.exe:
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@33c78b
         Registered Taglet ndstest.util.javadoc.MandatoryTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@6c137c
         Registered Taglet ndstest.util.javadoc.OptionalTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@1104da7
         Registered Taglet ndstest.util.javadoc.MemberInlineTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@6745b9
         Registered Taglet ndstest.util.javadoc.DescriptionInlineTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@10a14ad
         Registered Taglet ndstest.util.javadoc.ExampleTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@1afe460
         Registered Taglet ndstest.util.javadoc.ToDoTaglet ...
    Why does the static initializer get called 6 different times? It's mildly annoying and I want to understand why and if it is something I am doing to cause this.
    Thanks!

    Well, have you ever taken a look at the implementation of the Standard doclet? (Its source code is part of the SCSL distribution.)
    The current implemenatation uses a TagletManager to handle/store/load custom taglets.
    For each -taglet option, method addCustomTag of this TagletManager is called.
    This method creates a new instance of UrlClassLoader and uses loadClass( className ) to load the taglet each time it is called.
    So, each of your six taglets is loaded through/in a different ClassLoader context, therefore the static init block is executed six times.

  • Design Pattern: Is the Universe Object a Singleton or Static or either way.

    Hi All,
    1. I've read this thread: static versus singleton
    http://forum.java.sun.com/thread.jsp?forum=425&thread=401035&tstart=105&trange=15
    2. Now, specifically if you were to model the Universe Object, what would you choose? a Singleton
    or a Static Class or either way depending on your design point of view?
    (either way depending on your design point of view imply there is more than one solution to a problem.)
    Basically, I'm looking for is the justification of one (singleton) or the other (static) or doesn't matter
    in addition to the pure technical pros and cons (or avantage/disavantage) of singleton versus Static (see pt. 1)

    <dubwai>
    What's 'the Universe Object'?
    </dubwai>
    Sorry, for not being clear. My assumption is that every body would undertand the word 'Universe' immediately. So with this clarification. I hope you will have more input. Thanks.
    public class Universe //Singleton
         private static Universe instance = new Universe(); 
         private Universe()
         public static Universe getInstance() 
           return instance;
         public void do() 
    public class Universe  //Static Class like Math class for example
         public static void do() 
         ...all other methods are static
    <os>
    Personally, I'd make the universe a singleton.
    The universe is an 'object', not a class, and if alternate universes are proved to exist you can create new instances,
    and not treat it as a singleton any more, without much rewriting (a static implementation would need a total rewrite).
    </0s>
    1. Keywords: Personally and alternate universes are proved to exist.
    Yes, this is the kind of reasoning I'm looking for. By that I mean when we design a class, our reasonning should not depends
    on the 'pure' technical concepts of what Singleton class or Static class can do but rather depending on the reality
    of the world. And then from that understanding we would choose a Singleton or Static class. This is what I meant by 'Either way, it doesn't matter' which depend on one's view about of existence of the universe whether it's unique or not. In your case (Os), you prefer Singleton because of the possibility of alternate universes.
    2. Now, let's admit, there is only one Universe, would you still prefer Singleton class over Static class? for all the techincal reasons that you said
    "As a singleton,..."
    "It would also probably be useful to treat the universe as a generic Object..."
    OR just because a Singleton would be 'safer' to cover the possibility of design extension in that can cover all cases (alternate as well)

  • Difference between a static class and singleton

    What is the difference between a static object and a singleton ?
    for example:
    1 )
    public class MyObject {
    static MyObject singleton ;
    public static MyObject getInstance() {
    if (singleton ==null) singleton = new MyObject ();
    return singleton;
    private MyObject () {
    supe();
    public void myMethod() {
    2 )
    public class MyObject {
    private MyObject () {
    supe();
    public static void myMethod() {
    If I need to call the myMethod() , witch of this solution is better ?
    // case 1
    MyObject.getInstance().myMethod()
    // case 2
    MyObject.myMethod()
    .....

    This has been discussed a lot here.
    Use the forum's search feature, or, since it's not necessarily reliable, use google.
    For many intents and purposes, they're equivalent.
    However, with a singleton you can implement an interface, and get polymorphic behavior. You can't do with with a class full of static methods (which, by the way, is NOT a static class).

  • Difference between static class and singleton?

    Hi I wonder what could be the difference between static methods and singleton?
    In singleton at any point of time there will be only one object existing in the JVM. We create singleton to avoid multiple object creation for that class.
    If I make all the methods in the class as static also it does the same job. The memory will be allocated once. Even there wont be any object in this case, so time required for object creation also can be saved. looks like more efficient but still why need singleton?
    This question is also posted in java programming forum. The thread is as follows:-
    [Click on this to visit that thread |http://forum.java.sun.com/thread.jspa?threadID=5278517&tstart=0]
    Edited by: murrayb9654 on Mar 25, 2008 8:20 AM

    yawmark wrote:
    Static class is a realization of singleton pattern.Not in any conventional sense.
    ~Especially since a static class is completely different from a class with all static methods.

  • Singleton instance vs static class

    Hi,
    I often got confused to identify when is better to use a singleton instance and when is better use a static class insted.
    Could someone please advise what criteria should be observed to decide which way is better?
    Thanks in advance,

    A class with all static methods generally connotes a helper class that supplies behavior or enforces business rules of other objects. A class with only state and no behavior is typically encountered in distributed systems, also known as a transfer object. Most true objects have both state and behavior. A singleton is simply a normal object that ensures only a single instance of itself will ever be created and returned for use to a caller.
    - Saish

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Abstract classes and static methods

    I have an abstract report class AbstractReportClass which I am extending in multiple report classes (one for each report, say ReportA, ReportB, ...). Each report class has its own static column definitions, title, etc., which I have to access through a static method getDataMeta() in a web application. Each report has the same exact code in getDataMeta, and no report may exist without these fields. My intuition tells me that AbstractReportClass should contain the code for getDataMeta, but I know that you can't mix abstract and static keywords.
    Am I missing a simple solution to unify the getDataMeta code in the abstract base class? or do I really need to have a static function getDataMeta with the same code in each of the base classes?
    My apologies if this has been discussed many times before.
    Thanks,
    -Andrew

    I'm not trying to be "right"; rather I just asked a question about whether I can do something that seems intuitive. Perhaps you might write code in a different way than I would or perhaps I wasn't clear about every little detail about my code? Do you regularly belittle people who ask questions here?
    I have a loadFromDB() member function in AbstractReport for which all sub classes have an overloaded version. All reports I'm displaying have 4 common fields (a database id and a name and a monetary value, for example), but then each other report has additional fields it loads from the database. Inside ReportX classes' loadFromDB(), I call the superclass loadFromDB() function and augment values to get a completely loaded object. In fact, the loadedData member object resides in AbstractReport.
    I can't use a report unless it has these common features. Every report is an AbstractReport. There is common functionality built on top of common objects. Isn't this the point of inheritance? I'm essentially saying that abstract class Shape has a getArea function and then I'm defining multiple types of Shapes (e.g. Rectangle and Circle) to work with...

  • Static class and clustering

              I have a static class that I use to cache some values during a batch process. The
              batch process uses a JMS queue to parcel our identical units of work to MDBs.
              I want this to scale using a cluster with the same MDBs on multiple machines.
              Everything works fine except that I can't figure out how to tell my cache to clear
              itself out on every node between batch runs. Is there a pattern or solution to
              this problem?
              What I've tried is to create a stateless session bean method that clears my cache.
              At the begining of my batch job, (which is a stateless session bean call) I call
              this method on each server in the cluster by getting the remote interface for
              the stateless bean via the different URLs of the servers. However, the session
              bean method always executes on the one server where I make the call. It's as if
              WebLogic gives me back a local interface instead of the remote interface that
              I asked for.
              Any ideas would be appreciated.
              Colin
              

    ... static class and static method.I have never heard of a thing called "static class". Perhaps you mean a class with only static members?
    My design approach (which is bound to needs of the moment and seldom to library-development or future re-use, since both is harder than most developers realize) is to develop straight without caring too much about static or not. When a method is done, debugged and works well, it happens that other objects access this method as well.
    It may happen that I just want to use this single method and almost nothing else of the object. If that is the case, I can start looking if it's a Good Thing(tm) to make the method static, so no object creation is needed just for the one method. Sometimes it can be done, sometimes not.
    But that's just me and you'll find quite a lot of coders that'll advice you to decide what's static and what not before you start coding. And that's as good an advice as most others you can get.
    In the end it's your decision, so start fiddling around and see what fits best for you.
    -T-

  • SQL, static classes and sessionBeans

    Hi,
    my JSF-project has one static class where it handle all sql-queries and I asked me if that is the "best" solution.
    I.e. a User-Sessionbean call that static class to save his data into the user-sql-table. I asked myself, if it might not better to delete this static class and let the user-sessionbean save his data itself.
    If my webserver has 100 usersessions and 50 users save their data at same time, does the "static-sql-save-version" has only one sql-connection and 49 user have to wait in a queue? And with the "every-usersession-has-his-own-sql-save-method" I have got 50 DB connection at the same time?
    I hope you could help me :)
    Alex

    you will gain some bytes by merging all the static classes in one.
    you can create a ManagerTool.java class and write inside all the static methods ...

  • Static classes and variables

    Hello,
    I put all of my constants in an *{color:#3366ff}interface{color}* called Constants.java (I only put constants in this file) and when obfuscated the Constants.class file is removed from .jar and constants are inlined into classes this is Great! However, do I gain anything by placing all of my static methods into one class? Currently, there are all over the place and also I have classes that are already static like HttpMgr.java/ErrorMgr.java/InfoMgr.java I am thinking about merging these classes together with all static methods defined within the project. Do I gain or loss anything by doing this?
    Thanks!

    you will gain some bytes by merging all the static classes in one.
    you can create a ManagerTool.java class and write inside all the static methods ...

Maybe you are looking for