Solved

Java singleton - elaborate

Posted on 2014-11-30
2
185 Views
Last Modified: 2015-02-23
I wonder when it is a bad idea to use singletons in Java.

Specifically I am to build an API where files will be submitted to my API (or actually the file name and then the file will be located in a specific directory).

There are no specifications on how many transactions needs to be handled. If there would have been my stomach tells me it would be good to have a singleton taking care adding to of the inqueue and making sure it is not bigger then MAX_ALLOWED_SIZE (a value set to a reasonable figure to make sure the system is stable).

Something I do know is that I need to have a very good idea on how to make the code testable. Something that is abit tricky when it comes to singletons.

-JUnit
-On the system level - performance wise maybe

Please elaborate on when to use a singleton and when not, and also how to handle Junit testing and also if possible a good way to handle performance testing.
0
Comment
Question by:mdoland
2 Comments
 
LVL 35

Accepted Solution

by:
mccarl earned 250 total points
ID: 40472891
I wonder when it is a bad idea to use singletons in Java.
It is a bad idea to use singletons when singletons don't fit with your design. And yes, that statement was intentionally vague because your question is so open, ie. it totally depends on each individual situation as to whether a singleton is a good/bad idea. Also you can take from the above, that there is nothing "inherently" bad about them, they just should be used when the right situation calls for it. Note also that the above is talking from a framework agnostic point of view, and if you are referring to specific frameworks then the above situation might change somewhat. For example, if you are using Spring then singletons are using quite extensively, whereas others (I think J2EE might be one, I've never really used it though) don't really use them at all.

As for issues regarding testability, then whether you have singletons or not should make NO difference what so ever. How you design your classes and how you implement that design will be the telling factor on how testable you code is. Ensuring that you keep a good separation of concerns and clean API's between your classes is a first step to ensuring testable code.
0
 
LVL 27

Assisted Solution

by:dpearson
dpearson earned 250 total points
ID: 40473094
The concerns people have with Singletons for testing is that they may want to replace the object managed by the Singleton with a mock object.  This may or may not be easy.

For example:

public class Database {
    private final static Database instance= new Database("jdbc:mysql://...") ;

    public static Database getDatabase() { return instance ; }
}

Since this Singleton is tied to a real database which it initializes itself, it may make unit testing of other elements harder.  For instance it's common to replace calls to an actual SQL database with a mock database during testing - perhaps an in memory database.  The above class makes that hard to do.

The common fix is to have the Singleton not initialize itself, but be passed in:

public class Database {
    private final static Database instance = null ;

    public static void initialize(Database inst) {
         if (instance != null)
            throw new IllegalStateException("This is a singleton - only allowed to set it one time") ;

         instance = inst ;
    }

    public static Database getDatabase() { return instance ; }
}

This makes the Singleton more testable, but makes initialization more complex in return (somebody has to remember to initialize this before it's used and that has to happen exactly once).

As mccarl says, it depends on the specifics of the problem whether there's an issue with what you're trying to do with a Singleton or not.  But that's the general concern.

Doug
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Maven Project: Hibernate Dependencies Conflict 10 40
map related example 6 55
tomcat startup error 5 104
maven module vs maven project 3 47
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question