[code="java"]
/*
import java.util.BitSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
/**
@author ATracer
*/
public class IdFactory
{
private final BitSet idList = new BitSet();
private final ReentrantLock lock = new ReentrantLock();
private AtomicInteger nextMinId = new AtomicInteger(1);
protected static IdFactory instance = new IdFactory();
public int nextId()
{
try
{
lock.lock();
int id = idList.nextClearBit(nextMinId.intValue());
idList.set(id);
nextMinId.incrementAndGet();
return id;
}
finally
{
lock.unlock();
}
}
public static IdFactory getInstance()
{
return instance;
}
public static void main(String[] xiaoe)
{
BitSet idList = new BitSet();
for (int i = 0; i < 100; i++)
System.out.println(idList.nextClearBit(i));
}
}
[/code]
我觉得有两个问题:
1. 这里既然已经用锁同步了,就可以不用atomic类
2. BitSet有点画蛇添足的味道
不知道作者为何要这么设计,求解。谁能指点下这么写的好处。
[code="java"]public class IdFactory {
private final ReentrantLock lock = new ReentrantLock();
private volatile int id = 0;
private static final IdFactory instance = new IdFactory();
private IdFactory() {
}
public int nextId() {
try {
lock.lock();
id++;
return id;
} finally {
lock.unlock();
}
}
public static IdFactory getInstance() {
return instance;
}
static class TestThread extends Thread {
ArrayList<Integer> idList = new ArrayList<Integer>();
public void run() {
IdFactory fac = IdFactory.getInstance();
for (int i = 0; i < 10000; i++) {
idList.add(fac.nextId());
}
}
}
public static void main(String[] arg) throws Exception {
TestThread t1 = new TestThread();
TestThread t2 = new TestThread();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(t1.idList.size());
System.out.println(t2.idList.size());
t1.idList.removeAll(t2.idList);
System.out.println(t1.idList.size());
System.out.println(t2.idList.size());
}
}[/code]
我这样写,效果应该一样吧!
1.AtomicXXX类保证的只是是compare-and-swap的原子性
2.这里使用BitSet是为了避免使用Integer或者BigInteger来表示id,这样的话id就可以无限增大下去
看起来貌似很蛋疼,还是依据自己的需求写一个吧。
可能他这样写是为了迎合特定的需要