001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.utils; 014 015import java.util.*; 016import java.util.concurrent.*; 017 018/** 019 * A hashmap that allows for two-part keys. 020 * @param <K1> Key part 1 type. 021 * @param <K2> Key part 2 type. 022 * @param <V> Value type. 023 */ 024public class TwoKeyConcurrentHashMap<K1,K2,V> extends ConcurrentHashMap<TwoKeyConcurrentHashMap.Key<K1,K2>,V> { 025 private static final long serialVersionUID = 1L; 026 027 /** 028 * Adds an entry to this map. 029 * 030 * @param key1 Key part 1. Can be <jk>null</jk>. 031 * @param key2 Key part 2. Can be <jk>null</jk>. 032 * @param value Value. 033 * @return The previous value if there was one. 034 */ 035 public V put(K1 key1, K2 key2, V value) { 036 Key<K1,K2> key = new Key<>(key1, key2); 037 return super.put(key, value); 038 } 039 040 /** 041 * Retrieves an entry from this map. 042 * 043 * @param key1 Key part 1. Can be <jk>null</jk>. 044 * @param key2 Key part 2. Can be <jk>null</jk>. 045 * @return The previous value if there was one. 046 */ 047 public V get(K1 key1, K2 key2) { 048 Key<K1,K2> key = new Key<>(key1, key2); 049 return super.get(key); 050 } 051 052 static class Key<K1,K2> { 053 final K1 k1; 054 final K2 k2; 055 final int hashCode; 056 057 Key(K1 k1, K2 k2) { 058 this.k1 = k1; 059 this.k2 = k2; 060 this.hashCode = 31*(k1 == null ? 0 : k1.hashCode()) + (k2 == null ? 0 : k2.hashCode()); 061 } 062 063 @Override /* Object */ 064 public int hashCode() { 065 return hashCode; 066 } 067 068 @Override /* Object */ 069 @SuppressWarnings("unchecked") 070 public boolean equals(Object o) { 071 Key<K1,K2> ko = (Key<K1,K2>)o; 072 return Objects.equals(k1, ko.k1) && Objects.equals(k2, ko.k2); 073 } 074 } 075}