繁体   English   中英

List的添加方法 <String> 线程安全与否?

[英]add method of List<String> is thread safe or not?

我有一个代码,其中each thread将工作10 minutes ,它将决定我应该根据random number选择哪个表。 然后在那之后,我使用PreparedStatement对那个表执行一个SQL query 执行它之后,我需要遍历result set只有当数据有在ResultSet和添加数据List<String> colData

在这里, columnsList将包含以逗号分隔的table columns 例如-

col1, col2, col3

以下是代码-

class ReadTask implements Runnable {

    private static Random random = new SecureRandom();

    public ReadTask() {

    }    


    @Override
    public run() {
      ...

      while ( < 10 minutes) {

        double randomNumber = random.nextDouble() * 100.0;
        ReadTableConnectionInfo tableInfo = selectRandomConnection(randomNumber);

        final int id = generateRandomId(random);
        final String columnsList = getColumns(table.getColumns());
        final String selectSql = "SELECT " + columnsList + "  from " + table.getTableName() + " where id = ?";

        preparedStatement = tableStatement.get(table.getTableName()).prepareCall(selectSql);
        preparedStatement.setString(1, String.valueOf(id));

        rs = preparedStatement.executeQuery();

        List<String> colData = new ArrayList<String>(columnsList.split(",").length);
        boolean foundData = false;

        if (id >= 1 && id <= 5000) {

            if (rs.next()) {
                foundData = true;

                for (String column : columnsList.split(",")) {

                         colData.add(rs.getString(column)); 
                }
                rs.next();//this should return false or an error condition and do I need this here?
            }
        } else if (rs.next()) {
            // do some stuff
         }

        if (flagValidateData && foundData) {

        // iterate through colData map
             }
         }
       }
    }

问题陈述:-

1)是否需要在colData list上进行同步?

2)我在List<String> colData添加数据的方式是否是线程安全的?

3)在我遍历结果集并将其添加到colData string array的方式上还有其他问题吗? 鉴于此,它是一个多线程代码,因此在任何竞争条件下都很难对其进行调试。

add方法是否是多线程安全的取决于实现类。 ArrayList不是多线程安全的。 向量已同步,也可以使用Collections.synchronizedList方法包装ArrayList。

您可以像这样使任何List线程安全:

List<String> names = new ArrayList<String>(); // not thread safe
List<String> threadSafeNames = Collections.synchronizedList(names);

更好的解决方案可能是java.util.concurrent的新数据结构,例如CopyOnWriteArrayList

如果您需要同步数据,为什么不编写同步读写功能? 如果您扩展集合和列表,它们也可以同步

我母亲的小舌是德语(aut / vie),现在是3 ...;)

sync用于将数据覆盖或通过多路访问替换(如果您已同步)数据,它可能使系统崩溃(速度降低),因为:

同步意味着,只有一个对象可以处理某个部分

如果您有一个线程巫婆访问某些方法,则下一个线程必须等待,直到之前的线程完成了本节

一个好例子:使用流将数据写入单个文件,然后将一些数据写入文件或输出连接:公共同步的void write(OutputStream str,byte toSend []){...}

我通常将同步用于池技术,例如get-next-operation(列表删除,返回最后一个元素)

我厌倦了18个小时的工作;)

我只是说:

无论您要同步什么,都可以为其编写一个函数,例如

public synchronized void colData_add(final String str) // or object or whatever
{
...
}

public synchronized String colData_nextElement()
{
return colData.remove();
}

希望这个帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM