HaZe
HaZe

Reputation: 45

Not sure about Singleton

If I have a singleton class like:

public class MySingleton(){
    private static MySingleton istance;
    private int element;

    private MySingleton(){element = 10;}     

    public static MySingleton getIstance() {
        if(istance == null)
            istance = new Mysingleton();
        return istance;
    }
    public void setElement(int i ){
        element = i;
    }
    public int getElement(){
        return element;
    }
}

and I want to change element's value by calling

MySingleton.getIstance().setElement(20)

Will it change the element value for the istance? Here's an example:

... main () {
    MySingleton.getIstance().setElement(20);
    System.out.prinln(MySingleton.getIstance().getElement());
    // It displays 10, why ?

Upvotes: 1

Views: 78

Answers (3)

rbeltrand
rbeltrand

Reputation: 118

Im not sure if your code really work, how azurefrog say, make your code synchronized, and in youre line public static getIstance() { you need to set the return type.

Upvotes: -1

jack
jack

Reputation: 303

I'm not sure if your code block above was copied in or just retyped, but there were a few basic compilation issues I saw with it - when you're setting MySingleton in getInstance, you need to check capitalization. Also, your class declaration shouldn't have (parentheses). After fixing these two things and running basic main, I got 20.

This is the same as what you had - no synchronization or anything else, but on a single thread it doesn't seem necessary.

public class MySingleton{
    private static MySingleton istance;
    private int element;

    private MySingleton(){element = 10;}     

    public static MySingleton getIstance() {
        if(istance == null)
            istance = new MySingleton();
        return istance;
    }
    public void setElement(int i ){
        element = i;
    }
    public int getElement(){
        return element;
    }

    public static void main(String[] args) {
        System.out.println(MySingleton.getIstance().getElement());
        MySingleton.getIstance().setElement(20);
        System.out.println(MySingleton.getIstance().getElement());
    }

}

should have an output of

10
20

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533820

I suggest you use an enum as it is simpler and thread safe (but not your getter/setter)

public enum MySingleton() {
    INSTANCE;

    private int element = 10;

    public void setElement(int element) { this.element = element; }
    public int getElement() { return element; }
}

MySingleton.INSTANCE.setElement(20);
System.out.prinln(MySingleton.INSTANCE.getElement()); // prints 20.

Upvotes: 2

Related Questions