LoginSignup
4
2

More than 1 year has passed since last update.

Hashtable、Vector、HashMap、ConcurrentHashMapの違い、ConcurrentHashMapはkey,valueにnullを許容しない等

Last updated at Posted at 2020-08-10

Javaにおける似たようなものたちの基礎知識メモ。
ConcurrentHashmapはHashMapをスレッドセーフにしたものだけどちょっと違うところもある。

基礎知識

VectorやHashtableは古い

「同期」のためにVectorは使わない(VectorとCollections.synchronizedList)
同様の理由で、もちろんHashtableも使うべきではない、という話。
Hashtableと同様の機能がほしければ以下。

// スレッドセーフなHashMapを生成
Map map = Collections.synchronizedMap(new HashMap());

あるいはソート済みの特性がほしければTreeMapを用いて以下。

// スレッドセーフなTreeMapを生成
Map map = Collections.synchronizedMap(new TreeMap());

HashMap

ConcurrentHashMap

排他制御を達成するために java1.5から追加された
が、nullを許容しない。

ConcurrentHashMap.java
    /**
     * Maps the specified key to the specified value in this table.
     * Neither the key nor the value can be null.
     *
     * <p> The value can be retrieved by calling the <tt>get</tt> method
     * with a key that is equal to the original key.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
     * @throws NullPointerException if the specified key or value is null
     */
    public V put(K key, V value) {
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).put(key, hash, value, false);
    }

例:

Sample1.java
        ConcurrentHashMap map = new ConcurrentHashMap();
        map.put("test", null);
Exception in thread "main" java.lang.NullPointerException
    at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:881)
    at playground.Sample1.main(Sample1.java:9)
Sample2.java

        ConcurrentHashMap map = new ConcurrentHashMap();
        map.put(null, "test");
Exception in thread "main" java.lang.NullPointerException
    at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:882)
    at playground.Sample2.main(Sample2.java:12)

よって、HashMap→ConcurrentHashmap置換時は注意。

Realcode.java
        if (inputvalue == null) {
            return;
        }

以上参考になればさいわいです。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2