我需要插入有两列的数据库 -
ID Primary Key String
Data String
所以这意味着ID每次都应该是唯一的,否则duplicate row in unique index
插入时会抛出异常。我需要在这个范围内选择 ID1-100000
所以这意味着每个线程应该始终使用唯一的 id-
下面是我编写的多线程程序,每次从ArrayBlockingQueue
.
那么这个程序是否是线程安全的?或者有没有其他更好的方法来每次为每个线程获取唯一 ID?或者下面的程序会导致duplicate row in unique index
?
private static LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
public static void main(String[] args) {
for (int i = 1; i <= 100000; i++) {
availableExistingIds.add(i);
}
BlockingQueue<Integer> pool = new ArrayBlockingQueue<Integer>(200000, false, availableExistingIds);
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < noOfTasks * noOfThreads; i++) {
service.submit(new ThreadTask(pool));
}
}
class ThreadTask implements Runnable {
private BlockingQueue<Integer> pool;
private int id;
public ThreadTask(BlockingQueue<Integer> pool) {
this.pool = pool;
}
@Override
public void run() {
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(INSERT_SQL);
id = pool.take();
preparedStatement.setString(1, String.valueOf(id));
preparedStatement.setString(2, ACCOUNT);
preparedStatement.executeUpdate();
} finally {
pool.offer(id);
}
}
}