Re: Singleon class with parallel threads accessing it. will it return the same instance or seperate instances for each thread?
Posted By:
sujata_samal
Posted On:
Friday, September 30, 2005 06:04 AM
As FUTT said that depends on how do u implement the SingleTone Class..
but as per as Singletone class specification, there should be one and only one singletone object in memory.
Just have a look into the below code If a singletone object is already been created by a thread then other threads can't create more objects .
It would throw exception.
class SingleToneException extends Exception
{
public String getMessage()
{
return "Can't create more than one object";
}
}
class SingleToneTestFactory
{
private static SingleToneTestFactory singletonObject = null;
private SingleToneTestFactory(){}
public static SingleToneTestFactory getInstance()
throws SingleToneException
{
if(singletonObject == null)
singletonObject = new SingleToneTestFactory();
else
throw new SingleToneException();
return singletonObject;
}
public void display()
{
System.out.println("Inside display method");
}
}
public class SingleToneTest extends Thread
{
public static void main(String[] args) throws SingleToneException
{
Thread t = new SingleToneTest();
t.start();
Thread t1 = new SingleToneTest();
t1.start();
}
public void run()
{
try{
SingleToneTestFactory sObject = SingleToneTestFactory.getInstance();
sObject.display();
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
Thanx.
Sujata
Re: Singleon class with parallel threads accessing it. will it return the same instance or seperate instances for each thread?
Posted By:
Anonymous
Posted On:
Sunday, September 25, 2005 03:14 PM
Use a static initialiser for the Singleton class and you will have no problem.
Re: Singleon class with parallel threads accessing it. will it return the same instance or seperate instances for each thread?
Posted By:
Almagest_FUTT
Posted On:
Monday, September 19, 2005 01:48 AM
How (speaking of code) do you intend to implement it ?