code

Java의 ConcurrentHashMap?

codestyles 2021. 1. 11. 08:14
반응형

Java의 ConcurrentHashMap?


ConcurrentHashMapJava에서 무엇을 사용 합니까? 그 이점은 무엇입니까? 어떻게 작동합니까? 샘플 코드도 유용 할 것입니다.


요점은 HashMap스레드로부터 안전한 구현을 제공하는 것입니다 . 여러 스레드가 오래된 데이터 나 손상된 데이터를받지 않고 읽고 쓸 수 있습니다. ConcurrentHashMap자체 동기화를 제공하므로 이에 대한 액세스를 명시 적으로 동기화 할 필요가 없습니다.

의 또 다른 기능은 지정된 키가 존재하지 않는 경우 매핑 원자 적으로 추가하는 메서드를 ConcurrentHashMap제공한다는 것 입니다. 다음 코드를 고려하십시오.putIfAbsent

ConcurrentHashMap<String, Integer> myMap = new ConcurrentHashMap<String, Integer>();

// some stuff

if (!myMap.contains("key")) {
  myMap.put("key", 3);
}

다른 스레드가에 대한 "key"호출 contains과에 대한 호출 사이에 에 대한 매핑을 추가 할 수 있기 때문에이 코드는 스레드로부터 안전하지 않습니다 put. 올바른 구현은 다음과 같습니다.

myMap.putIfAbsent("key", 3);

ConcurrentHashMap지도에 대한 동시 액세스를 허용합니다. HashTables도지도에 대한 동기화 된 액세스를 제공하지만 모든 작업을 수행하기 위해 전체지도가 잠겨 있습니다.

ConcurrentHashMap의 논리 your entire table is not getting locked는 부분 [ segments] 뿐입니다 . 각 세그먼트는 자체 HashTable을 관리합니다. 잠금은 업데이트에만 적용됩니다. 검색의 경우 완전한 동시성을 허용합니다.

용량이 32 인 맵에서 4 개의 스레드가 동시에 작업하고 테이블이 4 개의 세그먼트로 분할되어 각 세그먼트가 용량의 해시 테이블을 관리한다고 가정 해 보겠습니다. 컬렉션은 기본적으로 16 개의 세그먼트 목록을 유지하며, 각 세그먼트는 맵의 단일 버킷을 보호 (또는 잠금)하는 데 사용됩니다.

여기에 이미지 설명 입력

이는 사실상 16 개의 스레드가 한 번에 콜렉션을 수정할 수 있음을 의미합니다. 이 동시성 수준은 선택적 concurrencyLevel 생성자 인수를 사용하여 늘릴 수 있습니다 .

public ConcurrentHashMap(int initialCapacity,
                         float loadFactor, int concurrencyLevel)

다른 답변에서 언급했듯이 ConcurrentHashMap은 putIfAbsent()키가 있으면 값이 재정의되지 않는다는 점을 제외하면 put과 유사한 새로운 메서드 제공 합니다.

private static Map<String,String> aMap =new ConcurrentHashMap<String,String>();

if(!aMap.contains("key"))
   aMap.put("key","value");

새로운 방법은 double traversing위와 같이 하므로 더 빠릅니다 . contains메소드는 세그먼트를 찾고 키를 찾기 위해 테이블을 반복해야하며 다시 메소드 put는 버킷을 통과하여 키를 넣어야합니다.


실제로 큰 기능적 차이점은 예외를 던지지 않고 / 또는 사용하는 동안 다른 사람이 변경해도 손상되지 않는다는 것입니다.

일반 컬렉션을 사용하면 반복기를 통해 액세스하는 동안 다른 스레드가 요소를 추가하거나 제거하면 예외가 발생합니다. ConcurrentHashMap을 사용하면 변경 작업을 수행 할 수 있으며 스레드를 중지하지 않습니다.

한 스레드에서 다른 스레드로의 변경 사항에 대한 특정 시점 가시성에 대해 어떤 종류의 동기화를 보장하거나 약속하지 않습니다. (직렬화 가능한 데이터베이스 격리처럼 동작하는 동기화 된 맵이 아니라 읽기 커밋 된 데이터베이스 격리와 비슷합니다. (오라클 같은 다중 버전 직렬화가 아닌 오래된 학교 행 잠금 SQL 직렬화 가능 :))

