Home > Software design >  Difference between concurrentMap
Difference between concurrentMap

Time:11-11

I am new to Java, and one thing confuse me is sometime commonly used APIs has very similar or same names. Like following, what are the differences between these two concurrentMap, and how to decide which one to use?

import java.util.concurrent.ConcurrentMap
ConcurrentMap<Integer, String> m = new ConcurrentHashMap<Integer, String>();

import com.google.common.collect.Maps;
Map<Integer, String> m = Maps.newConcurrentMap();

CodePudding user response:

When you have a doubt, you can check the source code:

/**
 * Creates a new empty {@link ConcurrentHashMap} instance.
 *
 * @since 3.0
 */
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
  return new ConcurrentHashMap<>();
}

Note that you don't need to specify the types starting Java 7:

ConcurrentMap<Integer, String> m = new ConcurrentHashMap<>();

CodePudding user response:

They are identical. You should just call new ConcurrentHashMap and forget about Maps.newConcurrentHashMap.

Over a decade ago at this point, the <> were optional when invoking static methods but they weren't when invoking constructors. var also didn't exist yet. Thus, the only way to write the code "Make a field or variable for a Map object, and create a new Map object, and assign the reference to this newly made object to the newly made field/variable" which is a rather common thing to do, is:

Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();

That's very weirdy and the <String, Integer> part is straight up duplication, which is annoying. That's why google introduced the newConcurrentHashMap method in their guava library, because:

Map<String, Integer> map = Maps.newConcurrentHashMap();

is shorter, and you can static-import that method for the even shorter:

Map<String, Integer> map = newConcurrentHashMap();

That was the only point of all this: Shorter code. It does the same thing. These days, for local vars you can write:

var map = new ConcurrentHashMap<String, Integer>();

and for fields you can use the diamond syntax:

Map<String, Integer> map = new ConcurrentHashMap<>();

Hence, google's newXYZ methods are obsolete.

  •  Tags:  
  • java
  • Related