so i'm trying to remove synch problems across multiple threads and i've seen two ways of doing it:
from my understanding, example 2 doesn't always stop the function from creating two objects if two threads enter the function at the "same" time. is one method better then the other or is there an even better way of doing it? (java btw)
Code:
//
// this one uses a static method and object
//
public class Singleton
{
private static Singleton instance = new Singleton();
private Singleton()
{
//...
}
public static Singleton getInstance()
{
return instance;
}
}
// this one uses a static method and object
//
public class Singleton
{
private static Singleton instance = new Singleton();
private Singleton()
{
//...
}
public static Singleton getInstance()
{
return instance;
}
}
Code:
//
// this one attempts to synchronize getInstance()
//
public class Singleton
{
private static Singleton instance;
private Singleton()
{
// ...
}
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class)
{
instance = new Singleton();
}
}
return instance;
}
}
// this one attempts to synchronize getInstance()
//
public class Singleton
{
private static Singleton instance;
private Singleton()
{
// ...
}
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class)
{
instance = new Singleton();
}
}
return instance;
}
}
from my understanding, example 2 doesn't always stop the function from creating two objects if two threads enter the function at the "same" time. is one method better then the other or is there an even better way of doing it? (java btw)