使用与线程安全集合同步? [英] Using Synchronized with Thread-Safe Collection?

查看:93
本文介绍了使用与线程安全集合同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

    private ConcurrentHashMap<Integer, Book> shelf;

    public Library(ConcurrentHashMap<Integer, Book> shelf){         
        this.shelf = new ConcurrentHashMap<Integer, Book>(shelf);       
    }

鉴于我正在使用线程安全集合,是否可以使用以下方法,还是需要担心线程安全?

Given that I'm using a thread safe collection would the following method be okay to use or do I need to worry about thread safety?

    public void addBook(int index, Book add){
        shelf.put(index, add);
    }

如果上述方法使用不安全,是否添加同步是正确的方法?像这样

If the above method isn't safe to use, would adding synchronized be the proper way of doing it? Like so,

public synchronized void addBook(int index, Book add){
    shelf.put(index, add);
}

推荐答案

synchronized关键字实际上是在整个addBook方法周围放置了互斥锁.

The synchronized keyword essentially puts a mutex lock around the entire addBook method.

A ConcurrentHashMap确保所有操作(例如put)都是线程安全的,但是结合使用检索操作(例如get)可能会导致您遇到同时从Hashmap检索内容的情况.您正在放置,并获得意外的结果.

A ConcurrentHashMap ensures that all operations (such as put) are threadsafe, but using retrieval operations (such as get) in conjunction might cause you to come across a situation where you are retrieving contents from the Hashmap at the same time that you are putting, and get unexpected results.

单独地,ConcurrentHashMap中的所有方法都是线程安全的,但是在单独的线程中结合使用时,您不一定必须确定它们的执行顺序. (感谢@jtahlborn进行澄清).

Individually, all methods in the ConcurrentHashMap are thread-safe, but used in conjunction in separate threads you cannot necessarily be certain of the order in which they execute. (Thanks to @jtahlborn for clarification).

因此,在您的特定情况下,将synchronized关键字添加到addBook方法是多余的.

So, in your specific case, adding the synchronized keyword to the addBook method is redundant.

如果您要执行涉及多个取回和放置操作的更复杂的操作,则可能需要考虑进行一些无关的锁定(您自己的互斥锁).

If you're doing more complex operations involving multiple retrievals and puts, you may want to consider some extraneous locking (your own mutex).

请参阅: https://docs. oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

这篇关于使用与线程安全集合同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