user1269298
user1269298

Reputation: 727

Difference between concurrentMap

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();

Upvotes: 3

Views: 1442

Answers (2)

rzwitserloot
rzwitserloot

Reputation: 102804

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 wordy 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.

Upvotes: 1

Maroun
Maroun

Reputation: 95948

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<>();

Upvotes: 0

Related Questions