简体   繁体   English

如何自动增加HashMap中的键?

[英]How to auto increment the keys in a HashMap?

I have a multithreading app. 我有一个多线程应用程序。 Multiple threads are putting things into a Map in which each thing must have a unique ID. 多个线程将事物放入Map中,其中每个事物必须具有唯一ID。 Right now I'm using a TreeMap for this purpose like this: 现在我正在为此目的使用TreeMap,如下所示:

TreeMap<Integer, Thing> things = new TreeMap<>();
things.put(things.isEmpty() ? 0 : things.lastKey() + 1, thing);

But a TreeMap is not thread-safe, so I decided to replace it with a ConcurrentHashMap. 但是TreeMap不是线程安全的,所以我决定用ConcurrentHashMap替换它。

But how could I achieve the same using a HashMap? 但是我如何使用HashMap实现相同的目标呢? So how to generate a new unique key for each thing I put into it? 那么如何为我投入的每件事生成一个新的唯一键?

You can generate unique Integers using Javas AtomicInteger class. 您可以使用Javas AtomicInteger类生成唯一的整数。 It has a thread-safe getAndIncrement() method for that purpose. 它有一个线程安全的getAndIncrement()方法用于此目的。

However, this may cause some unpredictable bug in HashMap even with different keys. 但是,即使使用不同的密钥,这也可能导致HashMap中出现一些不可预测的错误。 Some example listed here: Is a HashMap thread-safe for different keys? 这里列出的一些例子: HashMap对不同的密钥是否是线程安全的?

So be sure to use a thread-safe map, or some other faster thread-safe datastructure like a Vector. 所以一定要使用线程安全的映射,或者像Vector这样的其他更快的线程安全的数据结构。 If you know an upper bound of how many elements will be added, using an array with the index from AtomicInteger would be fastest, as you can avoid all synchronization. 如果您知道将添加多少元素的上限,则使用具有AtomicInteger索引的数组将是最快的,因为您可以避免所有同步。

Well you can write (something) like this: 那么你可以这样写(某事):

Map<Integer, Integer> map = new ConcurrentHashMap<>();
AtomicInteger ai = new AtomicInteger(-1);

map.compute(x, (l, r) -> {
    return ai.incrementAndGet();
})

compute is documented to be atomic compute被记录为原子的

Consider using an UUID for the keys, it's extremely unlikely that a collision will occur. 考虑使用UUID作为密钥,发生冲突的可能性极小 Something like this: 像这样的东西:

// import java.util.UUID;
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();

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

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