Singleton java object

For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.

Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.

So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.
Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.
Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....
Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();
}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}

private static SingletonObject ref;
}

Summary

A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

hibernate mappinigs

db queries
------------

  CREATE TABLE TEST1
   (    "ID" NUMBER NOT NULL ENABLE,
    "DESC" VARCHAR2(20 BYTE),
     CONSTRAINT "TEST1_PK" PRIMARY KEY ("ID")

   ) ;


  CREATE TABLE "SYSTEM"."TEST2"
   (    "T2ID" NUMBER NOT NULL ENABLE,
    "T1FKID" NUMBER NOT NULL ENABLE,
    "T2DESC" VARCHAR2(20 BYTE),
     CONSTRAINT "TEST2_PK" PRIMARY KEY ("T2ID")
      CONSTRAINT "TEST2_TEST1_FK1" FOREIGN KEY ("T2ID")
     REFERENCES TEST1 ("ID") ON DELETE CASCADE ENABLE
   );


  CREATE TABLE "SYSTEM"."TEST3"
   (    "T3ID" NUMBER NOT NULL ENABLE,
    "T11FK1D" NUMBER NOT NULL ENABLE,
    "T2FK1D" NUMBER NOT NULL ENABLE,
    "T3DESC" VARCHAR2(20 BYTE),
     CONSTRAINT "TEST3_PK" PRIMARY KEY ("T3ID", "T11FK1D", "T2FK1D"),
      CONSTRAINT "TEST3_TEST1_FK1" FOREIGN KEY ("T11FK1D")
      REFERENCES TEST1 ("ID") ENABLE,
     CONSTRAINT "TEST3_TEST2_FK1" FOREIGN KEY ("T2FK1D")
      REFERENCES TEST2 ("T2ID") ENABLE
   ) ;






test1.hbm.xml
----------------
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="comjava.Test1" table="TEST1" schema="SYSTEM">
        <id name="id" type="java.math.BigDecimal">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="desc" type="java.lang.String">
            <column name="DESC" length="20" />
        </property>
        <set name="test3s" inverse="true">
            <key>
                <column name="T11FK1D" precision="22" scale="0" not-null="true" />
            </key>
            <one-to-many class="comjava.Test3" />
        </set>
        <one-to-one name="test2" class="comjava.Test2"></one-to-one>
    </class>
</hibernate-mapping>


test2.hbm.xml
--------------

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="comjava.Test2" table="TEST2" schema="SYSTEM">
        <id name="t2id" type="java.math.BigDecimal">
            <column name="T2ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
      
        <one-to-one name="test1" class="comjava.Test1" constrained="true"></one-to-one>
      
        <property name="t1fkid" type="java.math.BigDecimal">
            <column name="T1FKID" precision="22" scale="0" not-null="true" />
        </property>
      
        <property name="t2desc" type="java.lang.String">
            <column name="T2DESC" length="20" />
        </property>
      
        <set name="test3s" inverse="true">
            <key>
                <column name="T2FK1D" precision="22" scale="0" not-null="true" />
            </key>
            <one-to-many class="comjava.Test3" />
        </set>
      
      
      
    </class>
</hibernate-mapping>


test3.hbm.xml
-------------

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="comjava.Test3" table="TEST3" schema="SYSTEM">
        <composite-id name="id" class="comjava.Test3Id">
            <key-property name="t3id" type="java.math.BigDecimal">
                <column name="T3ID" precision="22" scale="0" />
            </key-property>
            <key-property name="t11fk1d" type="java.math.BigDecimal">
                <column name="T11FK1D" precision="22" scale="0" />
            </key-property>
            <key-property name="t2fk1d" type="java.math.BigDecimal">
                <column name="T2FK1D" precision="22" scale="0" />
            </key-property>
        </composite-id>
      
      
        <many-to-one name="test1" class="comjava.Test1" update="false" insert="false" fetch="select">
            <column name="T11FK1D" precision="22" scale="0" not-null="true" />
        </many-to-one>
      
        <many-to-one name="test2" class="comjava.Test2" update="false" insert="false" fetch="select">
            <column name="T2FK1D" precision="22" scale="0" not-null="true" />
        </many-to-one>
        <property name="t3desc" type="java.lang.String">
            <column name="T3DESC" length="20" />
        </property>
    </class>
</hibernate-mapping>


java classes
--------------

test1.java
-----------
package comjava;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;


/**
 * Test1 entity. @author MyEclipse Persistence Tools
 */

public class Test1  implements java.io.Serializable {


    // Fields  

     private BigDecimal id;
     private String desc;
     private Set test3s = new HashSet(0);
     private Test2 test2;


    // Constructors

    /** default constructor */
    public Test1() {
    }

    /** minimal constructor */
    public Test1(BigDecimal id) {
        this.id = id;
    }
  
    /** full constructor */
    public Test1(BigDecimal id, String desc, Set test3s, Test2 test2) {
        this.id = id;
        this.desc = desc;
        this.test3s = test3s;
        this.test2 = test2;
    }

 
    // Property accessors

    public BigDecimal getId() {
        return this.id;
    }
  
    public void setId(BigDecimal id) {
        this.id = id;
    }

    public String getDesc() {
        return this.desc;
    }
  
    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Set getTest3s() {
        return this.test3s;
    }
  
    public void setTest3s(Set test3s) {
        this.test3s = test3s;
    }

    public Test2 getTest2() {
        return this.test2;
    }
  
    public void setTest2(Test2 test2) {
        this.test2 = test2;
    }

}


test2.java
-----------
package comjava;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;


/**
 * Test2 entity. @author MyEclipse Persistence Tools
 */

public class Test2  implements java.io.Serializable {


    // Fields  

     private BigDecimal t2id;
     private Test1 test1;
     private BigDecimal t1fkid;
     private String t2desc;
     private Set test3s = new HashSet(0);


    // Constructors

    /** default constructor */
    public Test2() {
    }

    /** minimal constructor */
    public Test2(BigDecimal t2id, Test1 test1, BigDecimal t1fkid) {
        this.t2id = t2id;
        this.test1 = test1;
        this.t1fkid = t1fkid;
    }
  
    /** full constructor */
    public Test2(BigDecimal t2id, Test1 test1, BigDecimal t1fkid, String t2desc, Set test3s) {
        this.t2id = t2id;
        this.test1 = test1;
        this.t1fkid = t1fkid;
        this.t2desc = t2desc;
        this.test3s = test3s;
    }

 
    // Property accessors

    public BigDecimal getT2id() {
        return this.t2id;
    }
  
    public void setT2id(BigDecimal t2id) {
        this.t2id = t2id;
    }

    public Test1 getTest1() {
        return this.test1;
    }
  
    public void setTest1(Test1 test1) {
        this.test1 = test1;
    }

    public BigDecimal getT1fkid() {
        return this.t1fkid;
    }
  
    public void setT1fkid(BigDecimal t1fkid) {
        this.t1fkid = t1fkid;
    }

    public String getT2desc() {
        return this.t2desc;
    }
  
    public void setT2desc(String t2desc) {
        this.t2desc = t2desc;
    }

    public Set getTest3s() {
        return this.test3s;
    }
  
    public void setTest3s(Set test3s) {
        this.test3s = test3s;
    }

}


test3.java
----------

package comjava;



/**
 * Test3 entity. @author MyEclipse Persistence Tools
 */

public class Test3  implements java.io.Serializable {


    // Fields  

     private Test3Id id;
     private Test1 test1;
     private Test2 test2;
     private String t3desc;


    // Constructors

    /** default constructor */
    public Test3() {
    }

    /** minimal constructor */
    public Test3(Test3Id id, Test1 test1, Test2 test2) {
        this.id = id;
        this.test1 = test1;
        this.test2 = test2;
    }
  
