简体   繁体   English

使非线程安全队列线程安全

[英]Making a non-thread safe queue thread safe

Say I have a queue implementation which is not thread safe. 说我有一个不是线程安全的队列实现。 How can I make it thread safe (without modifying original code)? 如何使它线程安全(不修改原始代码)? In other words: 换一种说法:

How can I write a SynchronizedQueueWrapper which is backed by a regular non-thread safe queue? 如何编写由常规的非线程安全队列支持的SynchronizedQueueWrapper?

Plus: My queue does not implement Collection interface besides add, remove, peek and size functions. 加:我的队列除了添加,删除,查看和调整大小功能外,未实现Collection接口。

If your queue implements Collection , you can simply use a Collections.synchronizedCollection(queue); 如果您的队列实现Collection ,则只需使用Collections.synchronizedCollection(queue); . Otherwise I suggest you checked the code of synchronizedCollection and did something similar (essentially: guarding all operations on the queue by a mutex on this ). 否则,我建议你检查的代码synchronizedCollection并没有类似的东西(主要有:保守队列上的所有操作由一个互斥this )。

Note that it will still require the users to properly access the synchronized queue, for example during iteration. 请注意,仍然需要用户正确访问同步队列,例如在迭代过程中。

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

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