HashMap対ConcurrentHashMap対。 SynchronizedMap –JavaでHashMapを同期する方法
公開: 2015-01-29
HashMap
は、Javaの非常に強力なデータ構造です。 私たちは毎日、ほとんどすべてのアプリケーションでそれを使用しています。 スレッドセーフキャッシュを実装する方法、ハッシュマップを配列リストに変換する方法について以前に書いた例はかなりありますか?
上記の両方の例でHashmapを使用しましたが、これらはHashmapの非常に単純なユースケースです。 HashMap is a non-synchronized
コレクションクラスです。
以下の質問はありますか?
- ConcurrentHashMapとCollections.synchronizedMap(Map)の違いは何ですか?
- ConcurrentHashMapとCollections.synchronizedMap(Map)のパフォーマンスの違いは何ですか?
- ConcurrentHashMapとCollections.synchronizedMap()
- 人気のあるHashMapとConcurrentHashMapのインタビューの質問
このチュートリアルでは、上記のすべてのクエリを確認し、ハッシュマップを同期できるwhy and how
を説明します。
なんで?
Mapオブジェクトは、一意に識別されるkey
とマップされたvalue
の組み合わせによって形成された要素を格納する連想コンテナです。 異なるスレッドでキー値を変更または読み取りたい可能性のある非常に並行性の高いアプリケーションがある場合は、並行ハッシュマップを使用するのが理想的です。 最良の例は、同時読み取り/書き込みを処理するプロデューサーコンシューマーです。
では、スレッドセーフマップとはどういう意味ですか? multiple threads
が同時にハッシュマップにアクセスし、少なくとも1つのスレッドがマップを構造的に変更する場合は、コンテンツの表示に一貫性がないように、 must be synchronized externally
。
どのように?
HashMapを同期する方法は2つあります
- JavaコレクションsynchronizedMap()メソッド
- ConcurrentHashMapを使用する
1 2 3 4 5 6 7 8 |
//Hashtable Map < String , String > normalMap = new Hashtable < String , String > ( ) ; //synchronizedMap synchronizedHashMap = Collections . synchronizedMap ( new HashMap < String , String > ( ) ) ; //ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap < String , String > ( ) ; |
ConcurrentHashMap
- プロジェクトで非常に高い同時実行性が必要な場合は、ConcurrentHashMapを使用する必要があります。
-
whole map
を同期しなくてもスレッドセーフです。 - 書き込みがロックで行われている間、読み取りは非常に高速に発生する可能性があります。
- オブジェクトレベルでのロックはありません。
- ロックは、ハッシュマップバケットレベルではるかに細かい粒度で行われます。
- ConcurrentHashMapは、別のスレッドが反復しているときに1つのスレッドがそれを変更しようとしても、
ConcurrentModificationException
をスローしません。 - ConcurrentHashMapは、多数のロックを使用します。
SynchronizedHashMap
- オブジェクトレベルでの同期。
- すべての読み取り/書き込み操作はロックを取得する必要があります。
- コレクション全体をロックすると、パフォーマンスのオーバーヘッドが発生します。
- これにより、基本的に、マップ全体への1つのスレッドのみにアクセスできるようになり、他のすべてのスレッドがブロックされます。
- 競合が発生する可能性があります。
- SynchronizedHashMapは
Iterator
を返しますが、これは同時変更で失敗します。
それでは、コードを見てみましょう
- クラス
CrunchifyConcurrentHashMapVsSynchronizedHashMap.java
作成します - HashTable、SynchronizedMap、CrunchifyConcurrentHashMapごとにオブジェクトを作成します
- マップから500kエントリを追加および取得します
- 開始時間と終了時間、および表示時間をミリ秒単位で測定します
- ExecutorServiceを使用して、
5 threads
を並行して実行します
Javaコードは次のとおりです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
package crunchify . com . tutorials ; import java . util . Collections ; import java . util . HashMap ; import java . util . Hashtable ; import java . util . Map ; import java . util . concurrent . ConcurrentHashMap ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . TimeUnit ; /** * @author Crunchify.com * */ public class CrunchifyConcurrentHashMapVsSynchronizedMap { public final static int THREAD_POOL_SIZE = 5 ; public static Map < String , Integer > crunchifyHashTableObject = null ; public static Map < String , Integer > crunchifySynchronizedMapObject = null ; public static Map < String , Integer > crunchifyConcurrentHashMapObject = null ; public static void main ( String [ ] args ) throws InterruptedException { // Test with Hashtable Object crunchifyHashTableObject = new Hashtable < String , Integer > ( ) ; crunchifyPerformTest ( crunchifyHashTableObject ) ; // Test with synchronizedMap Object crunchifySynchronizedMapObject = Collections . synchronizedMap ( new HashMap < String , Integer > ( ) ) ; crunchifyPerformTest ( crunchifySynchronizedMapObject ) ; // Test with ConcurrentHashMap Object crunchifyConcurrentHashMapObject = new ConcurrentHashMap < String , Integer > ( ) ; crunchifyPerformTest ( crunchifyConcurrentHashMapObject ) ; } public static void crunchifyPerformTest ( final Map < String , Integer > crunchifyThreads ) throws InterruptedException { System . out . println ( "Test started for: " + crunchifyThreads . getClass ( ) ) ; long averageTime = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { long startTime = System . nanoTime ( ) ; ExecutorService crunchifyExServer = Executors . newFixedThreadPool ( THREAD_POOL_SIZE ) ; for ( int j = 0 ; j < THREAD_POOL_SIZE ; j ++ ) { crunchifyExServer . execute ( new Runnable ( ) { @SuppressWarnings ( "unused" ) @Override public void run ( ) { for ( int i = 0 ; i < 500000 ; i ++ ) { Integer crunchifyRandomNumber = ( int ) Math . ceil ( Math . random ( ) * 550000 ) ; // Retrieve value. We are not using it anywhere Integer crunchifyValue = crunchifyThreads . get ( String . valueOf ( crunchifyRandomNumber ) ) ; // Put value crunchifyThreads . put ( String . valueOf ( crunchifyRandomNumber ) , crunchifyRandomNumber ) ; } } } ) ; } // Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation // has no additional effect if already shut down. // This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that. crunchifyExServer . shutdown ( ) ; // Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is // interrupted, whichever happens first. crunchifyExServer . awaitTermination ( Long . MAX_VALUE , TimeUnit . DAYS ) ; long entTime = System . nanoTime ( ) ; long totalTime = ( entTime - startTime ) / 1000000L ; averageTime += totalTime ; System . out . println ( "500K entried added/retrieved in " + totalTime + " ms" ) ; } System . out . println ( "For " + crunchifyThreads . getClass ( ) + " the average time is " + averageTime / 5 + " ms\n" ) ; } } |

shutdown()
は、エグゼキュータサービスが着信タスクをこれ以上受け取らないことを意味します。-
awaitTermination()
は、シャットダウン要求の後に呼び出されます。
したがって、最初にserviceExecutorをシャットダウンしてから、ブロックしてスレッドが終了するのを待つ必要があります。
Eclipseコンソールの結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Test started for: class java.util.Hashtable 500K entried added/retrieved in 1832 ms 500K entried added/retrieved in 1723 ms 500K entried added/retrieved in 1782 ms 500K entried added/retrieved in 1607 ms 500K entried added/retrieved in 1851 ms For class java.util.Hashtable the average time is 1759 ms Test started for: class java.util.Collections$SynchronizedMap 500K entried added/retrieved in 1923 ms 500K entried added/retrieved in 2032 ms 500K entried added/retrieved in 1621 ms 500K entried added/retrieved in 1833 ms 500K entried added/retrieved in 2048 ms For class java.util.Collections$SynchronizedMap the average time is 1891 ms Test started for: class java.util.concurrent.ConcurrentHashMap 500K entried added/retrieved in 1068 ms 500K entried added/retrieved in 1029 ms 500K entried added/retrieved in 1165 ms 500K entried added/retrieved in 840 ms 500K entried added/retrieved in 1017 ms For class java.util.concurrent.ConcurrentHashMap the average time is 1023 ms |