我在使用一個使用Sqllite數據庫的多線程Java程序時遇到了這個問題。它使用文件鎖定,所以我必須確保只有一個線程在同一時間工作。
我基本結束了使用同步。當ConnectionFactory返回一個數據庫連接時,它還會返回一個鎖定對象,在使用連接時應該鎖定該對象。所以,你可以做手工同步鎖,或者創建低於該會爲你的類的子類:
/**
* Subclass this class and implement the persistInTransaction method to perform
* an update to the database.
*/
public abstract class DBOperationInTransaction {
protected Logger logger = Logger.getLogger(DBOperationInTransaction.class.getName());
public DBOperationInTransaction(ConnectionFactory connectionFactory) {
DBConnection con = null;
try {
con = connectionFactory.getConnection();
if(con == null) {
logger.log(Level.SEVERE, "Could not get db connection");
throw new RuntimException("Could not get db connection");
}
synchronized (con.activityLock) {
con.connection.setAutoCommit(false);
persistInTransaction(con.connection);
con.connection.commit();
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed to persist data:", e);
throw new RuntimeException(e);
} finally {
if(con != null) {
//Close con.connection silently.
}
}
}
/**
* Method for persisting data within a transaction. If any SQLExceptions
* occur they are logged and the transaction is rolled back.
*
* In the scope of the method there is a logger object available that any
* errors/warnings besides sqlException that you want to log.
*
* @param con
* Connection ready for use, do not do any transaction handling
* on this object.
* @throws SQLException
* Any SQL exception that your code might throw. These errors
* are logged. Any exception will rollback the transaction.
*
*/
abstract protected void persistInTransaction(Connection con) throws SQLException;
}
而DBConnection的結構:
final public class DBConnection {
public final Connection connection;
public final String activityLock;
public DBConnection(Connection connection, String activityLock) {
this.connection = connection;
this.activityLock = activityLock;
}
}
感謝答案。事情是應用程序必須非常高效,它可能運行在16個甚至32個線程上。並且每個都啓動事務,進行大量處理,然後獲取結果並在提交步驟中執行插入和更新 - 全部以jdbc批處理(用於性能)。然後交易被提交。無論如何,在我的情況下,可串行化的級別將會過多,特別是對於32個線程。我希望我能夠通過Java應用程序中的緩存來解決這個問題。 – nesvarbu 2011-02-02 17:41:52