Skip to content

Instantly share code, notes, and snippets.

@hengyunabc
Last active May 31, 2018 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hengyunabc/bf306625879a6e0e7f12991e49b73838 to your computer and use it in GitHub Desktop.
Save hengyunabc/bf306625879a6e0e7f12991e49b73838 to your computer and use it in GitHub Desktop.
ConcurrentHashMap NoSuchMethodError

当用jdk8编绎,生成target 为 jdk6/7 的代码时,如果有使用到了类似的代码,就会抛出异常

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
map.keySet();

抛出

java.lang.NoSuchMethodError: java.util.concurrent.ConcurrentHashMap.keySet()Ljava/util/concurrent/ConcurrentHashMap$KeySetView;

原因很简单,jdk8里的ConcurrentHashMap#keySet()返回了一个新的类型,这个在旧的jdk上没有。

网上有很多文章说编绎时,用-bootclasspath指定旧版本的jdk来解决。但是太麻烦,没有通用性。

最简单实用的办法是把接口改为 ConcurrentMap

ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>();

这个接口在jdk6上也有putIfAbsent函数。

https://docs.oracle.com/javase/6/docs/api/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment