是否同步锁定结果集对象?

Rav*_*uri 2 java multithreading jdbc resultset

我正在尝试多线程结果集.我想确保每当我调用next()多个线程中的一个时,所有其他线程都被锁定.这很重要,因为如果许多线程next()同时调用该方法,这将导致跳过行.这就是我做的

public class MainClass {
    private static ResultSet rs;

    public static void main (String [] args) {

        Thread thread1  = new Thread(new Runnable() {
            @Override
            public void run() {
                runWhile();
            }});
        Thread thread2  = new Thread(new Runnable() {
            @Override
            public void run() {
                runWhile();
            }});

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.exit(0);
    }

    private static void runWhile () {
        String username = null;
        while ((username = getUsername()) != null) {
            // Use username to complete my logic 
        }
    }

    /**
     * This method locks ResultSet rs until the String username is retrieved. 
     * This prevents skipping the rows 
     * @return
     * @throws SQLException
     */
    private synchronized static String getUsername() throws SQLException {
        if(rs.next()) {
            return  rs.getString(1).trim();
        }
        else
            return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一种正确的使用方式吗synchronized?它会锁定ResutSet并确保其他线程不会干扰吗?

这是一个好方法吗?

Nat*_*hes 5

不应在线程之间共享JDBC对象.这适用于Connections,Statements和ResultSet.这里最好的情况是JDBC供应商遵循规范并进行内部锁定,以便您可以使用它,在这种情况下,所有线程仍然尝试获取相同的锁,并且只有一个可以一次进行.这比使用单个线程要慢,因为除了执行相同的工作以从数据库读取之外,管理所有线程还有额外的开销.

(由驱动程序完成的锁定可能是为了驱动程序的利益,因此提供程序不必处理因用户滥用其软件而导致的竞争条件的错误报告.它确实锁定并不一定意味着软件应该实际使用通过多个线程.)

当线程可以同时进行时,多线程工作,参见Amdahl定律.如果您有可以阅读ResultSet并使用结果来创建您提交给ExecutorService的任务的情况(正如Peter Lawrey在评论中所建议的那样)那么这将更有意义(只要这些任务可以独立工作并且不要不必互相等待.