简体   繁体   English

如何在ConcurrentHashMap中并发放置元素(可能存在)而没有锁定?

[英]how to concurrently put an element (might exist) without lock in ConcurrentHashMap?

I'm writing a simple message queue program and I have multiple producers and multiple serializer (consumer is not considered right now). 我正在编写一个简单的消息队列程序,并且有多个生产者多个序列化器 (现在不考虑使用消费者)。 The producer specifies which queue it want to send message to by using a String queueName . 生产者通过使用String queueName指定要向其发送消息的队列。 And the serializer could only be initialized during sending procedure because the exact number/name of queues are not known until running. 而且串行器只能在发送过程中初始化,因为直到运行,队列的确切数目/名称才知道。 Since I have to use a Map, I think I can use either 由于我必须使用地图,因此我认为我可以使用

  • HashMap together with lock/synchronized HashMap与锁/同步
  • ConcurrentHashMap 的ConcurrentHashMap

I want to avoid using explicit lock, so I choose ConcurrentHashMap. 我想避免使用显式锁,所以我选择ConcurrentHashMap。 However, using ConcurrentHashMap doesn't mean my program ConcurrentHashMap is thread-safe, the idle between containsKey() and put() might cause some chaos. 但是,使用ConcurrentHashMap并不意味着我的程序ConcurrentHashMap是线程安全的, containsKey()put()之间的空闲状态可能会引起混乱。 So I consider using its putIfAbsent() method. 因此,我考虑使用其putIfAbsent()方法。

However, when I call putIfAbsent(queuename, new MySerializer()) , I find it creates a new instance of MySerializer everytime I call putIfAbsent. 但是,当我调用putIfAbsent(queuename, new MySerializer()) ,我发现每次我调用putIfAbsent时,它都会创建MySerializer的新实例。 But if I don't use putIfAbsent , I'll have to use something like a lock. 但是,如果我不使用putIfAbsent ,则必须使用诸如锁之类的东西。

My question is how to concurrently add elements into ConcurrentHashMap while avoiding using lock at the same time? 我的问题是如何在避免同时使用锁的同时向ConcurrentHashMap中添加元素?

Java 8 added new methods to the Map interface which allow the potentially-new value to be evaluated lazily. Java 8向Map接口添加了新方法,这些方法允许延迟评估潜在的新值。 For example: 例如:

map.computeIfAbsent(queuename, MySerializer::new);

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

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