Java中的多个锁定对象

时间:2014-11-26 20:44:06

标签: java multithreading locking

这是我的代码

private String tableName1 = "Customers_Home";
private String tableName2 = "Customers_Work";
private String tableName3 = "Customers_Away";

public void insertData(List<Object> data1, List<Object> data2, List<Object> data3) {
   //inserts data into back-end database
   insertTable1Data(tableName1, data1);
   insertTable2Data(tableName2, data2);
   insertTable3Data(tableName3, data3);
   //there are more insertTableData() calls.
}

public List<List<Object>> getData() {

   //select data from back-end database
   List<Object> table1Data = getTable1Data(tableName1);
   List<Object> table2Data = getTable2Data(tableName2);
   List<Object> table3Data = getTable3Data(tableName3);

List<List<Object>> tableData = new ArrayList<>();
tableData.addAll(table1Data);
tableData.addAll(table2Data);
tableData.addAll(table3Data);
return tableData;
}

问题: getData()有时返回空列表或不完整的值,可能导致insertData()在调用getData()之前没有完成,这是一个线程问题,所以我做了,在insertData()和getData()中使用了Lock

public void insertData(List<Object> data1, List<Object> data2, List<Object> data3) {
       //inserts data into back-end database
ReadWriteLock lock1 = getLock(tableName1);//returns a ReadWriteLock from HashMap based on tableName (key).
     boolean acquired = false;
      do {
           acquired = lock1.writeLock().tryLock(5, TimeUnit.MILLISECONDS);
         } while (!acquired);
       insertTable1Data(tableName1, data1);

       ReadWriteLock lock2 = getLock(tableName2);
       acquired = false;
       do {
           acquired = lock2.writeLock().tryLock(5, TimeUnit.MILLISECONDS);
         } while (!acquired);
       insertTable2Data(tableName2, data2);
       //and a similar do while block for tableName3.
       insertTable3Data(tableName3, data3);
       //Ommitted try, catch, finally block and unlocking operation.
    }

这种方法是为每个insertTableData()操作创建一个Lock Object,但是我想为每个insertData()操作只使用一个Lock对象,如何实现呢?

有什么建议吗? 提前谢谢。

0 个答案:

没有答案