내가 아는 가장 일반적인 용도는 많은 스레드가 동일한 항목에 액세스 할 수있는 App Server 환경에서 변경 불가능한 파생 정보를 캐싱하는 것입니다. 두 개의 스레드가 동일한 캐시 값을 계산하고 두 번 삽입하는 것은 실제로 중요하지 않습니다. 등 (예를 들어, URL에서 핸들러 메소드로의 매핑과 같은 런타임 파생 구성을 유지하기 위해 Spring WebMVC 프레임 워크 내에서 광범위하게 사용됩니다.)


메모에 사용할 수 있습니다.

import java.util.concurrent.ConcurrentHashMap;
public static Function<Integer, Integer> fib = (n) -> {
  Map<Integer, Integer> cache = new ConcurrentHashMap<>();
  if (n == 0 || n == 1) return n;
  return cache.computeIfAbsent(n, (key) -> HelloWorld.fib.apply(n - 2) + HelloWorld.fib.apply(n - 1));
};

1. ConcurrentHashMap은 한 번에 단일 스레드에서 코드에 액세스 할 수있는 스레드로부터 안전합니다.

2. ConcurrentHashMap은 Map의 특정 부분을 동기화하거나 잠급니다. ConcurrentHashMap의 성능을 최적화하기 위해 Map은 Concurrency 수준에 따라 여러 파티션으로 나뉩니다. 따라서 전체 Map Object를 동기화 할 필요가 없습니다.

3.Default concurrency level is 16, accordingly map is divided into 16 part and each part is governed with a different lock that means 16 thread can operate.

4.ConcurrentHashMap does not allow NULL values . So the key can not be null in ConcurrentHashMap .


Hello guys today we discussed the ConcurrentHashMap.
What is ConcurrentHashMap?

ConcurrentHashMap is a class it introduce in java 1.5 which implements the ConcurrentMap as well as the Serializable interface. ConcurrentHashMap is enhance the HashMap when it dealing with multiple Theading. As we know when the application has multiple threading HashMap is not a good choice because performance issue occurred.

There are the some key point of ConcurrentHashMap.

  • Underling data structure for ConcurrentHashMap is HashTable.
  • ConcurrentHashMap is a class, That class is thread safe, it means multiple thread can access on a single thread object without any complication.
  • ConcurretnHashMap object is divided into number of segment according to the concurrency level.
  • The Default Concurrency-level of ConcurrentHashMap is 16.
  • In ConcurrentHashMap any number of Thread can perform the retrieval operation,But for updation in object Thread must lock the particular Segment in which thread want to operate.
  • This type of locking mechanism is known as Segment-Locking OR Bucket-Locking.
  • In ConcurrentHashMap the 16 updation operation perform at a time.
  • Null insertion is not possible in ConcurrentHashMap.

Here are the ConcurrentHashMap construction.

  1. ConcurrentHashMap m=new ConcurrentHashMap();:Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16).

  2. ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity);:Creates a new, empty map with the specified initial capacity, and with default load factor (0.75) and concurrencyLevel (16).

  3. ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity, float loadFactor);: Creates a new, empty map with the specified initial capacity and load factor and with the default concurrencyLevel (16).

  4. ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel);:Creates a new, empty map with the specified initial capacity, load factor and concurrency level.

  5. ConcurrentHashMap m=new ConcurrentHashMap(Map m);:Creates a new map with the same mappings as the given map.

ConcurretHashMap에는 putIfAbsent (); 이 방법은 중복 키 저장을 방지하는 방법입니다. 아래 예를 참고하시기 바랍니다.

    import java.util.concurrent.*; 

     class ConcurrentHashMapDemo { 
     public static void main(String[] args) 
     { 
         ConcurrentHashMap m = new ConcurrentHashMap(); 
          m.put(1, "Hello"); 
          m.put(2, "Vala"); 
          m.put(3, "Sarakar"); 

         // Here we cant add Hello because 1 key 
         // is already present in ConcurrentHashMap object 

            m.putIfAbsent(1, "Hello"); 

         // We can remove entry because 2 key 
         // is associated with For value 

            m.remove(2, "Vala"); 

        // Now we can add Vala

            m.putIfAbsent(4, "Vala"); 


            System.out.println(m); 
      } 
}  

참조 URL : https://stackoverflow.com/questions/2836267/concurrenthashmap-in-java

반응형