讀了ibatis的jpetstore源程式,有個關於synchronized的問題請教一下

kevinleepk發表於2005-10-29
在看jpetstore的源程式時,發現裡面有個生成序列號dao實現類,透過名稱找到當前資料庫中該類別的序列號,將取出的序列號加1並更新到資料庫中,同時返回加1前的序列號,這個方法名前有個synchronized關鍵字。請問如果在真實環境下采用這種方法會不會有問題?是否需要將該方法定義為static方法?或對該類採用singleton的模式?


程式碼如下

/**
* User: Clinton Begin
* Date: Jul 13, 2003
* Time: 7:21:30 PM
*/
package com.ibatis.jpetstore.persistence.sqlmapdao;

import com.ibatis.dao.client.DaoException;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.jpetstore.domain.Sequence;
import com.ibatis.jpetstore.persistence.iface.SequenceDao;

public class SequenceSqlMapDao extends BaseSqlMapDao implements SequenceDao {

public SequenceSqlMapDao(DaoManager daoManager) {
super(daoManager);
}

/**
* This is a generic sequence ID generator that is based on a database
* table called 'SEQUENCE', which contains two columns (NAME, NEXTID).
* <p/>
* This approach should work with any database.
*
* @param name The name of the sequence.
* @return The Next ID
* @
*/
public synchronized int getNextId(String name) {
Sequence sequence = new Sequence(name, -1);

sequence = (Sequence) queryForObject("getSequence", sequence);
if (sequence == null) {
throw new DaoException("Error: A null sequence was returned from the database (could not get next " + name + " sequence).");
}
Object parameterObject = new Sequence(name, sequence.getNextId() + 1);
update("updateSequence", parameterObject);

return sequence.getNextId();
}

}

相關文章