CrazyEngineers
  • Write a Program for a Singleton Class

    sookie

    sookie

    @sookie-T06sFW
    Updated: Oct 21, 2024
    Views: 1.3K
    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.
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Sahithi Pallavi

    MemberJul 22, 2012

    #-Link-Snipped-# - No idea. Explanation please.

    PS : Sorry for bumping the old thread but I want answer.
    Are you sure? This action cannot be undone.
    Cancel
  • Anoop Kumar

    MemberJul 22, 2012

    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();
        }
       
    }
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register