Codename One中的ConcurrentHashMap

问题描述 投票:1回答:1

我需要在不同的线程中使用相同的HashMap ((EDT,一个计时器,也许还有网络线程))。由于Codename One在其API中没有ConcurrentHashMap实现,因此我尝试绕过此问题,因此:

/**
 * ConcurrentHashMap emulation for Codename One.
 */
public class ConcurrentHashMap<K, V> {

    private static final EasyThread thread = EasyThread.start("concurrentHashMap_Thread");
    private final Map<K, V> map = new HashMap<>();

    public V put(K key, V value) {
        return thread.run(() -> map.put(key, value));
    }

    public V get(K key) {
        return thread.run(() -> map.get(key));
    }

    public V remove(K key) {
        return thread.run(() -> map.remove(key));
    }

}

我有两个问题:

  1. 当从两个或多个线程访问Map时,是否确实需要在Codename One中使用上述代码?直接使用HashMap更好吗?

  2. 您如何看待该代码?我试图使其尽可能简单,但不确定其正确性。

codenameone
1个回答
0
投票

该代码非常正确。当您创建多个锁以将新对象添加到不同的线程时,它的效率也非常低。因此,您可以有效地解决一个简单得多的问题。

TL; DR是这里:

map = Collections.synchronizedMap(map);

您的代码本可以这样编写,并且效率更高:

public class ConcurrentHashMap<K, V> {
    private static final EasyThread thread = EasyThread.start("concurrentHashMap_Thread");
    private final Map<K, V> map = new HashMap<>();

    public synchronized V put(K key, V value) {
        return map.put(key, value);
    }

    public synchronized V get(K key) {
        return map.get(key);
    }

    public synchronized V remove(K key) {
        return map.remove(key);
    }
}

但是您显然不需要它,因为我们有synchronizedMap方法...

所以我们为什么没有ConcurrentHashMap

因为我们不在大型服务器上运行。看到这篇文章:https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

该文章的TL; DR是,当您有很多线程和很多服务器核心时,ConcurrentHashMap是有意义的。它会尽最大努力限制同步以达到最大规模。在移动设备中,这是一个巨大的矫kill过正。

© www.soinside.com 2019 - 2024. All rights reserved.