简体   繁体   English

将Iterator传递给Java中的线程

[英]Passing an Iterator to a thread in Java

Given the following code snippet that fetches records from a Cassandra database : 给出以下从Cassandra数据库中提取记录的代码片段:

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 : 如果我将rowsIterator对象放在Queue上,定义如下:

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? 现在,如果我有一个从该队列读取的线程,我是否能够从队列中获取迭代器并迭代此线程中的OrderRows?

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 ? 也许迭代原始集合的副本?

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

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