AKIWEB
AKIWEB

Reputation: 19612

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

I have a code in which each thread will work for 10 minutes and it will decide which table I am supposed to pick basis on random number. And then after that I am executing a SQL query for that table using PreparedStatement. After executing it, I need to loop through the result set only if the data is there in the ResultSet and add the data in List<String> colData.

Here columnsList will contains table columns delimited by comma. For example-

col1, col2, col3

Below is the code-

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
             }
         }
       }
    }

Problem Statement:-

1) Do I need synchronization on my colData list or not?

2) Whether the way I am add the data in List<String> colData is thread safe or not?

3) And is there any other problem in the way I am looping through the result set and adding it to colData string array? As given that, its a Multithreaded code, so it will be hard to debug it out for any race conditions.

Upvotes: 0

Views: 2863

Answers (3)

duffymo
duffymo

Reputation: 308763

You can make any List thread safe like this:

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

A better solution might be a new data structure from java.util.concurrent, like CopyOnWriteArrayList.

Upvotes: 2

user1753144
user1753144

Reputation: 1

if you need synchronized data, why don't you write a synchronized read- and write function? also collections and lists can be synchronyzed, if you extend them

my mother's tounge is german (aut/vie) and it's 3... ;)

sync is used where data can be overwritten or replaced by multiple access if you got something in sync, it can brake your system out (speeding down) cuz:

sync means, that only one object can handle some section

if you had an thread witch access some method, the next thread MUST wait until the thread before is finished with the section

a good example: writing data to a single file using streams and write some data to the file or output-connect: public synchronized void write(OutputStream str, byte toSend[]){...}

i usaly use synchronized for pool-techniques, such as get-next-operation (list-removal, return last element)

im tired of 18 hours of work ;)

i just say:

whatever you have to sync, write a function for it e.g.

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

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

hope this helpz

Upvotes: 0

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Whether the add method is multi-thread safe depends on the implementing class. ArrayList is not multi-thread safe. Vector is synchronized, or you can wrap an ArrayList using the Collections.synchronizedList method.

Upvotes: 3

Related Questions