    /** full constructor */
    public Test3(Test3Id id, Test1 test1, Test2 test2, String t3desc) {
        this.id = id;
        this.test1 = test1;
        this.test2 = test2;
        this.t3desc = t3desc;
    }

 
    // Property accessors

    public Test3Id getId() {
        return this.id;
    }
  
    public void setId(Test3Id id) {
        this.id = id;
    }

    public Test1 getTest1() {
        return this.test1;
    }
  
    public void setTest1(Test1 test1) {
        this.test1 = test1;
    }

    public Test2 getTest2() {
        return this.test2;
    }
  
    public void setTest2(Test2 test2) {
        this.test2 = test2;
    }

    public String getT3desc() {
        return this.t3desc;
    }
  
    public void setT3desc(String t3desc) {
        this.t3desc = t3desc;
    }

}

test3Id.java
--------------
package comjava;

import java.math.BigDecimal;


/**
 * Test3Id entity. @author MyEclipse Persistence Tools
 */

public class Test3Id  implements java.io.Serializable {


    // Fields  

     private BigDecimal t3id;
     private BigDecimal t11fk1d;
     private BigDecimal t2fk1d;


    // Constructors

    /** default constructor */
    public Test3Id() {
    }

  
    /** full constructor */
    public Test3Id(BigDecimal t3id, BigDecimal t11fk1d, BigDecimal t2fk1d) {
        this.t3id = t3id;
        this.t11fk1d = t11fk1d;
        this.t2fk1d = t2fk1d;
    }

 
    // Property accessors

    public BigDecimal getT3id() {
        return this.t3id;
    }
  
    public void setT3id(BigDecimal t3id) {
        this.t3id = t3id;
    }

    public BigDecimal getT11fk1d() {
        return this.t11fk1d;
    }
  
    public void setT11fk1d(BigDecimal t11fk1d) {
        this.t11fk1d = t11fk1d;
    }

    public BigDecimal getT2fk1d() {
        return this.t2fk1d;
    }
  
    public void setT2fk1d(BigDecimal t2fk1d) {
        this.t2fk1d = t2fk1d;
    }
 }


if u want to integrate spring with the ibernate project

the spring configuration will look like this

springConfig.xml
----------------

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation" value="file:src/hibernate.cfg.xml">
        </property>
    </bean>
</beans>

web service client

public static void main(String args){
String url="http;//localhost:9080/offer/axis/personWS?wsdl";
Service service=new service();
try{
Call cal=(Call) service.createCall();
call.setTargetEndPointAddress(url);

QName qn=new QName(url,"addPerson");
call.setOperationName(qn);
call.registerTypemapping(person.class,qn,
new BeanSerializerFactory(test.class,qn),
new BeanDeserializerFactory(test.class,qn));

// creation a person object

test vo=new test();

vo.setFirstName("FirstName");
vo.setMiddleName("Middlename");

call.invoke();




}catch(ServiceException e){
e.printStracktrace();
}catch(RemoteException e){
e.printStracktrace();
}


}

Ahead of his time, Tagore left a legacy for world

