让我们采用一个线程安全类,例如LinkedBlockingDeque
:
BlockingQueue<Task> taskQueue = new LinkedBlockingDeque<Task>();
我知道像 take
和 put
这样的操作是线程安全的,因此它们尊重之前发生的关系。
但是如果我想组合一些操作以使其原子化怎么办? 像这样:
if(taskQueue.size() == 1) {
/*Do a lot of things here, but I do not want other threads
to change the size of the queue here with take or put*/
}
//taskQueue.size() must still be equal to 1
如果它是一个非线程安全的类,我可以这样做:
synchronized(taskQueue) {
if(taskQueue.size() == 1) {
/*Do a lot of things here, but I do not want other threads
to change the size of the queue here with take or put*/
}
//taskQueue.size() must still be equal to 1
}
但事情没那么简单,我不认为take
和put
的实现使用了对象锁。
你如何处理这个扫描?
最佳答案
How do you handle this scenario?
一般来说,如果不使用某种外部锁定,就无法对并发数据结构进行“组合”操作。当您这样做时,您会重新引入您试图通过使用并发数据结构来避免的并发瓶颈。
在这种情况下,你是对的。 LinkedBlockingDeque
类使用私有(private)锁对象进行同步等。
关于java - 如何编写线程安全操作并使它们原子化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30965096/