import java.util.ArrayList;
import java.util.Random;
class Singleton
{
/**
* Singleton
*
*/
@SuppressWarnings("finally")
public static boolean Init()
{
boolean bRet = false;
try
{
synchronized(Singleton.class)
{
if( null == m_pSingleton)
{
m_pSingleton = new Singleton();
bRet = true;
}
}
}
catch (Exception e)
{
System.out.println("Singleton Init, catch exception");
m_pSingleton = null;
throw e;
}
finally
{
return bRet;
}
}
public static void UnInit()
{
synchronized(Singleton.class)
{
if( null != m_pSingleton)
{//释放空闲资源
m_pSingleton = null;
}
}
}
public static Singleton GetInstance()
{
synchronized(Singleton.class)
{
return m_pSingleton;
}
}
public void doSomething()
{}
private Singleton()
{}
private static Singleton m_pSingleton = null;
}
class MultiObj
{
private static final int SIZE_OBJ = 4;
private static ArrayList<MultiObj> m_vpTcpIp = null;
@SuppressWarnings("finally")
public static boolean Init()
{
boolean bRet = false;
try
{
synchronized(Singleton.class)
{
if( null == m_vpTcpIp)
{
m_vpTcpIp = new ArrayList<MultiObj>();
for(int i=0; i<SIZE_OBJ; i++)
{
MultiObj pMultiObj = new MultiObj(i);
m_vpTcpIp.add(pMultiObj);
pMultiObj = null;
}
bRet = true;
}
}
}
catch (Exception e)
{
System.out.println("Singleton Init, catch exception");
m_vpTcpIp = null;
throw e;
}
finally
{
return bRet;
}
}
public static void UnInit()
{
synchronized(Singleton.class)
{
if( null != m_vpTcpIp)
{//释放空闲资源
m_vpTcpIp.clear();
m_vpTcpIp = null;
}
}
}
public static MultiObj GetInstance()
{
Random pRandom = new Random();
MultiObj pMultiObj = m_vpTcpIp.get(pRandom.nextInt(SIZE_OBJ));
pRandom = null;
return pMultiObj;
}
public MultiObj(int i)
{
m_iID = i;
System.out.println("MultiObj");
}
void doSomething()
{
System.out.println(m_iID);
};
private int m_iID;
}
//---------------------------------------------------
class SingletonClient
{
public static void Client()
{
MultiObj.Init();
for(int i=0; i<20; i++)
{
MultiObj pMultiObj = MultiObj.GetInstance();
pMultiObj.doSomething();
pMultiObj = null;
}
MultiObj.UnInit();
}
}