Rabindranath Tagore (1861-1941), the first Asian author to have won the Nobel Prize in literature, still remains an inspiration around the world. A poet, playwright, performer, musician, essayist, philosopher, and one of the finest storytellers from India (eight novels, four novellas and numerous short stories), he also had over 2,000 paintings and doodles to his credit.
As he said in his first talk at Shanghai in 1924: 'I say that a poet's mission is to attract the voice which is yet inaudible in the air; to inspire faith in the dream which is unfulfilled; to bring the earliest tidings of the unborn flower to a sceptic world.'
That Tagore was able to give voice to the voiceless from among the colonised and subjugated nations is history now. But his legacy still lives on because, as Mahatma Gandhi had once said about him: 'In common with thousands of his countrymen I owe much to one who by his poetic genius and singular purity of life has raised India in the estimation of the world.'
It was not that he advocated a narrow definition of 'nationalism' to equate it with 'nationism', but he wanted to keep the idea of Asia and a spirit of universalism that emerged from this continent alive and foregrounded this idea.
For Tagore, the immense beauty that a localised vernacular language had to offer in the form of the best of poetry and writings that he churned out throughout his life, and the local knowledge bases that were created over centuries and millennia had very special positions.
The youngest of many children, Tagore was born into a Kolkata aristocrat family to Debendranath and Sarada Devi. He had de-schooled himself as a young child. Yet before him, nobody seemed to have thought about Complete Education as he did in the early 20th century.
In his model of teaching, the school would provide a learning opportunity where there is a communion between man and nature, between liberal and the performing arts. That education did not mean 'rote' learning, memorisation and reproduction is clear from his opening paragraphs of the book titled 'Visva -Bharati': 'The education that encourages repetition is not the education of the mind, because that can be taken care of even mechanically!'.
When Tagore started his school in Santinketan in 1901, he had wanted to include girls as well, but it did not prove practical until 1909, when a further blow to the traditional image of his Brahmacharyashram occurred with the admission of six girl students who were not put in separate classes but rather along with the boys in classes, sports and elsewhere -- a radical idea then.
He faced the death of his closest relatives one after the other but these could not deter him from creating the finest writings, music, theatre, and paintings for his legacy.
Tagore's literary contributions created a large following among Bengali and foreign readers by the beginning of the 20th century, and he published by then such works as 'Naivedya' (1901) and 'Kheya' (1906) - culminating with 'Gitanjali: Song Offerings' in 1912 that helped him win the Nobel Prize a year later. Talking about the charm of 'Gitanjali', W.B. Yeats wrote: 'These prose translations have stirred my blood as nothing has for years.'
Tagore was a widely travelled man and had himself said about his fascination for travel. 'I am a wayfarer of the endless road' - starting with his first trip to the Himalayas in 1873 with his father, and then on to numerous countries all around the world. The journey to Kolkata from Santiniketan in 1941 came immediately after his stirring address titled 'Crisis in Civilization' where Tagore observed the darkening clouds of war and destruction gather over the world.
Bengali theatre of the 19th century, which emerged as a product of Bengal Renaissance, was a colonial phenomenon and largely urban in nature, but it was completely revolutionised by Tagore through his numerous plays as well as dance-dramas. English theatre in those days mainly catered to the local British residents.
Tagore had created a new universe of theatre by bringing in a rare combination of traditional musical theatre ('Jatra'), didactic story-telling tradition ('kathakata'), singing of bards ('Kabigan') and folk-epic narratives ('panchali').
In that sense, with him, modern theatre was born in India, without aping the Western stage.
In addition, he created a truly large and varied body of music (over 2,230 songs) in 64 years between 1877 and 1941, where he brought in a rare fusion between the folk and the Indian classical, the traditional devotional songs with the western choir and church music, thus bringing in a rare convergence between the north Indian Hindustani tradition and the southern Karnataki tradition.
Tagore's legacy is not a simple case of a poet being remembered for some memorable lines. He was a model of a person who had all the wisdoms of the past, and yet was a modernist to the core - making a beginning in several endeavours that he had undertaken in each field he traversed. Even when he experimented with religious thinking and practices, his mission was 'divinisation of man and the humanising of god'.
This was the reason he adopted a lot of wisdom from ancient Hindu thoughts as well as from Buddhism and Christianity. His reading and commentaries on all religious texts and thoughts have given rise to many important philosophical and ethical questions.
Said Martin Kampchen, a German specialist of Tagore: 'Creative writers like Tagore do not merely produce works of art, but they also create a new art of living which translates, as closely as possible, the essence of their creative impulses into a social context.'
(08.05.2010 - Udaya Narayana singh is a linguist by profession, and is currently the Director & Tagore Research Chair, Rabindra Bhavana, Visva Bharati, Santiniketan, and is himself an accomplished poet, playwright and essayist. He can be contacted at unsciil@yahoo.com)