单例虽然没有缓存写的那么平凡,如果在getinstance方法上加sychonize会大大影响性能,单例的写只有在第一使用时才会写。
使用读写锁操作,基本上都上的读锁,对其他线程访问没有影响
public class Singleton
{
private static Singleton instance = null;
private static ReadWriteLock rwl = new ReentrantReadWriteLock();
private Singleton(){
}
public static Singleton getInstance(){
rwl.readLock().lock();
try
{
if (null == instance)
{
rwl.readLock().unlock();
rwl.writeLock().lock();
if (null == instance)
{
instance = new Singleton();
}
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
finally
{
rwl.readLock().unlock();
}
return instance;
}
public void hello(){
System.out.println("hello");
}
}