简体   繁体   中英

Passing an Iterator to a thread in Java

Given the following code snippet that fetches records from a Cassandra database :

QueryResult<OrderedRows<String, String, String>> result = rangeSlicesQuery.execute();
OrderedRows<String, String, String> rows = result.get();
Iterator<Row<String, String, String>> rowsIterator = rows.iterator();

If I put the rowsIterator object on a Queue defined as :

BlockingQueue<Iterator<Row<String, String, String>>> queue = 
    new PriorityBlockingQueue<Iterator<Row<String, String, String>>>();

Now, if I have a thread that reads from this queue, will I be able to fetch the iterator from the queue and iterate over the OrderRows in this thread?

In other words, can iterators created in one thread be passed to a second thread such that the second thread can iterate over the original collection for which the iterator was created in the first thread?

Briefly, yes. It's just an object referencing your collection.

I would perhaps be wary of this. Having an iterator used in one thread presumably means that you can modify your collection in the other thread, and you run the risk of concurrent modifications unless you're careful. Perhaps iterate over a copy of your original collection ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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