Generic Singleton Pattern in Java

In my previous post about singleton pattern in C#, it is very nice flexible singleton code which make us be able to create a singleton instance of a non singleton class. But we can still be able to create a non singleton instance of the target class.

In this post I want to implement it in Java. As far as I know even though both C# and Java have generic feature, generic in C# quite different from the one in Java. While converting of what I did about generic singleton in C# to Java, I feel that the way I do in Java is not as elegant as in C#. The following code is the generic singleton code I write in Java.

import java.util.HashMap;
import java.util.Map;

public class Singleton{

    private static final Singleton instance = new Singleton();

    @SuppressWarnings( "rawtypes")
    private Map<Class,Object> mapHolder = new HashMap<Class,Object>();

    private Singleton() {}


    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> classOf) throws InstantiationException, IllegalAccessException {


        synchronized(instance){

            if(!instance.mapHolder.containsKey(classOf)){

                T obj = classOf.newInstance();  

                instance.mapHolder.put(classOf, obj);
            }

            return (T)instance.mapHolder.get(classOf);          

        }

    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }   
}

The following code show how to use the generic singleton class. It’s quite similar to the C# version.

public class Starter {

    /**
     * @param args
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException  {
        // TODO Auto-generated method stub

        Employee emp1 = new Employee();
        emp1.setName("neutro");

        Employee emp2 = new Employee();
        emp2.setName("neutro");

        boolean isEqual = emp1.equals(emp1);

        isEqual = emp1==emp2;       
        System.out.println("Is Equal Test1 = "+ isEqual);

        Singleton.getInstance(Employee.class).setName("Hello");
        emp1 = Singleton.getInstance(Employee.class);
        emp2 = Singleton.getInstance(Employee.class);

        isEqual = emp1==emp2;       
        System.out.println("Is Equal Test2 = "+ isEqual);

        System.out.println("emp1 = "+ emp1.getName());
        System.out.println("emp2 = "+ emp2.getName());


        Singleton.getInstance(Departement.class).setName("Information Technology");
        Departement dpt1 = Singleton.getInstance(Departement.class);
        Departement dpt2 = Singleton.getInstance(Departement.class);

        isEqual = dpt1==dpt2;       
        System.out.println("Is Equal Test3 = "+ isEqual);

        System.out.println("dpt1 = "+ dpt1.getName());
        System.out.println("dpt2 = "+ dpt2.getName());

    }
}

Again, if we see from the sample code above it seems that generic singleton in C# is more elegant than in Java. The main thing that I should do is I have to use HashMap collection to hold any instance of what that want to be as singleton and reuse for the future need in the life cycle of my application.

Anyway, if you have better and much more elegant solution how to implement generic singleton pattern in Java I am very appreciate for any suggestion. Finally I would like to thank you very much for visiting and reading my blog, and have a nice day.

Update March 11, 2016

If you want to the java singleton above, please ensure you have remove / clean up method to clean up HashMap contents if the singleton objects are not needed anymore. At least at the end of application lifecycle, the HashMap and its contents should be removed completely from memory.

Generic Singleton Pattern in C#

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.[1]

Honestly in my daily coding activity, sometimes I need to implement singleton pattern. Jon wrote a good singleton article in C# here. Another case I want to implement singleton pattern in generic way. I convert what has been wrotten by Jon into generic.

/// <summary>
    /// Generic class which makes non singleton class to be singleton.
    /// Calling singleton instance of class should be Singleton<T>.Instance, otherwise the returned class is not singleton one.    ///
    /// </summary>
    /// <typeparam name="T">Genric class type to be singletonized</typeparam>
    public sealed class Singleton<T> where T : class, new()
    {
        /// <summary>
        /// Private constuctor to avoid this class instantiated
        /// </summary>
        Singleton()
        {
        }

        /// <summary>
        /// Property to get access to singleton instance
        /// </summary>
        public static T Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        /// <summary>
        /// Private nested class which acts as singleton class instantiator. This class should not be accessible outside <see cref="Singleton<T>"/>
        /// </summary>
        class Nested
        {
            /// <summary>
            /// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
            /// </summary>
            static Nested()
            {
            }

            /// <summary>
            /// Static instance variable
            /// </summary>
            internal static readonly T instance = new T()
        }
    }

The following snipped code is a sample how to use the generic singleton class.

public class Processor
{
    public string Name
    {
        get;
        set;
    }

    public void Execute()
    {
    }
}

public class void Main(string[] args)
{
    Singleton<Processor>.Instance.Execute();
}

From the sample above is shown that we can make a non singleton class to be singleton at runtime. But we can still create a non singleton instance as we need. That’s really nice flexible thing.

Reference

[1] http://en.wikipedia.org/wiki/Singleton_pattern

ASP.NET Session State in Database

At some point we need to store information when dealing with web application. Storing information in web application can be implemented in some ways such as session and cookies.

Dealing with session case, previously I never got a situation where I should store the session state in persistance way till I got a condition implementing this way.

The scenario is we want to implement load balancer to our applications and services (web service, wcf) that hosted in IIS. The aim of this enhancement basically to improve availability and scalability of existing in house application without doing huge refactoring.

In this post I just want to share the short steps I did during researching implementing session state on a database. First of all open command prompt and navigate to .NET framework installation path. In this case, my installation path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

We will use a tool called aspnet_regsql.exe that shipped with .NET framework installation to generate database that will be used to store session state. To display detail argument needed by this tool we can use the following command:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regsql.exe /?
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regsql.exe -ssadd -d {databaseName} -S {server\instance} -sstype c -U {username} -P {password}

The command will create database, tables and store procedures. In web.config, don’t forget to add session state configuration by pointing the generated database.

<!--session state configuration-->
<system.web>
    <sessionstate mode="SQLServer" allowcustomsqldatabase="true" sqlconnectionstring="Data Source={server\instance};Initial Catalog={databaseName}; user={username}; password={password}" cookieless="false" timeout="20">

  </sessionstate>
</system.web>

To test our session storage, just create simple aspx page.

<asp:button id="btnAddSession" runat="server" text="Add Session" onclick="btnAddSession_Click"/>

<asp:button id="btnRemoveSession" runat="server" text="Remove Session" onclick="btnRemoveSession_Click"/>

<br>
<asp:label id="ctlLblSessionDisplay" runat="server" text=""></asp:label>
protected void Page_Load(object sender, EventArgs e)
{
    if (Session[Constant.SessionKey] != null)
        ctlLblSessionDisplay.Text = Session[Constant.SessionKey].ToString();
    else
        ctlLblSessionDisplay.Text = "NO Session";
}

protected void btnAddSession_Click(object sender, EventArgs e)
{
    Session.Add(Constant.SessionKey, "Hello");
}

protected void btnRemoveSession_Click(object sender, EventArgs e)
{
    Session.Remove(Constant.SessionKey);
}

Mono on OS X 10.8 Mountain Lion

In this post I will write about setup and configure mono on OS X. I need mono on my Mac since C# is one of my favorite programming language ;)

First of all let’s download Mono SDK and MonoDevelop. The order installation is Mono SDK first then MonoDevelop. The installation of Mono SDK and MonoDevelop should be easy by following the installation wizard.

When the installation finish, open terminal :

# mono version
mono -V

We should get info about the version of mono installed in our machine.

Try to create an ASP.NET Web Application project by selecting menu : File > New > Solution. Select C# > ASP.NET > Web Application

Click Run > Run With > Mono Soft Debugger for ASP.NET

ASP.NET on Apache Web Server

To run ASP.Net on Apache web server, we need Mod mono module. It is an Apache 2.0/2.2 module that provides ASP.Net support for Apache web server. The steps installation are :

  1. Install Apache web server. The steps for OS X Mountain Lion can be found in my previous post
  2. Install Xcode, OS X development tool. It’s free and can be downloaded via App Store. We need it to compile mod mono installation source
  3. Download Mod mono source installation here. At the time of write this article I use mod_mono-2.10.tar.bz2
  4. Install mod mono module. Open terminal
    # mod mono installation
    mkdir ~/modmono
    cp ~/Downloads/mod_mono-2.10.tar.bz2 ~/modmono
    cd ~/modmono
    tar xzf mod_mono-2.10.tar.bz2
    cd mod_mono-2.10
    ./configure
    make
    sudo make install
    sudo cp /etc/apache2/mod_mono.conf /etc/apache2/other
  5. Add mod_mono.conf reference in httpd.conf
    sudo vi /etc/apache2/httpd.conf
    Add the following code at the end of httpd.conf
    Include /etc/apache2/mod_mono.conf
  6. Create a web directory with the path ~/Projects/Mono/TestMonoApache/TestMonoApache/ In that directory create an index.aspx file
    <center>mod_mono is working:<%=System.DateTime.Now.ToString()%></center>
  7. Add an Apache configuration file for mono.
    sudo vi /etc/apache2/mod_mono.conf
    Add the following line at the end of mod_mono.conf
    Alias /testmono "/Users/username/Projects/Mono/TestMonoApache/TestMonoApache/"
    <Directory "/Users/username/Projects/Mono/TestMonoApache/TestMonoApache/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
    
        Order allow,deny
        Allow from all
    </Directory>
    AddMonoApplications default "/testmonoapache:/Users/username/Projects/Mono/TestMonoApache/TestMonoApache/"
    <Location /testmonoapache>
     SetHandler mono
    </Location>
  8. Restart apache server with command :
    sudo /usr/sbin/apachectl restart
  9. Open browser and hit http://localhost/testmonoapache/index.aspx

Cool, now our apache web server can receive request for asp.net page. Thanks for reading and see you in the next post :)

References

  1. http://www.mono-project.com/Mod_mono
  2. http://blog.coultard.com/2012/04/developing-using-c-and-mono-on-mac.html
  3. http://www.ienablemuch.com/2010/10/aspnet-on-mac-os-x-snow-leopard-at-one.html

Install Tomcat in OS X 10.8 Mountain Lion

In this blog post will show us about step installing Apache Tomcat on OS X Mountain Lion. I assume we already have Java installed on our machine. The first step is downloading Tomcat binary distribution in Tomcat website. In this case I use version 7.0.30.

Extract the downloaded binary distribution onto ~/Download/apache-tomcat-7.0.30. Create directory in /usr/local if we don’t have it yet.

sudo mkdir /usr/local

Move ~/Download/apache-tomcat-7.0.30 to /usr/local

sudo mv ~/Downloads/apache-tomcat-7.0.30 /usr/local

To make it easy to replace this release with future releases, we are going to create a symbolic link that we are going to use when referring to Tomcat. Then we also will change owner and make script executable

sudo ln -s /usr/local/apache-tomcat-7.0.30/ /Library/Tomcat
sudo chown -R neutrocode /Library/Tomcat
sudo chmod +x /Library/Tomcat/bin/*.sh

The next step is creating user for tomcat admin by editing tomcat-user.xml

vi /Library/Tomcat/conf/tomcat-users.xml
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>

<user username="admin" password="password" roles="admin-gui,admin-script" />
<user username="manager" password="password" roles="manager-gui,manager-script,manager-jmx,manager-status" />

Add the following text in current user profile .bash_profile

# .bash_profile
export CATALINA_HOME=/Library/Tomcat
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home

export PATH=$JAVA_HOME:$PATH

Start the server with the following command :

# start tomcat
$CATALINA_HOME/bin/catalina.sh start

or

# start tomcat
$CATALINA_HOME/bin/startup.sh

Stop the server with the following command :

# stop tomcat
$CATALINA_HOME/bin/catalina.sh stop

or

# stop tomcat
$CATALINA_HOME/bin/shutdown.sh