Write a Program for a Singleton Class

Hi All,

I am not sure if you all know about "Singleton" class program in java or not. Well, in brief for those who don't know, it is a class that lets only one object to be created always. The basic approach being used is just making the constructor of the class as "private"
/* Singleton Program **/
class Singleton{
    private static Singleton singletonObj;

    private Singleton(){
        
    }
    public void printMe(String val){
        System.out.println("Singleton Test val="+val);
    }
    
    public static synchronized Singleton getInstance(){
        if(singletonObj==null){
            singletonObj=new Singleton();
        }
        return singletonObj;
    }
}
/* Singleton class invoking program */
public class SingletonTest {
        
    public static void main(String[] args) throws Exception{
        
        Singleton s1=Singleton.getInstance();
        s1.printMe("1");
        Singleton s2=Singleton.getInstance();
          s2.printMe("2");
    
    }
}
Now here goes my actual question, if I put a constraint to modify the above "Sinlgleton" class in such a way that the constructor access level is not "private" rather as "public" then how will you modify the "Singleton" class program so as to make below program working. It should show proper message like "Object -2 cannot be created" instead of printing output as
Singleton Test val=1
Singleton Test val=2
/* Singleton Program **/
class Singleton{
    private static Singleton singletonObj;

    [B]public [/B]Singleton(){
        
    }
    public void printMe(String val){
        System.out.println("Singleton Test val="+val);
    }
    
    public static synchronized Singleton getInstance(){
        if(singletonObj==null){
            singletonObj=new Singleton();
        }
        return singletonObj;
    }
}
/* Singleton class invoking program */
 public class SingletonTest {
         
     public static void main(String[] args) throws Exception{
         
        [B] Singleton s1=new Singleton();
        s1.printMe("1");
        Singleton s2=new Singleton();
        s2.printMe("2");[/B]
     
     }
 }
I have already given so much information in it, now just use little of Java knowledge and your brain how to handle this scenario.

Replies

  • Sahithi Pallavi
    Sahithi Pallavi
    #-Link-Snipped-# - No idea. Explanation please.

    PS : Sorry for bumping the old thread but I want answer.
  • Anoop Kumar
    Anoop Kumar
    Singleton model: Only one thread can access to the object. Unless and until it completed it's operation of that object other thread have to wait.
    -------
    In above example #-Link-Snipped-# wrote is actually synchronizing the static method since static variable is shared by all the object the whole class is now synchronized. Other way is to use synchronize all methods (if no static block is there.)
    -------------------------
    Simplest example is to create a servlet and add following code to your doPost/doGet
    for(int i=0;i<10;i++){
    system.out.println(i);
    Thread.sleep(1000);
    }
    now add following class signature to your servlet
    public class YourServlet extends HttpServlet
    implements SingleThreadModel {
    /*Your Code , (Try making variable as class member and removing/ adding SingleThreadModel  )*/
    }
    try requesting servlet from different tab/window you will see that other request have to wait until a request from one tab not completed.
    Since container only create only one object of servlet to serve the application no matter how many request are coming.
    ----------------------
    edit: Core java example

    class TestSynchronized  extends Thread {
       
        private  String ThreadName;
       
        TestSynchronized(String param){
            this.ThreadName=param;
        }
        public void run() {
            try {
                aMethod(ThreadName);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        static synchronized void aMethod(String s) throws InterruptedException{
            int i=0;
            System.out.println("ThreadName  "+s);
            while(i<10){
                System.out.println(i);
                Thread.sleep(1000);
                i++;
            }
           
           
        }
     
    }
     
    public class SynchronisedClass {
        public static void main(String []args){
          TestSynchronized t1 = new TestSynchronized("t1");   
          t1.start();
          TestSynchronized t2 = new TestSynchronized("t2");   
          t2.start();
        }
       
    }

You are reading an archived discussion.

Related Posts

The results for the above mentioned examination can be checked out at NAGPUR UNIVERSITY: RTM NAGPUR RESULTS :- POST GRADUATE DIPLOMA ENVIROMENTAL BIOTECHNOLOGY PART I SUMMER 2011 Best of luck
the results for above mentioned examination can be checking out by following link. NAGPUR UNIVERSITY: RESULTS 2011 :- FOURTH SEMESTER B.Tech. CHEMICAL ENGINEERING RTMNU SUMMER 2011 RESULTS
The results for above mentioned examination can be checked out at: NAGPUR UNIVERSITY: RESULTS 2011 :- EIGHTH SEMESTER B.Tech. CHEMICAL ENGINEERING NAGPUR UNIVERSITY All the best.
EIGHTH SEMESTER B.Tech. BIO-TECHNOLOGY NAGPUE UNIVERSITY results can be seen at NAGPUR UNIVERSITY: RESULTS 2011 :- EIGHTH SEMESTER B.Tech. BIO-TECHNOLOGY NAGPUE UNIVERSITY Best of luck
The results for the above mentioned exam can be checked out at NAGPUR UNIVERSITY: FOURTH SEMESTER B.Tech. BIO-TECHNOLOGY RESULT SUMMER 2011 NAGPUR Best of luck.