java多线程map_Java Hashmap-多线程放置

我们最近在工作中讨论了在多线程环境中是需要使用ConcurrentHashMap还是可以简单地使用常规HashMap。HashMaps的参数有两个:它比ConcurrentHashMap更快,所以我们应该尽可能使用它。而且ConcurrentModificationException显然只有在修改后迭代地图时才会出现,所以“如果我们仅从地图进行PUT和GET,则常规HashMap有什么问题?”

是争论。

我以为并发PUT操作或并发PUT和READ可能导致异常,因此我进行了测试以证明这一点。测试很简单;创建10个线程,每个线程一次又一次地将相同的1000个键值对再次写入映射,持续5秒钟,然后打印结果映射。

结果实际上令人困惑:

Length:1299

Errors recorded: 0

我以为每个键值对在HashMap中都是唯一的,但是从地图上看,我可以找到多个相同的键值对。 我期望某种异常或损坏的键或值,但是我没有想到这一点。

这是怎么发生的?

这是我使用的代码,仅供参考:

public class ConcurrentErrorTest

{

static final long runtime = 5000;

static final AtomicInteger errCount = new AtomicInteger();

static final int count = 10;

public static void main(String[] args) throws InterruptedException

{

List threads = new LinkedList<>();

final Map map = getMap();

for (int i = 0; i < count; i++)

{

Thread t = getThread(map);

threads.add(t);

t.start();

}

for (int i = 0; i < count; i++)

{

threads.get(i).join(runtime + 1000);

}

for (String s : map.keySet())

{

System.out.println(s + " " + map.get(s));

}

System.out.println("Length:" + map.size());

System.out.println("Errors recorded: " + errCount.get());

}

private static Map getMap()

{

Map map = new HashMap<>();

return map;

}

private static Map getConcMap()

{

Map map = new ConcurrentHashMap<>();

return map;

}

private static Thread getThread(final Map map)

{

return new Thread(new Runnable() {

@Override

public void run()

{

long start = System.currentTimeMillis();

long now = start;

while (now - start < runtime)

{

try

{

for (int i = 0; i < 1000; i++)

map.put("i=" + i, i);

now = System.currentTimeMillis();

}

catch (Exception e)

{

System.out.println("P - Error occured: " + e.toString());

errCount.incrementAndGet();

}

}

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值