即使有自己的连接也会阻塞线程

时间:2019-05-15 12:49:23

标签: java multithreading

我正在使用多线程进行一些数据库操作。我为此使用executorservice和线程池。问题是,由于我在每个班级上都移开了我的联系(使它们成为私有的,因此对于每个任务都是独立的),我的线程陷入了困境。令人惊讶的是,这种情况只发生过几次。说,如果我执行10次程序,此问题将出现2或3次。

我尝试使用jstack生成线程转储,但是我的计算机上没有管理员访问权限,因此无济于事。 我已通过jprofiler确认,只要出现此类问题(程序无法正常结束时),线程就会被阻塞。 Jprofiler显示我的两个线程与两个系统线程一起被阻塞(其中一个是连接的东西)。

在主要方法中,这是我创建任务的方式:

for(int fileNum = 0; fileNum < num_of_tasks; fileNum++)
            {
                Callable<Object> callable = new WriteTodbTransReqDataTask(fileNum);
                executor.submit(callable);          
            }

这是WriteTodbTransReqDataTask类中存在的我的调用方法。

private Connection con = null; //instance variable
public Object call() throws Exception{
        PreparedStatement  pstmt = null;
        ResultSet rs = null;

        try
        {
            con = ConnectionManager.getConnection();
            con.setAutoCommit(true);
            pstmt = con.prepareStatement("INSERT INTO trans_requests_test (trace_audit_no,card_prg_id,trans_date) VALUES (?,?,?)");
            BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\mchaudhry02\\Documents\\output" + fileNumber + ".csv"));
            String line = br.readLine();

            while (line != null) {
                String[] parameters = line.split(",");
                pstmt.setString(1, parameters[0]);
                pstmt.setString(2, parameters[1]);
                pstmt.setString(3, parameters[2]);
                pstmt.addBatch();
                line = br.readLine();
            }
            pstmt.executeBatch();
            br.close();
        }
        catch (SQLException e1) {log.error("##SQLException##",e1);}
        catch (ClassNotFoundException e1) {log.error("##ClassNotFoundException##",e1);}
        catch (IOException e1) {log.error("##IOException##",e1);}
        catch (Exception e1) {log.error("##Exception##",e1);}
        finally
        {
            try { if (rs != null) rs.close(); } catch (SQLException e1) {log.error("##SQLException##",e1);}
            try { if (pstmt != null) pstmt.close(); } catch (SQLException e1) {log.error("##SQLException##",e1);}
            try { if (con != null) con.close();System.out.println("Reached writer class");} catch (SQLException e1) {log.error("##SQLException##",e1);}
        }

        return null;
    }

为什么有时我的线程阻塞而有时却正常工作?

0 个答案:

没有答案