java - 一般synchronizedList问题
我有一个关于同步列表的一般性问题。
假设在构造函数中我正在创建一个列表
List synchronizedList = Collections.synchronizedList(list);
,并且我有一个方法将一个对象添加到列表中。
public void add(String s){
synchronizedList.add(s)
}
还有另一个线程每隔几秒检查一次是否有几行,将其转储到文件中并将其全部删除。
现在假设我迭代每一行并将其保存到数据库中。 经过所有迭代后,我清除了列表。
多线程支持对我有何帮助?
我可以在另一个线程中的clear() 发生之前将一个元素添加到列表中。
除非我自己管理锁(我真的不需要同步列表)。
I have a general question regarding synchronized List.
Lets say that in the constructor I am createing a list
List synchronizedList = Collections.synchronizedList(list);
and I have one method adds an object to the list.
public void add(String s){
synchronizedList.add(s)
}
There is another thread that checks every few seconds if there are a few rows , dump it to a file and deletes them all.
Now lets say I iterate each row and save it to the db.
after all iteration I clear the list.
How does the multithread support help me?
I could add an element to the list just before the clear() in the other thread occurs .
Unless I manage the lock myself (which I dont realy need a synched list for that ) it myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Collections
返回的同步列表对您的情况没有帮助。仅当您需要保证对各个方法调用的串行访问时,它才有用。如果您需要同步一组更大的操作,那么您需要手动将该代码包装在synchronized
块中。 Javadoc 指出:如果您的列表在其他地方使用,您至少可以保护它免受单个方法调用的影响,否则这些方法调用将不是线程安全的。但是,如果您完全管理列表,则只需将一个
synchronized
块添加到add
方法中,并使用在迭代它时使用的相同锁。The synchronized list returned by
Collections
won't help in your case. It's only good if you need to guarantee serial access to individual method calls. If you need to synchronize around a larger set of operations, then you need to manually wrap that code in asynchronized
block. The Javadoc states:If your list is used elsewhere you can at least safeguard it from individual method calls that would otherwise not be thread-safe. If you're entirely managing the list however, you can just add a
synchronized
block to youradd
method and use the same lock that you'll use when iterating over it.synchronizedList
实际上只保证列表上的每个方法调用都是同步的。如果您需要以同步方式完成多个操作,则必须自己处理同步。顺便说一句,这在 Collections.synchronizedList的javadoc:
synchronizedList
indeed only guarantees that every method call on the list is synchronized. If you need multiple operations to be done in a synchronized way, you have to handle the synchronization yourself.BTW, this is explicitely said in the javadoc for Collections.synchronizedList :
同步列表意味着该列表上的所有操作都保证是原子的。您描述的场景需要在列表之外进行一些锁定。考虑使用信号量或制作
synchronized
块来实现监视器。看一下 java.util.concurrent 。synchronized list means that all the operations on that list are guaranteed to be atomic. The scenario you describe requires to have some locking outside the list. Consider semaphores or making
synchronized
block to implement monitors. Take a look at java.util.concurrent.