我必須使用執行緒將記錄保存到 H2 資料庫。
這是我的資料庫類中用于將類別(具有名稱和描述的類)保存到資料庫中的方法:
public static void saveNewCategory(Category newCategory, Connection connection){
try {
String sql = "INSERT INTO CATEGORY(NAME, DESCRIPTION) VALUES(?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, newCategory.getName());
ps.setString(2, newCategory.getDescription());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
這是我的執行緒類,它應該實作該原理并使用執行緒將其保存到資料庫中
public class SaveCategoryThread implements Runnable{
private static Connection connectToDatabase;
private Category category;
public SaveCategoryThread(Category categoryC) {
category=categoryC;
}
@Override
public void run() {
try {
openConnectionWithDatabase();
Database.saveNewCategory(category,connectToDatabase);
} catch (IOException | SQLException e) {
e.printStackTrace();
} finally {
closeConnectionWithDatabase();
}
}
public synchronized void openConnectionWithDatabase() throws IOException, SQLException {
if (Database.activeConnectionWithDatabase) {
try {
wait();
System.out.println("Connection is busy");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
connectToDatabase = Database.connectToDatabase();
}
public synchronized void closeConnectionWithDatabase() {
try {
Database.disconnectFromDatabase(connectToDatabase);
} catch (SQLException ex) {
ex.printStackTrace();
}
notifyAll();
}
}
這就是我在接受用戶輸入的 JavaFX 類中執行它的方式
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new SaveCategoryThread(category));
但它不起作用,沒有錯誤或任何東西,但結果沒有保存到資料庫中。
uj5u.com熱心網友回復:
我認為問題在于wait/notifyAll代碼。
您正在等待/通知this。在這種情況下,這將是Runnable您提交給ExecutorService. 它們都是不同的物件。所以notifyAll通知將不會到達Runnable正在等待的物件。
但我認為我應該指出,您在這里嘗試實施的策略(基本上)是錯誤的。看起來您正在嘗試使用一個資料庫連接并在多個執行緒之間共享它。實際上,所有資料庫 INSERT 操作都是單執行緒的;即在資料庫操作中沒有并行性。
如果您需要并行性,請使用由現成的 JDBC 連接池管理的多個連接。這也將避免為每個 INSERT 打開和關閉資料庫連接的開銷......就像您當前的實作可能正在做的那樣。(我們看不到相關代碼。)
但是,如果您想要良好的插入性能,請不要執行包含單個 INSERT 陳述句的事務。而是使用 JDBC 的批處理機制或多行 INSERT 陳述句。
uj5u.com熱心網友回復:
DataSource
我同意Stephen C 的回答,除了提倡使用連接池的部分。恕我直言,對連接池的需求通常被超賣,風險/問題被低估了。至于他的主要觀點,我同意:您可能會在嘗試共享Connection物件時遇到麻煩。我剛看到就很擔心static Connection,因為應該沒有必要Connection通過 a 來保持 a static。
與其專注于傳遞一個Connection物件,我建議你改為傳遞一個DataSource物件。ADataSource包含連接到資料庫所需的所有資訊。或者,如果您決定使用連接池,則DataSource物件可以是訪問該池的前門。無論哪種方式,使用 aDataSource都很簡單,因為它主要由方法組成getConnection,回傳一個Connection物件。
DataSource您可以使用資料庫資訊(例如資料庫服務器地址、資料庫用戶名和密碼等)對物件進行硬編碼。或者,您可以將這些細節外部化,以便管理員在運行時在目錄/命名服務(如LDAP服務器)或Jakarta EE服務器中進行配置。使用Java 中的JNDI獲取外部化DataSource物件。
例如,對于H2 資料庫引擎DataSource,使用,的捆綁實作org.h2.jdbcx.JdbcDataSource。這是一些代碼,顯示了如何對DataSource資訊進行硬編碼。
public javax.sql.DataSource configureDataSource() {
org.h2.jdbcx.JdbcDataSource ds = Objects.requireNonNull( new JdbcDataSource() ); // Implementation of `DataSource` bundled with H2.
ds.setURL( "jdbc:h2:/path/to/database_file;" );
ds.setUser( "scott" );
ds.setPassword( "tiger" );
ds.setDescription( "An example database showing how to use DataSource." );
return ds ;
}
保留該DataSource物件以供以后使用。該物件僅保存連接資訊(或對連接池的訪問)。傳遞給您的 JDBC 代碼。
順便說一句,給您一個大提示:使用try-with-resources語法自動關閉您的資源,例如Connection、Statement和ResultSet.
我還建議養成使用分號 ( ;) 正確終止 SQL 陳述句的習慣。
添加第二個catch,除此之外SQLException,更具體的例外也是由DataSource#getConnection:引發的SQLTimeoutException。setLoginTimeout此例外適用于驅動程式確定已超出方法指定的超時值時。
public void saveNewCategory( Category newCategory, DataSource ds ){
String sql = "INSERT INTO CATEGORY( NAME, DESCRIPTION ) VALUES( ?, ? ) ;";
try (
Connection conn = ds.getConnection() ;
PreparedStatement ps = conn.prepareStatement( sql );
) {
ps.setString( 1, newCategory.getName() );
ps.setString( 2, newCategory.getDescription() );
ps.executeUpdate();
} catch ( SQLTimeoutException e ) {
…
} catch ( SQLException e ) {
…
}
}
請注意,在上面的代碼中,如果成功打開了Connection和物件, try-with-resources 語法將如何自動關閉它們。PreparedStatement我們不想讓該Connection物件保持打開狀態超過必要的時間。
執行服務
As for using concurrency with threads, using a DataSource probably simplifies your code significantly.
Early on, define a ExecutorService object, and keep it around. If you want a single task to be executed at a time, use a single-threaded service. If you want concurrent tasks, use a service backed by a pool of threads.
Either way, use Executors utility class to obtain a ExecutorService as seen in your code. Keep this ExecutorService object around, for repeated use.
ExecutorService executorService = Executors.newCachedThreadPool();
…
When you are ready to persist one of your Category objects, define a task and pass to the executor service. As your code shows, the task is defined as a Runnable or a Callable.
But the name SaveCategoryThread you chose for your Runnable task suggests you are thinking about managing threads. That is not what a Runnable is about. The Runnable is the work to be done, without regard for threads. A Runnable can be executed on the same thread, as is appropriate to some situations. So the Runnable is not in charge of threads. Managing threads is the job of the ExecutorService.
public class SaveNewCategoryTask implements Runnable {
// Member fields.
DataSource dataSource;
Category newCategory ;
// Constructor
public SaveNewCategoryTask ( Category newCategory , DataSource dataSource ) {
this.newCategory = newCategory ; // Remember the passed argument.
this.dataSource = dataSource ; // Remember the passed argument.
}
@Override
public void run() {
saveNewCategory( this.newCategory , this.dataSource ) ;
}
}
Notice how our Runnable is no longer tracking connections or exceptions. All the database exchange details are contained within the saveNewCategory method. It is generally best to keep the Runnable task class as simple as possible. Its job is to simply hold info until needed, when its run method is eventually executed.
Usage:
// Retrieve that `DataSource` object you established early on in your app’s lifecycle.
DataSource ds = … retrieve existing object … ;
// Retrieve the `ExecutorService` object you established early on in your app’s lifecycle.
ExecutorService es = … retrieve existing object … ;
es.submit( new SaveNewCategoryTask( newCategory , ds ) ) ;
I am not entirely sure of your intent with using wait and notifyAll. It seems you are trying to manage simultaneous access to a single Connection object. As Stephen C explains in other Answer, that is basically a wrong approach, fraught with peril. Hopefully I have shown that such an approach is also unnecessary and needlessly complicated.
JavaFX
All the above discussion was aimed at Java in general.
But you mentioned JavaFX. JavaFX has its own concurrency utilities. I am not familiar with those. Hopefully the above code helps establish some general concepts and guidelines, but you may need to modify to work properly with JavaFX.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/422241.html
標籤:
下一篇:帶有期望的事務注釋
