Is the singleton class single in threads?

I have a class designed by singleton pattern.
I use this in many threads in one VM.
I found every thread had a different instance.
Why?
And if I want to share information with different
threads,how can I apply singleton in this context?

I know why!
In my singleton class,I don't add the keyword "synchronized".
Code below:
public static MySingleton getInstance(){
if(instance == null){                       //miss the keyword "synchronized"
instance = new MySingleTon();
return instance;
So when threads call this method at the same time,
many instances created.

Similar Messages

  • (retain) properties in the singleton class

    Hi,
    What happens with the properties declared with (retain) in the singleton class:
    MyClass *foo;
    @property (nonatomic, retain) MyClass *foo;
    I am using a singleton class as explained http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFunda mentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32 which should NOT be released.
    I see no way to call
    [foo release].
    My guess is that these properties will be allocated once and persist though entire life of the singelton - which is not a leak.
    correct?

    leonbrag wrote:
    My guess is that these properties will be allocated once and persist though entire life of the singelton - which is not a leak.
    correct?
    Yes. Of course, there are still ways to get rid of singletons if you really want/had to. In some cases, you could have a singleton that allocated system resources that aren't automatically released when a program ends. There are ways to clean up such things if you run across them. Look at the "applicationWillTerminate:" notification, for example.

  • To ragnic and other about Singleton class

    Hi ragnic. Thanks for your reply. I posted the code wrong. Heres' my correct one.
    I have a GUI first loaded information and the information is stored in a databse, I have some EJB classes..and my singleton class ABC has some method to access to the EJB..
    so my first GUI will gather info using singleton class and later if I click on
    a button in my first GUI class, will pop up another frame of another class , this class also need to class setPassword in my Singleton..
    are my followign codes correctly??
    iS my Class ABC a SINgleton class? thanks
    Is my class ABC use as single correctly. And It is called from other classes is also correct?
    I'm new to java and like to learn about Singleton class.
    But I really dont' understand it clearly after reading many examples of it.
    I have a project to convert my class abc to a singleton.
    But I dont know how to do it.
    In my class(soon will become a singleton) will have few methods that later I need to use it from another class A and class B.
    I have a GUI application that first load my class A..and my class will call
    class abc(singleton) to get some information from it.
    and then in class A has a button, if I click on that button I will call SIngleton class again to update my password, in the singleton class has method calls updatePassword. But I dont know how to call a singleton from other class.
    I have my code for them below:
    1)public class ABC //attempt using a singleton
    private static ABC theABC = null;
    private ABC(){}
    public synchronized static ABC getABC()
    if(theABC == null)
    theABC= new ABC();
    return the ABC;
    public void updateUserInfo(SimpleUser user)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.updateUserInfo(user, userHome);
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    public SimpleUser getID(String id)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    SimpleUser su = uc.getID(id, userHome);
    return su;
    } catch(HomeFactoryException hfe) {
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    throw new DelegateException(re);
    } catch(CreateException ce) {
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    throw new UserNotFoundException();
    public void setPassword(String lname,String pw)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.setPassword(lname,pw, userHome);//assume that all lname are differents.
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    }//Do I have my class as a Singleton correctly???
    2)//Here is my First Frame that will call a Singleton to gather user information
    public A(Frame owner)
    super(owner, "User Personal Information",true);
    initScreen();
    loadPersonalInfo();
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen()
    txtFname = new JTextField(20);
    txtLname=new JTextField(20);
    btnsave =new JButton("Save");
    btnChange= new JButton("Click here to change PW");//when you click this button there will be a frame pop up for you to enter informaton..this iwll call class B
    JPanel pnlMain=new JPanel();
    JPanel pnlFname= new JPanel();
    pnlFname.setLayout(new BoxLayout(pnlFname, BoxLayout.X_AXIS));
    pnlFname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlFname.add(new JLabel("First Name:"));
    pnlFname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlFname.add(txtFname);
    JPanel pnlLname= new JPanel();
    pnlLname.setLayout(new BoxLayout(pnlLname, BoxLayout.X_AXIS));
    pnlLname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlLname.add(new JLabel("Last Name:"));
    pnlLname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlLname.add(txtLname);
    pnlMain.add(pnlFname);
    pnlMain.add(pnlLname);
    pnlMain.add(btnsave);
    pnlMain.add(btnChange");
    btnSave = new JButton("Save");
    btnSave.setActionCommand("SAVE");
    btnSave.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,0,0));
    pnlBottom.add(btnSave);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(500,500);
    GraphicUtilities.center(this);
    theABC=ABC.getABC();
    //Do I call my ABC singleton class correctly??
    private void loadPersonalInfo()
    String ID= System.getProperty("user.name");
    SimpleUser user = null;
    try {
    user = ABC.getID(ID);
    //I tried to use method in ABC singleton class. IS this correctly call?
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered.",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    System.exit(0);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    currentUser = user;
    txtFname.setText(currentUser.getFirstName());
    txtLname.setText(currentUser.getLastName());
    //This information will be display in my textfields Fname and Lname
    //I can change my first and last name and hit button SAVE to save
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("SAVE")) submitChanges();
    if(e.getActionCommand().equals("CHANGE_PASSWORD")) {
    changepassword=new ChangePassword(new Frame(),name,badgeid);
    public void submitChanges(){
    String currentNTUsername = System.getProperty("user.name");
    SimpleUser user =null;
    try {
    user = theABC.getID(ID);
    user.setFirstName(txtFname.getText().trim());
    user.setLastName(txtLname.getText().trim());
    currentUser = user;
    theABC.updateUserInfo(currentUser);
    //IS this correctly if I want to use this method in singleton class ABC??
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    this.setVisible(false);
    3) click on ChangePassword in my above GUI class A..will call this class B..and in this class B
    I need to access method in a Singleton class- ABC class,,DO i need to inititates it agian, if not what should I do? thanks
    package com.lockheed.vista.userinfo;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.colorchooser.*;
    import javax.swing.filechooser.*;
    import javax.accessibility.*;
    import java.beans.*;
    import java.applet.*;
    import java.net.*;
    import org.apache.log4j.*;
    import com.lockheed.common.gui.GraphicUtilities;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import vista.user.UserServicesDelegate;
    import vista.user.SimpleUser;
    import vista.user.UserNotFoundException;
    import vista.user.*;
    import com.lockheed.common.ejb.*;
    import com.lockheed.common.gui.*;
    import com.lockheed.vista.publish.*;
    * This program allow users to change their Vista Web Center's password
    public class ChangePassword extends JDialog
    implements ActionListener{
    protected final Logger log = Logger.getLogger(getClass().getName());
    private UserServicesDelegate userServicesDelegate;
    private User currentUser = null;
    private JPasswordField txtPasswd, txtVerifyPW;
    private JButton btnSubmit,btnCancel;
    private JLabel lblName,lblBadgeID;
    private String strBadgeID="";
    * This is the constructor. It creates an instance of the ChangePassword
    * and calls the method to create and build the GUI.
    public ChangePassword(Frame owner,String name,String badgeid)
    super(owner, "Change Password",true);
    initScreen(name,badgeid);//build the GUI
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen(String strname,String strBadgeid)
    txtPasswd = new JPasswordField(20);
    txtVerifyPW=new JPasswordField(20);
    txtPasswd.setEchoChar('*');
    txtVerifyPW.setEchoChar('*');
    JPanel pnlMain=new JPanel();
    pnlMain.setLayout(new BoxLayout(pnlMain, BoxLayout.Y_AXIS));
    pnlMain.setBorder(BorderFactory.createEmptyBorder(20,0,20,0));
    JPanel pnlPW=new JPanel();
    pnlPW.setLayout(new BoxLayout(pnlPW, BoxLayout.X_AXIS));
    pnlPW.setBorder(BorderFactory.createEmptyBorder(0,96,0,30));
    pnlPW.add(new JLabel("Password:"));
    pnlPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlPW.add(txtPasswd);
    JPanel pnlVerifyPW=new JPanel();
    pnlVerifyPW.setLayout(new BoxLayout(pnlVerifyPW, BoxLayout.X_AXIS));
    pnlVerifyPW.setBorder(BorderFactory.createEmptyBorder(0,63,0,30));
    pnlVerifyPW.add(new JLabel("Verify Password:"));
    pnlVerifyPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlVerifyPW.add(txtVerifyPW);
    JPanel pnlTop= new JPanel();
    pnlTop.add(pnlPW);
    pnlTop.add(Box.createRigidArea(new Dimension(0,10)));
    pnlTop.add(pnlVerifyPW);
    pnlMain.add(pnlTop);
    btnSubmit = new JButton("Submit");
    btnSubmit.setActionCommand("SUBMIT");
    btnSubmit.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,20,30));
    pnlBottom.add(btnSubmit);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(350,230);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("CANCEL")) this.setVisible(false);
    if(e.getActionCommand().equals("SUBMIT")) submitPW();
    * This method is called when the submit button is clicked. It allows user to change
    * their password.
    public void submitPW(){
    myABC= ABC.getABC();//Is this correct?
    char[] pw =txtPasswd.getPassword();
    String strPasswd="";
    for(int i=0;i<pw.length;i++){
    strPasswd=strPasswd+pw;
    char[] vpw =txtVerifyPW.getPassword();
    String strVerifyPW="";
    for(int i=0;i<vpw.length;i++){
    strVerifyPW=strVerifyPW+pw;
    if((strPasswd==null)||(strPasswd.length()==0)) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not enter a password. Please try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    if((!strPasswd.equals(strVerifyPW)))
    //password and verify password do not match.
    JOptionPane.showMessageDialog(new JDialog(),"Your passwords do not match. Reenter and try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    try
    myABC.setUserPassword(strPasswd);//try to use a method in Singleton class
    txtPasswd.setText("");
    txtVerifyPW.setText("");
    this.setVisible(false);
    } catch(DelegateException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    } catch(UserNotFoundException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    And ofcourse I have other EJB classes to work with these classes.
    ***It compiles okey but when I ran, it say "NullPointerException"
    I think I call my Singleton wrong.
    Please help me.thanks

    1. When replying, use <reply>, don't post a new topic.
    2. Implementing a singleton is a frequently asked question. Search before you post.
    3. This is not a question about Swing. A more appropriate forum would be "New To Java Technology" or perhaps "Java Programming", but see point 1.
    4. When posting code, keep it short. It increases the chance of readers looking at it. And in composing your shorter version for the forum, you just may solve your problem.

  • Singleton class within Container

    Let me extend my apologies now if this is to simple of a question for the forum.
    Here is my design issue. We are within a session bean (Stateless) and each session bean will need access to a Singleton class which possesses reference data (has a find method). This Singleton class must be static as we do not wish to replicate the amount of data involved.
    Here is my concern. Based on the fact the EJB container has created 10 session beans which must access this Singleton class and the methods within it, I "think" there will be a concurrency issue with this design.
    Can a EJB guru shade some light on this issue for me?
    Thanks in advance!

    If the the singleton class is used for multiple read and only one specific bean does a write, I dont think there should be a problem.
    However, if there are multiple read and write scenarios, then offcourse concurrency is an issue.
    What kind of data are using inside the single ton class. If you are using a hashtable or Vector inside, they take care of concurreny , as they are synchronized.
    Or else another way I could think of is
    Create a statefull session bean, instead of a java object for your singleton. Make the maximum and minimum cache size to 1.
    This will take care of the object to be singleton. And the bean would take care of the concurreny.
    Just my thoughts, am not an expert,

  • How to make Singleton Class secure

    I have a Singleton class which I instantiate using reflection by a call to a public getInstance method that return the object from a private constructor. I have to use reflection as I dont have any other options since my class instantiation is decided on runtime. How will I secure other form instantiating the same class again by using reflection on my private constructor? Any ideas?

    How much do these different implementations of your singleton have in common? What I'm getting at is, is there some common code you could extract out of them all, and make that a singleton in it's own right? Needing to do this sort of hacking is often a sign you're fudging something together, that could be solved more elegantly. We use the Singleton pattern generally when the state of the object needs to exist exactly once. Can you extract that from the disparate objects?
    The singleton classes that I load do not have anything in common. They are all similar but unique, and independant in their own respect. I will have to decide only on what singleton object I have to load in runtime, based on certain criterion. This is done by reflection, by a call to the public getInstance() method of the respective singleton classes, since I am deciding on runtime. My problem is that can I prevent others from accessing my private constructor from outside the class using reflection, which enables them to create another duplicate object. Can I restrict them to use only my getInstance() method instead?? I know this is hacking to access the private members, but I want to know whether there is any way where I can restrict this hacking???In the above code I dont want these statements to work at any case
    java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
    c[0].setAccessible(true);
    A anotherA  = (A) c[0].newInstance(new Object[]{"Duplicate"});

  • How to implement a singleton class across apps in a managed server}

    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once.
    Am i missing something here ? or did i implement it wrong..?
    public class Test
       private static Test ref ;
       private DataSource X; 
       static int Y;
       long Z ;  
       private Test ()
          // Singleton
           Z= 100 ;
       public static synchronized Test getinstance()  throws NamingException, SQLException
          if(ref == null)
             ref = new Test() ;        
             InitialContext ic = new InitialContext();
             ref.X = (DataSource)ic.lookup ("jdbc/Views");
          return ref ;       
       public Object clone()throws CloneNotSupportedException
           throw new CloneNotSupportedException();
       public int sampleMethod (int X) throws SQLException
    public final class Filter implements Filter
         public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
              try
                   Test ref = Test.getinstance();
                   log.logNow(ref.toString());
    }Edited by: Tom on Dec 8, 2010 2:45 PM
    Edited by: Tom on Dec 8, 2010 2:46 PM

    Tom wrote:
    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .Two apps = two instances.
    Basically by definition.
    >
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once. A class is loaded by a class loader.
    Any class loader that loads a class, by definition loads the class.
    A VM can have many class loaders. And far as I know every JEE server in existance that anyone uses, uses class loaders.
    And finally there might be a problem with the architecture/design of a JEE system which has two applications but which is trying to solve it with a singleton. That suggests a there might be concept problem with understanding what an "app" is in the first place.

  • How to ensure singleton classes no longer exist

    hi all not sure if this is the right forum....
    I am writting an application that integrates another, I wish to stop and then restart the integrated application but it seems that the singleton classes of which there are quite a few ( each being statically initalised) do not disappear when I try to shut them dowm. (if I am shutting them down that is ...)
    is there a way to ensure these instances are terminated so I can restart the integrated application inside my application?
    is there a way to see what instances exist so I can see if in fact I am disposing of any?
    thanks for ur help

    is there a way to ensure these instances are
    terminated so I can restart the integrated application
    inside my application?
    is there a way to see what instances exist so I can
    see if in fact I am disposing of any?
    What exactly are you trying to achieve?
    Do these hold on to resources which you must clean first? Then you must have a clean/dispose method. There is no other option. You can use a registration class to make this easier.
    Do you simply want to reinitialize them? Then you could use a class loader but it probably going to take less time to simply do the same as above and add a reinit method to each. Again you can use a registration class to make this easier.

  • Singleton Class ArrayCollection within Flashbuilder (Mobile) empty?

    Hi,
    I am currently trying to implememnt a Singleton Class in order to store a ArrayCollection of items that I can then access and manipulate across the lifecycle of my app. I have created the below Singleton Class that is designed to hold the ArrayCollection information:
    package valueObjects
        import mx.collections.ArrayCollection;   
        [Bindable]
        public class Model
            private static var instance:Model = new Model();
            public var ids:ArrayCollection = new ArrayCollection();
            public function Model()
                if(instance)
                    trace("New instance cannot be created. Use Singleton.getInstance()");
            public static function getInstance():Model
                return instance;
    I have then created the following code on the Main Deafult page for my application so that the ArrayCollection is populated as soon as the app is initiated:
                import valueObjects.Model;           
                protected var models:Model = new Model();
                            private function loop():void
                    var index:int;
                    for( index = 0; index < compsCollection.length; index++ )
                        trace( "Element " + index + " is " +  compsCollection[index].comp_id );
                                    models.ids.addItem(compsCollection[index].comp_id);
                        trace(models.ids.length);
    The ArrayCollection in the Singleton Class is being populated as the trace statement that I have entered into the loop clearly shows the build of of data in the ArrayCollection. However then when I move to another view within the application I then try to access this ArrayCollection within the Singleton Class with the following code:
    import valueObjects.Model;
    protected var models:Model = Model.getInstance();
    protected var test:ArrayCollection = new ArrayCollection();
    protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
                    var index:int;
                    trace("Array Length =" + models.ids.length);
                    for( index = 0; index < models.ids.length; index++ )
                        trace( "Element " + index + " is " + models.ids[index].comp_id );
                        test.addItem(models.ids[index].comp_id);
                    testbox.text = test.toString();
    Now the problem I am having is that when I try to access this ArrayCollection(ids) it appears to be empty for some reason. I have included a trace statement that also says that the length of the ArrayCollection is "0". Can anyone please help??

    if your value object class change this
    change this
    public var ids:ArrayCollection = new ArrayCollection();
    to
    public static var ids:ArrayCollection = new ArrayCollection();
    on your default page change this
    models.ids.addItem(compsCollection[index].comp_id);
    to
    valueObjects.Model.ids.addItem(compsCollection[index].comp_id);
    on your view change to something like this.
    protected
    function view1_viewActivateHandler():void
                   //initialize="view1_viewActivateHandler();"
                   var index:int;
                   trace("Array Length =" + valueObjects.Model.ids.length);
                   for( index = 0; index < valueObjects.Model.ids.length; index++ )
                        trace( "Element " + index + " is " + valueObjects.Model.ids[index].comp_id );
                        test.addItem(valueObjects.Model.ids[index].comp_id);
                   //testbox.text = test.toString();
    good luck let me know if you have any question i tested this and it worked like a charm for me.
    Miguel

  • Singleton class nagas

    hi,
    can any tel how to write the singleton class with full example
    for ex: for the class "Test" and how to use this in applications

    http://www.javacoffeebreak.com/articles/designpatterns/
    regards,
    Manuel Leiria

  • Assigning ThreadGroup to a Class that Extends Thread

    How can i assign a thread group to a class running as a thread that extends thread without changing the class to implement Runnable?
    An Example of the application format:
    public class Application implements Runnable
    private ThreadGroup main = new ThreadGroup("Main");
    private Thread mainThread = null;
    public Application()
    public void start()
    if (mainThread == null)
    mainThread = new Thread(main,"main")
    mainThread.start();
    public void run()
    Thread current = Thread.currentThread();
    while(current != null)
    while(something to do)
    AThread a = new AThread();
    a.start();
    String aData = a.getData();
    BThread b = new BThread(data);
    b.start();
    String bData = b.getData();
    class AThead extends Thread
    public AThread()
    //What to do with AThread to assign it to a thread group?
    public void run()
    Basically the application works form a main constructor class running the application class as a thread. The application class will then launch AThread and BThread as subthreads. I would like to be able to count how many of each type of thread is running for the AThread and BThread. I tried using AThread and BThread implementing Runnable to create a thread under a group but it wouldn't work. The application class needs to get information from the AThread and BThread threads once the thread was done, but if the AThread and BThread was implementing Runnable, the Applicaiton Class can't get the data or run methods. Is there some way i can assign what thread group AThread and BThread will run as in thier class files and not the Application class?

    See: http://java.sun.com/j2se/1.4/docs/api/java/lang/Thread.html#Thread(java.lang.ThreadGroup, java.lang.String)
    I think this does what you want:
    public class Application implements Runnable
    private ThreadGroup main = new ThreadGroup("Main");
    private ThreadGroup aThreads = new ThreadGroup("AThreads"); // Added a thread group for all AThread objects
    private Thread mainThread = null;
    public Application()
    public void start()
      if (mainThread == null)
        mainThread = new Thread(main,"main")
        mainThread.start();
      public void run()
        Thread current = Thread.currentThread();
        while(current != null)
          while(something to do)
            AThread a = new AThread(aThreads);  // Create an AThread that will belong to aThreads ThreadGroup
            a.start();
            String aData = a.getData();
            BThread b = new BThread(data);
            b.start();
            String bData = b.getData();
    class AThead extends Thread
      public AThread(ThreadGroup group)
        super(group, "AThread"); // This will make a new Thread that belongs to ThreadGroup group, see link above
      public void run()
    }

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • Gui doesn't show when the Thread is dispatched from the main class

    Hi all,
    I've tried to write a file unzipper class that shows a small frame with 2 progress bars.
    The unzipper extends Thread class in order to make it an independant service.
    However, when I debug it and use a main function that's written within the class, it works fine, and when I run it by calling it from another main, I only see a frame where the progress window should be, but no window.
    Does anyone know what I'm doing wrong? (About the GUI, I know my unzipper isn't the most efficient one:
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
    * User: Administrator
    * Date: 14/10/2005
    * Time: 18:26:47
    * This is a file Unzipper;
    * It takes a zipped archive, reads it, and decompresses the files within it
    * It is a stand alone thread since the user doesn't need to wait for it or whatever;
    * It also shows a nice progress bar gui for the user to know how the decompressing works
    public class FileUnZip extends Thread{
    private ZipEntry zipEntry;
    private ZipInputStream zipInStream;
    private FileInputStream fileInputStream;
    private int sChunk=8192;//8KB buffer size for optimized i/o performance
    private byte[] buff;
    private FileOutputStream entryOutputStream;
    private BufferedOutputStream bufferedOutputStream;
    private String sourceArchiveName;
    private String targetDirectoryName;
    private String targetFileName;// a string that stores the current zipped file in the archive
    private ZipFile zipFile;
    private int zipEntriesNum;
    private int readsNumber;//for knowing how many i/o approaches are required
    //for progress bar gui:
    private JProgressBar overAllProgBar;
    private JProgressBar currentFileProgBar;
    private JPanel progPanel;
    private JLabel overAllLabel;
    private JLabel currentFileLabel;
    private int currFileValue=0;
    private int currEntryValue=0;
    private JFrame progFrm;
    //constructor that produces the output in the same directory as source
    public FileUnZip(String sourceArchiveN) {
    sourceArchiveName = sourceArchiveN;
    targetDirectoryName=sourceArchiveName.substring(0,
    sourceArchiveName.length()-4);//trim ".zip"
    // for clean directory name
    File dir=new File (targetDirectoryName);
    dir.mkdir();
    this.start();
    //constructor that produces the output in the given targetDir... directory
    public FileUnZip(String sourceArchiveN, String targetFileN) {
    sourceArchiveName = sourceArchiveN;
    targetDirectoryName = targetFileN.substring(0,targetFileN.length()-4);
    // for clean directory name
    File dir=new File (targetDirectoryName);
    dir.mkdir();
    this.start();
    public void initGui(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    progFrm = new JFrame("Extracting " + sourceArchiveName);
    progPanel = new JPanel(new GridLayout(2,2));
    overAllLabel = new JLabel("<html><body><font size=4 color=red>Over All"+
    "</color></size><font><body><html>");
    progPanel.add(overAllLabel);
    overAllProgBar = new JProgressBar(currEntryValue, zipEntriesNum);
    overAllProgBar.setStringPainted(true);
    progPanel.add(overAllProgBar);
    currentFileProgBar = new JProgressBar(currFileValue, sChunk);
    currentFileProgBar.setStringPainted(true);
    currentFileLabel = new JLabel("<html><body>" +
    "<font size=4 color=red>Current file"+
    "</color></size><font><body><html>") ;
    progPanel.add(currentFileLabel);
    progPanel.add(currentFileProgBar);
    progFrm.getContentPane().add(progPanel);
    progFrm.pack();
    progFrm.setResizable(false);
    progFrm.setVisible(true);
    public void initStreams(){
    try {
    zipFile = new ZipFile(sourceArchiveName);
    zipEntriesNum=zipFile.size();// get entries number from the archive,
    //used for displaying the overall progressbar
    } catch (IOException e) {
    System.out.println("can't initiate zip file");
    if (zipFile!=null) {
    try {
    zipFile.close();
    } catch (IOException e) {
    System.out.println("zip file never initiated");
    try {
    fileInputStream = new FileInputStream(sourceArchiveName);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    zipInStream = new ZipInputStream(new BufferedInputStream(
    fileInputStream));
    buff=new byte[sChunk];
    public void start(){
    initStreams();
    initGui();
    run();
    public void run(){
    File outputFile;
    int succeededReading=0;
    try {
    while((zipEntry = zipInStream.getNextEntry())!=null){
    overAllProgBar.setValue(++currEntryValue);
    readsNumber=(int)zipEntry.getSize()/sChunk;
    currentFileProgBar.setMaximum(readsNumber);
    targetFileName=targetDirectoryName +
    File.separator + zipEntry.getName();
    outputFile=new File(targetFileName);
    System.out.println("outputFile.getAbsolutePath() = "
    + outputFile.getAbsolutePath());
    if(!outputFile.exists()){
    outputFile.createNewFile();
    entryOutputStream=new FileOutputStream(outputFile);
    bufferedOutputStream = new BufferedOutputStream(
    entryOutputStream, sChunk);
    while((succeededReading=zipInStream.read(
    buff,0,sChunk))!=-1){ //extract single entry
    bufferedOutputStream.write(buff,0,succeededReading);
    currentFileProgBar.setValue(++currFileValue);
    bufferedOutputStream.flush();
    bufferedOutputStream.close();
    entryOutputStream.flush();
    currFileValue = 0;
    } catch (IOException e) {
    e.printStackTrace();
    finalize();
    public void closeStreams(){
    try {
    zipInStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    try {
    fileInputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    if (entryOutputStream!=null) {
    try {
    entryOutputStream.flush();
    entryOutputStream.close();
    } catch (IOException e) {
    System.out.println("entry stream never opened");
    if(bufferedOutputStream!=null){
    try {
    bufferedOutputStream.flush();
    bufferedOutputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    public void finalize(){
    try {
    super.finalize();
    } catch (Throwable throwable) {
    throwable.printStackTrace();
    progFrm.dispose();
    closeStreams();
    endTask();
    private void endTask(){
    //play a sound when task is complete
    java.awt.Toolkit.getDefaultToolkit().beep();
    }

    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
    * User: Administrator
    * Date: 14/10/2005
    * Time: 18:26:47
    * This is a file Unzipper;
    * It takes a zipped archive, reads it, and decompresses the files within it
    * It is a stand alone thread since the user doesn't need to wait for it or whatever;
    * It also shows a nice progress bar gui for the user to know how the decompressing works
    public class FileUnZip extends Thread{
        private ZipEntry zipEntry;
        private ZipInputStream zipInStream;
        private FileInputStream fileInputStream;
        private int sChunk=8192;//8KB buffer size for optimized i/o performance
        private byte[] buff;
        private FileOutputStream entryOutputStream;
        private BufferedOutputStream bufferedOutputStream;
        private String sourceArchiveName;
        private String targetDirectoryName;
        private String targetFileName;// a string that stores the current zipped file in the archive
        private ZipFile zipFile;
        private int zipEntriesNum;
        private int readsNumber;//for knowing how many i/o approaches are required
    //for progress bar gui:
        private JProgressBar overAllProgBar;
        private JProgressBar currentFileProgBar;
        private JPanel progPanel;
        private JLabel overAllLabel;
        private JLabel currentFileLabel;
        private int currFileValue=0;
        private int currEntryValue=0;
        private JFrame progFrm;
    //constructor that produces the output in the same directory as source
        public FileUnZip(String sourceArchiveN) {
            sourceArchiveName = sourceArchiveN;
            targetDirectoryName=sourceArchiveName.substring(0,
                    sourceArchiveName.length()-4);//trim ".zip"
    // for clean directory name
            File dir=new File(targetDirectoryName);
            dir.mkdir();
            this.start();
    //constructor that produces the output in the given targetDir... directory
        public FileUnZip(String sourceArchiveN, String targetFileN) {
            sourceArchiveName = sourceArchiveN;
            targetDirectoryName = targetFileN.substring(0,targetFileN.length()-4);
    // for clean directory name
            File dir=new File(targetDirectoryName);
            dir.mkdir();
            this.start();
        public void initGui(){
            JFrame.setDefaultLookAndFeelDecorated(true);
            progFrm = new JFrame("Extracting " + sourceArchiveName);
            progPanel = new JPanel(new GridLayout(2,2));
            overAllLabel = new JLabel("<html><body><font size=4 color=red>Over All"+
                    "</color></size><font><body><html>");
            progPanel.add(overAllLabel);
            overAllProgBar = new JProgressBar(currEntryValue, zipEntriesNum);
            overAllProgBar.setStringPainted(true);
            progPanel.add(overAllProgBar);
            currentFileProgBar = new JProgressBar(currFileValue, sChunk);
            currentFileProgBar.setStringPainted(true);
            currentFileLabel = new JLabel("<html><body>" +
                    "<font size=4 color=red>Current file"+
                    "</color></size><font><body><html>") ;
            progPanel.add(currentFileLabel);
            progPanel.add(currentFileProgBar);
            progFrm.getContentPane().add(progPanel);
            progFrm.pack();
            progFrm.setResizable(false);
            progFrm.setVisible(true);
        public void initStreams(){
            try {
                zipFile = new ZipFile(sourceArchiveName);
                zipEntriesNum=zipFile.size();// get entries number from the archive,
    //used for displaying the overall progressbar
            } catch (IOException e) {
                System.out.println("can't initiate zip file");
            if (zipFile!=null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    System.out.println("zip file never initiated");
            try {
                fileInputStream = new FileInputStream(sourceArchiveName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            zipInStream = new ZipInputStream(new BufferedInputStream(
                    fileInputStream));
            buff=new byte[sChunk];
        public void start(){
            initStreams();
            initGui();
            run();
        public void run(){
            File outputFile;
            int succeededReading=0;
            try {
                while((zipEntry = zipInStream.getNextEntry())!=null){
                    overAllProgBar.setValue(++currEntryValue);
                    readsNumber=(int)zipEntry.getSize()/sChunk;
                    currentFileProgBar.setMaximum(readsNumber);
                    targetFileName=targetDirectoryName +
                            File.separator + zipEntry.getName();
                    outputFile=new File(targetFileName);
                    System.out.println("outputFile.getAbsolutePath() = "
                            + outputFile.getAbsolutePath());
                    if(!outputFile.exists()){
                        outputFile.createNewFile();
                    entryOutputStream=new FileOutputStream(outputFile);
                    bufferedOutputStream = new BufferedOutputStream(
                            entryOutputStream, sChunk);
                    while((succeededReading=zipInStream.read(
                            buff,0,sChunk))!=-1){ //extract single entry
                        bufferedOutputStream.write(buff,0,succeededReading);
                        currentFileProgBar.setValue(++currFileValue);
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                    entryOutputStream.flush();
                    currFileValue = 0;
            } catch (IOException e) {
                e.printStackTrace();
            finalize();
        public void closeStreams(){
            try {
                zipInStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            if (entryOutputStream!=null) {
                try {
                    entryOutputStream.flush();
                    entryOutputStream.close();
                } catch (IOException e) {
                    System.out.println("entry stream never opened");
            if(bufferedOutputStream!=null){
                try {
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
        public void finalize(){
            try {
                super.finalize();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            progFrm.dispose();
            closeStreams();
            endTask();
        private void endTask(){
    //play a sound when task is complete
            java.awt.Toolkit.getDefaultToolkit().beep();
    }

  • How can I kill all Threads of the same class from within the run() method?

    Ok
    I have a class called Consumer that extends Thread
    I have several Consumer threans running... but, when a certain condition is true (within the run() method) in ANY of the threads, I want to kill ALL the threads of that object.
    is this possible?

    I know this is gonna be too demanding, but can someone please tell me why my Consumer's run() method never reaches the System.out.println( "ALL CONSUMING DONE") line
    Create a multi-threaded prime number calculator that is based on the producer-consumer model
    using semaphores. Your program should be able to check for prime numbers in a range specified
    by the user and with a variable number of threads. Example:
    $ java PrimeFind 3 5000 10000
    should use 1 producer and 2 consumers (3 threads in total, obviously the minimum is 2) to find all
    the prime numbers in the range [5000,10000].
    The producer should: use a buffer to store candidate numbers that have to be checked for
    primality.
    Consumers should: read from the buffer, check if a number is prime and update the status of the
    program accordingly (e.g. show the number on the screen, or save it to a file)
    import java.util.concurrent.Semaphore;
    import java.io.*;
    public class Assign1 {
    static int fromThisNumber;
    static int toThisNumber;
    static int numberOfThreads;
    static int buffer[];
    static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                         an "OK" to the consumers*/
    static Semaphore critical;  /*This is a Mutex semaphore. It allows only 1 consumer
                                         to enter his critical section.
    static Semaphore counter;     /*This semaphore acts as a counter.
                                        Instead of having a global variable
                                         incremented each time, we just release()
                                         this semephore when we find a prime number
                                         Because remember that release() increments permits
    static Producer prod;
    static Consumer cons[];
    static int in=0;
    static int out=0;
    static PrintWriter outFile;
         public static void main (String args[]){
              try{
                   outFile=new PrintWriter(new FileWriter("primes.txt"));
                   }catch(Exception e){}
              numberOfThreads=Integer.parseInt(args[0]);
              fromThisNumber=Integer.parseInt(args[1]);
              toThisNumber=Integer.parseInt(args[2]);
              buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
              ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                      for the Producer to produce atleast a
                                                      item. Suppose ready was 1 and if
                                                      Consumer ran first he would be in an
                                                      empty buffer */
              critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                         the first Consumer thread tries
                                                         to enter its critical section, it
                                                         should be allowed to;
                                                         Subsequent threads will have to
                                                         wait since only 1 thread can
                                                         access its critical section at a time*/
              counter=new Semaphore(0,false); // duh!
              cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                                is taken by the Producer*/
              //Creating Producer object
              prod=new Producer();
              //Creating the Consumer object and start the thread.
              for(int i=0;i<cons.length;i++)
                        cons=new Consumer();
                        cons[i].start();
              prod.start();          
              //Printing to screen and file
    /*          for(int i=0;i<buffer.length;i++)
                   if(buffer[i]!=0)
                             System.out.println(buffer[i]);
                             outFile.println(buffer[i]);
              System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
              outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
              outFile.close();*/                    
    static class Producer extends Thread {
         public void run(){try{
              while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
                   {     System.out.println("producing");     
                        buffer[in]=fromThisNumber;
                        in++;
                        fromThisNumber++;
                        ready.release();
              catch (Exception e){e.printStackTrace();}
              System.out.println("ALL PRODUCING DONE");
    static class Consumer extends Thread {
         int tempout=0;
         public void run(){try{
              System.out.println("before while"+this.getId());
              while(tempout<=in)
                   System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
                   ready.acquire();
                   System.out.println("before critical.acquire"+this.getId());
                   critical.acquire();
                   tempout=out;
                   out++;
                   critical.release();               
                   if(!isPrime(buffer[tempout]))
                        {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
                   else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
                   critical.acquire();
                   tempout=out;
                   System.out.println("tempout:"+tempout+" of "+this.getId());
                   critical.release();
              System.out.println("ALL CONSUMING DONE"+this.getId());
         catch(Exception e){e.printStackTrace();}
         //Prime number-checking method     
         public boolean isPrime(int n){
              for(int i=2;i<=(n/2);i++)
                   if(n%i==0)
                        return false;
              return true;
    ======================
    import java.util.concurrent.Semaphore;
    import java.io.*;
    /* 3 questions to ask Barlas
    * Why error if I start the Consumer threads before Producer
    * Why does the counter semaphore always give a +1 result at the end
    * Is there a way I can verify that all the work is not being done by only 1 consumer thread? In other words, the workload is being shared properly
    * if I put ready.acquire() outside or inside the while loop, its not making any difference, why?
    * Strangely, its not making any difference if I playing with the release() and aquire() of the semaphores, WHY?!?!
    public class Assign1 {
    static int fromThisNumber;
    static int toThisNumber;
    static int numberOfThreads;
    static int buffer[];
    static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                       an "OK" to the consumers*/
    static Semaphore critical; /*This is a Mutex semaphore. It allows only 1 consumer
                                       to enter his critical section.
    static Semaphore counter;     /*This semaphore acts as a counter.
                                  Instead of having a global variable
                                       incremented each time, we just release()
                                       this semephore when we find a prime number
                                       Because remember that release() increments permits
    static Producer prod;
    static Consumer cons[];
    static int in=0;
    static int out=0;
    static PrintWriter outFile;
         public static void main (String args[]){
              try{
                   outFile=new PrintWriter(new FileWriter("primes.txt"));
                   }catch(Exception e){}
              numberOfThreads=Integer.parseInt(args[0]);
              fromThisNumber=Integer.parseInt(args[1]);
              toThisNumber=Integer.parseInt(args[2]);
              buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
              ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                      for the Producer to produce atleast a
                                                      item. Suppose ready was 1 and if
                                                      Consumer ran first he would be in an
                                                      empty buffer */
              critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                      the first Consumer thread tries
                                                      to enter its critical section, it
                                                      should be allowed to;
                                                      Subsequent threads will have to
                                                      wait since only 1 thread can
                                                      access its critical section at a time*/
              counter=new Semaphore(0,false); // duh!
              cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                                is taken by the Producer*/
              //Creating Producer object
              prod=new Producer();
              //Creating the Consumer object and start the thread.
              for(int i=0;i<cons.length;i++)
                        cons[i]=new Consumer();
                        cons[i].start();
              prod.start();          
              //Printing to screen and file
    /*          for(int i=0;i<buffer.length;i++)
                   if(buffer[i]!=0)
                             System.out.println(buffer[i]);
                             outFile.println(buffer[i]);
              System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
              outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
              outFile.close();*/                    
    static class Producer extends Thread {
         public void run(){try{
              while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
                   {     System.out.println("producing");     
                        buffer[in]=fromThisNumber;
                        in++;
                        fromThisNumber++;
                        ready.release();
              catch (Exception e){e.printStackTrace();}
              System.out.println("ALL PRODUCING DONE");
    static class Consumer extends Thread {
         int tempout=0;
         public void run(){try{
              System.out.println("before while"+this.getId());
              while(tempout<=in)
                   System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
                   ready.acquire();
                   System.out.println("before critical.acquire"+this.getId());
                   critical.acquire();
                   tempout=out;
                   out++;
                   critical.release();               
                   if(!isPrime(buffer[tempout]))
                        {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
                   else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
                   critical.acquire();
                   tempout=out;
                   System.out.println("tempout:"+tempout+" of "+this.getId());
                   critical.release();
              System.out.println("ALL CONSUMING DONE"+this.getId());
         catch(Exception e){e.printStackTrace();}
         //Prime number-checking method     
         public boolean isPrime(int n){
              for(int i=2;i<=(n/2);i++)
                   if(n%i==0)
                        return false;
              return true;
    ===========================
    BTW, when I tried to change extends Thread to implements Runnable I got some kinda of error.
    Actually, my program is pretty complete... its just that something if messed up in my Consumer's run() method's while loop... I think
    I know guys its crazy to ask ya'll to look at so much code, but.... I'd really appreciate it. This assignment is killing me, been at it since 10 hours now....

  • Thread: Could not generate the XML in single thread mode

    Hi all,
    I have created a report using PLSQL Procedure method after submitting the request I am getting the following Error.Couldn't sort out why I am getting the error while running the report.
    Error in "Multi threaded or single threaded execution block" of XXRX_REPORT_OUTPUT_PKG.insert_into_nested_table procedure
    ERROR :ORA-20005: Could not generate the XML in single thread mode
    XXRXERROR: XXRX_REPORT_OUTPUT_PKG.run_report SQLERROR: ORA-20005: ORA-20005: Could not generate the XML in single thread mode
    Can someone help me out finding the issue
    Thanks in Advance

    Hi,
    Please read SQL and PL/SQL FAQ
    We cannot guess what is the error if you don't post any part of your code.
    Additionally when you put some code or output please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Two threads in the same class ? Is that possible ?

    Hello, I am trying to use threads to move two images around the frame. And I am wondering if it is possible if it is possible to create two separate threads that act differently in the same class, for each of the image.
    Is just that so far I can't see a way since, by implementing Runnable, I'll need to overwrite the run() method. Which in a way just allows me to manage one image.
    Of course I can do two separate classes (each implementing Runnable) for each of the image, but since I think it may be an overkill, I rather to do it in just one.
    So, is that possible ?
    Thank you in advance.

    Of course I can do two separate classes (each implementing Runnable) for each of the image,Use two instances of the same class. Something like this example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

Maybe you are looking for

  • Autoconfiguration of Mac Mail

    I work for an isp. We are interested in automating the configuration of Mac Mail for our customers. What are the best practices to do so? It seems like Apple knows some informations about my servers, because when I enter my email address, my account

  • Two issues with latest update for Windows

    I have noticed 2 issues with the new update.  When I have a file transfer I don't want, there is no longer a cancel link.  Also, when saving a file transfer that I do want, it saved it to the default location and updated my preferences to always do t

  • Root:admin:AD Groups - What the latest deal on Mac OS X Server 2.2.1?

    Having a lot of issues with Open Directory usage in an AD Environment - Who has had success with proper AD group permissions usage. Suggestions on proper steps to get working?  We are having a lot of write errors in Shared Volumes on an external Stir

  • Default storage locations

    Is there anyway in the settings to make pictures and videos automatically save to the SD card instead of internal memory? Or is there a way to move them to the SD card?

  • Font size Elements 12 way too small - how to enlarge the font?

    Windows 8.1 and Elements 12.  The font in Elements is so small I can hardly see it, much less use it.   I've tried everything I can think of and I cannot get the font any larger.  Any ideas???   This is crazy!