sun.misc.Hashing cannot be resolved to a type

旧城等待, 2023-06-21 04:59 81阅读 0赞

sun.*包内的类在开发时尽量不要使用,oracle在官网上也建议大家不要使用,可以参考https://www.oracle.com/java/technologies/faq-sun-packages.html,像eclipse之类的编译器也会对引用sun.*子包内的类给出编译错误,要想使用必须相应设置可以绕过这一限制,但是这却不是一个好的开发习惯,sun.*子包内的类很可能会在后续版本中移除,sun.misc.Hashing这个类在jdk8中就移除了,笔者为了看下jdk7中hashmap用在多线程情况下死循环的问题,将jdk7中hashmap实现拷贝出来,但是在编译时报了“sun.misc.Hashing cannot be resolved to a type”编译失败,在网上搜了很多,基本上没人提到这个问题,大部分都是sun.misc.Base64Encoder、sun.misc.Base64Decoder之类的信息,最终在eclipse使用CTRL+SHIFT+T查了下Hashing这个类,发现这个类在jdk7版本中存在,但在jdk8版本中却移除了。

PS:

1、为了代码的可移植性,尽量慎用sun包下类

2、JDK7中hashmap用在多线程中出现死循环问题就在于扩容时数据重新配置时逆序导致的,只需要将transfer方法进行下面的调整就可以避免死循环问题,这也是jdk8中数据重新分配策略:

  1. /**
  2. * Transfers all entries from current table to newTable.
  3. */
  4. void transfer(Entry[] newTable, boolean rehash) {
  5. //jdk7中调整策略,用在多线程中存在死循环问题
  6. /* int newCapacity = newTable.length;
  7. for (Entry<K,V> e : table) {
  8. while(null != e) {
  9. Entry<K,V> next = e.next;
  10. if (rehash) {
  11. e.hash = null == e.key ? 0 : hash(e.key);
  12. }
  13. int i = indexFor(e.hash, newCapacity); //所在散列桶序号
  14. e.next = newTable[i]; //这边做了逆序处理,在多线程使用时会导致死循环
  15. newTable[i] = e;
  16. e = next;
  17. }
  18. }*/
  19. int oldCap = table.length;
  20. for (Entry<K,V> e : table) {
  21. Entry<K,V> loHead = null, loTail = null;
  22. Entry<K,V> hiHead = null, hiTail = null;
  23. int i =0;
  24. while(null != e) {
  25. Entry<K,V> next = e.next;
  26. if (rehash) {
  27. e.hash = null == e.key ? 0 : hash(e.key);
  28. }
  29. i = e.hash & (oldCap-1);
  30. if ((e.hash & oldCap) == 0) {//在原来的散列桶
  31. if (loTail == null)
  32. loHead = e;
  33. else
  34. loTail.next = e;
  35. loTail = e;
  36. }
  37. else {//不在原来的散列桶
  38. if (hiTail == null)
  39. hiHead = e;
  40. else
  41. hiTail.next = e;
  42. hiTail = e;
  43. }
  44. e = next;
  45. }
  46. if (loTail != null) {
  47. loTail.next = null;
  48. newTable[i] = loHead;
  49. }
  50. if (hiTail != null) {
  51. hiTail.next = null;
  52. newTable[i + oldCap] = hiHead;
  53. }
  54. }
  55. }

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读