-1

When I declare a ConcurrentHashMap in Java 8 class like this:

private final static ConcurrentHashMap<Long,Integer> signRatioMap = new ConcurrentHashMap();

I found without final it doesn't work fine. should I add final keywords? what is the advantage?

Omkar76
  • 1,317
  • 1
  • 8
  • 22
Dolphin
  • 29,069
  • 61
  • 260
  • 539

2 Answers2

1

The Final keyword does nothing but prevent a variable from being reassigned. If you don't need to reassign the variable, make it final.

SJS
  • 139
  • 1
  • 3
  • 13
1

Generally, making a variable final is a good coding practice and also may lead to some performance benefits (see the https://stackoverflow.com/a/4279442/508328 for details).

In your case, however, the situation is slightly different because Java's implementation of hash map can only grow its internal structure and never shrinks down, which leads to the continuous deterioration of its scan performance. So if your map is going to be changed often, it'd be better to recreate it now and then, and in that case it can't be final.

andbi
  • 4,426
  • 5
  • 45
  • 70
  • Recreating the map would defeat the purpose of a `ConcurrentHashMap`, as that can’t be an atomic operation, hence, not thread safe. That’s why the variable should be declared `final`, to document that the author understood that point. – Holger Oct 23 '20 at 08:36
  • @Holger still it can be done in a `synchronized` block, but that's far beyond the OP's original question :-) – andbi Oct 23 '20 at 08:50
  • A `synchronized` block would only work against code also using `synchronized` blocks using the same object. In other words, you’d have to put almost every access to the map into `synchronized` blocks, which, as said, would defeat the purpose of a `ConcurrentHashMap`. Atomic updates can only work when they are not mixed with non-atomic updates. – Holger Oct 23 '20 at 08:52