Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Singleton is not thread safe #1

Open
Cililing opened this issue Dec 18, 2018 · 2 comments
Open

Singleton is not thread safe #1

Cililing opened this issue Dec 18, 2018 · 2 comments

Comments

@Cililing
Copy link

Cililing commented Dec 18, 2018

Hello. In your readme there is:

We'll implement the thread safe one here.

But your Singleton-class is not thread safe.

@Cililing
Copy link
Author

Cililing commented Dec 19, 2018

To be more precisely - if you try access your singleton from more than one thread you can create more than one instance of your singleton:

Let's try this slightly modified code:

`
public class SingletonXD {

private static SingletonXD instance;

private SingletonXD() {
}

public static SingletonXD getInstance() {
    if (instance == null) {
        System.out.println("Creating new instance");
        instance = new SingletonXD();
        System.out.println("New instance created");
    }
    return instance;
}

public static void main(String[] args) {

    Runnable singletonAccessRunnable = () -> {
        SingletonXD xd = SingletonXD.getInstance();
        System.out.println(xd);
    };

    for (int i = 0; i < 10; i++) {
        Thread thread = new Thread(singletonAccessRunnable);
        thread.start();
    }

}

}
`

For most of the time my output is OK: First there is a message "Creating new instance", then "New instance created", and all objects have the same hashcode.

But, sometimes, output is like:
'
Creating new instance
New instance created
SingletonXD@2e00fa9
SingletonXD@2e00fa9
SingletonXD@2e00fa9
SingletonXD@2e00fa9
SingletonXD@2e00fa9
SingletonXD@2e00fa9
SingletonXD@2e00fa9
SingletonXD@2e00fa9
Creating new instance
New instance created
SingletonXD@7b111699
SingletonXD@2e00fa9
'

As you can see, one of the threads created his own instance - this can lead to very unexcpected behaviours.

@mohamedebrahim96
Copy link
Member

yes you are right
but ..
how can we avoid it ?
ammm maybe using Dagger2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants