Path: blob/master/test/jdk/java/util/Map/Defaults.java
41149 views
/*1* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 8010122 8004518 8024331 802468826* @summary Test Map default methods27* @author Mike Duigou28* @run testng Defaults29*/3031import org.testng.Assert.ThrowingRunnable;32import org.testng.annotations.DataProvider;33import org.testng.annotations.Test;3435import java.util.AbstractMap;36import java.util.AbstractSet;37import java.util.ArrayList;38import java.util.Arrays;39import java.util.Collection;40import java.util.Collections;41import java.util.EnumMap;42import java.util.HashMap;43import java.util.HashSet;44import java.util.Hashtable;45import java.util.IdentityHashMap;46import java.util.Iterator;47import java.util.LinkedHashMap;48import java.util.Map;49import java.util.Set;50import java.util.TreeMap;51import java.util.WeakHashMap;52import java.util.concurrent.ConcurrentHashMap;53import java.util.concurrent.ConcurrentMap;54import java.util.concurrent.ConcurrentSkipListMap;55import java.util.concurrent.atomic.AtomicBoolean;56import java.util.function.BiFunction;57import java.util.function.Function;58import java.util.function.Supplier;5960import static java.util.Objects.requireNonNull;61import static org.testng.Assert.assertEquals;62import static org.testng.Assert.assertFalse;63import static org.testng.Assert.assertNull;64import static org.testng.Assert.assertSame;65import static org.testng.Assert.assertThrows;66import static org.testng.Assert.assertTrue;67import static org.testng.Assert.fail;6869public class Defaults {7071@Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=withNull values=withNull")72public void testGetOrDefaultNulls(String description, Map<IntegerEnum, String> map) {73assertTrue(map.containsKey(null), description + ": null key absent");74assertNull(map.get(null), description + ": value not null");75assertSame(map.get(null), map.getOrDefault(null, EXTRA_VALUE), description + ": values should match");76}7778@Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=all values=all")79public void testGetOrDefault(String description, Map<IntegerEnum, String> map) {80assertTrue(map.containsKey(KEYS[1]), "expected key missing");81assertSame(map.get(KEYS[1]), map.getOrDefault(KEYS[1], EXTRA_VALUE), "values should match");82assertFalse(map.containsKey(EXTRA_KEY), "expected absent key");83assertSame(map.getOrDefault(EXTRA_KEY, EXTRA_VALUE), EXTRA_VALUE, "value not returned as default");84assertNull(map.getOrDefault(EXTRA_KEY, null), "null not returned as default");85}8687@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")88public void testPutIfAbsentNulls(String description, Map<IntegerEnum, String> map) {89// null -> null90assertTrue(map.containsKey(null), "null key absent");91assertNull(map.get(null), "value not null");92assertNull(map.putIfAbsent(null, EXTRA_VALUE), "previous not null");93// null -> EXTRA_VALUE94assertTrue(map.containsKey(null), "null key absent");95assertSame(map.get(null), EXTRA_VALUE, "unexpected value");96assertSame(map.putIfAbsent(null, null), EXTRA_VALUE, "previous not expected value");97assertTrue(map.containsKey(null), "null key absent");98assertSame(map.get(null), EXTRA_VALUE, "unexpected value");99assertSame(map.remove(null), EXTRA_VALUE, "removed unexpected value");100// null -> <absent>101102assertFalse(map.containsKey(null), description + ": key present after remove");103assertNull(map.putIfAbsent(null, null), "previous not null");104// null -> null105assertTrue(map.containsKey(null), "null key absent");106assertNull(map.get(null), "value not null");107assertNull(map.putIfAbsent(null, EXTRA_VALUE), "previous not null");108assertSame(map.get(null), EXTRA_VALUE, "value not expected");109}110111@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")112public void testPutIfAbsent(String description, Map<IntegerEnum, String> map) {113// 1 -> 1114assertTrue(map.containsKey(KEYS[1]));115Object expected = map.get(KEYS[1]);116assertTrue(null == expected || expected == VALUES[1]);117assertSame(map.putIfAbsent(KEYS[1], EXTRA_VALUE), expected);118assertSame(map.get(KEYS[1]), expected);119120// EXTRA_KEY -> <absent>121assertFalse(map.containsKey(EXTRA_KEY));122assertSame(map.putIfAbsent(EXTRA_KEY, EXTRA_VALUE), null);123assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);124assertSame(map.putIfAbsent(EXTRA_KEY, VALUES[2]), EXTRA_VALUE);125assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);126}127128@Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=all values=all")129public void testForEach(String description, Map<IntegerEnum, String> map) {130IntegerEnum[] EACH_KEY = new IntegerEnum[map.size()];131132map.forEach((k, v) -> {133int idx = (null == k) ? 0 : k.ordinal(); // substitute for index.134assertNull(EACH_KEY[idx]);135EACH_KEY[idx] = (idx == 0) ? KEYS[0] : k; // substitute for comparison.136assertSame(v, map.get(k));137});138139assertEquals(KEYS, EACH_KEY, description);140}141142@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")143public static void testReplaceAll(String description, Map<IntegerEnum, String> map) {144IntegerEnum[] EACH_KEY = new IntegerEnum[map.size()];145Set<String> EACH_REPLACE = new HashSet<>(map.size());146147map.replaceAll((k,v) -> {148int idx = (null == k) ? 0 : k.ordinal(); // substitute for index.149assertNull(EACH_KEY[idx]);150EACH_KEY[idx] = (idx == 0) ? KEYS[0] : k; // substitute for comparison.151assertSame(v, map.get(k));152String replacement = v + " replaced";153EACH_REPLACE.add(replacement);154return replacement;155});156157assertEquals(KEYS, EACH_KEY, description);158assertEquals(map.values().size(), EACH_REPLACE.size(), description + EACH_REPLACE);159assertTrue(EACH_REPLACE.containsAll(map.values()), description + " : " + EACH_REPLACE + " != " + map.values());160assertTrue(map.values().containsAll(EACH_REPLACE), description + " : " + EACH_REPLACE + " != " + map.values());161}162163@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")164public static void testReplaceAllNoNullReplacement(String description, Map<IntegerEnum, String> map) {165assertThrowsNPE(() -> map.replaceAll(null));166assertThrowsNPE(() -> map.replaceAll((k,v) -> null)); //should not allow replacement with null value167}168169@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")170public static void testRemoveNulls(String description, Map<IntegerEnum, String> map) {171assertTrue(map.containsKey(null), "null key absent");172assertNull(map.get(null), "value not null");173assertFalse(map.remove(null, EXTRA_VALUE), description);174assertTrue(map.containsKey(null));175assertNull(map.get(null));176assertTrue(map.remove(null, null));177assertFalse(map.containsKey(null));178assertNull(map.get(null));179assertFalse(map.remove(null, null));180}181182@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")183public static void testRemove(String description, Map<IntegerEnum, String> map) {184assertTrue(map.containsKey(KEYS[1]));185Object expected = map.get(KEYS[1]);186assertTrue(null == expected || expected == VALUES[1]);187assertFalse(map.remove(KEYS[1], EXTRA_VALUE), description);188assertSame(map.get(KEYS[1]), expected);189assertTrue(map.remove(KEYS[1], expected));190assertNull(map.get(KEYS[1]));191assertFalse(map.remove(KEYS[1], expected));192193assertFalse(map.containsKey(EXTRA_KEY));194assertFalse(map.remove(EXTRA_KEY, EXTRA_VALUE));195}196197@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")198public void testReplaceKVNulls(String description, Map<IntegerEnum, String> map) {199assertTrue(map.containsKey(null), "null key absent");200assertNull(map.get(null), "value not null");201assertSame(map.replace(null, EXTRA_VALUE), null);202assertSame(map.get(null), EXTRA_VALUE);203}204205@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")206public void testReplaceKVNoNulls(String description, Map<IntegerEnum, String> map) {207assertTrue(map.containsKey(FIRST_KEY), "expected key missing");208assertSame(map.get(FIRST_KEY), FIRST_VALUE, "found wrong value");209assertThrowsNPE(() -> map.replace(FIRST_KEY, null));210assertSame(map.replace(FIRST_KEY, EXTRA_VALUE), FIRST_VALUE, description + ": replaced wrong value");211assertSame(map.get(FIRST_KEY), EXTRA_VALUE, "found wrong value");212}213214@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")215public void testReplaceKV(String description, Map<IntegerEnum, String> map) {216assertTrue(map.containsKey(KEYS[1]));217Object expected = map.get(KEYS[1]);218assertTrue(null == expected || expected == VALUES[1]);219assertSame(map.replace(KEYS[1], EXTRA_VALUE), expected);220assertSame(map.get(KEYS[1]), EXTRA_VALUE);221222assertFalse(map.containsKey(EXTRA_KEY));223assertNull(map.replace(EXTRA_KEY, EXTRA_VALUE));224assertFalse(map.containsKey(EXTRA_KEY));225assertNull(map.get(EXTRA_KEY));226assertNull(map.put(EXTRA_KEY, EXTRA_VALUE));227assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);228assertSame(map.replace(EXTRA_KEY, (String)expected), EXTRA_VALUE);229assertSame(map.get(EXTRA_KEY), expected);230}231232@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")233public void testReplaceKVVNulls(String description, Map<IntegerEnum, String> map) {234assertTrue(map.containsKey(null), "null key absent");235assertNull(map.get(null), "value not null");236assertFalse(map.replace(null, EXTRA_VALUE, EXTRA_VALUE));237assertNull(map.get(null));238assertTrue(map.replace(null, null, EXTRA_VALUE));239assertSame(map.get(null), EXTRA_VALUE);240assertTrue(map.replace(null, EXTRA_VALUE, EXTRA_VALUE));241assertSame(map.get(null), EXTRA_VALUE);242}243244@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")245public void testReplaceKVVNoNulls(String description, Map<IntegerEnum, String> map) {246assertTrue(map.containsKey(FIRST_KEY), "expected key missing");247assertSame(map.get(FIRST_KEY), FIRST_VALUE, "found wrong value");248assertThrowsNPE(() -> map.replace(FIRST_KEY, FIRST_VALUE, null));249assertThrowsNPE(250() -> {251if (!map.replace(FIRST_KEY, null, EXTRA_VALUE)) {252throw new NullPointerException("default returns false rather than throwing");253}254});255assertTrue(map.replace(FIRST_KEY, FIRST_VALUE, EXTRA_VALUE), description + ": replaced wrong value");256assertSame(map.get(FIRST_KEY), EXTRA_VALUE, "found wrong value");257}258259@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")260public void testReplaceKVV(String description, Map<IntegerEnum, String> map) {261assertTrue(map.containsKey(KEYS[1]));262Object expected = map.get(KEYS[1]);263assertTrue(null == expected || expected == VALUES[1]);264assertFalse(map.replace(KEYS[1], EXTRA_VALUE, EXTRA_VALUE));265assertSame(map.get(KEYS[1]), expected);266assertTrue(map.replace(KEYS[1], (String)expected, EXTRA_VALUE));267assertSame(map.get(KEYS[1]), EXTRA_VALUE);268assertTrue(map.replace(KEYS[1], EXTRA_VALUE, EXTRA_VALUE));269assertSame(map.get(KEYS[1]), EXTRA_VALUE);270271assertFalse(map.containsKey(EXTRA_KEY));272assertFalse(map.replace(EXTRA_KEY, EXTRA_VALUE, EXTRA_VALUE));273assertFalse(map.containsKey(EXTRA_KEY));274assertNull(map.get(EXTRA_KEY));275assertNull(map.put(EXTRA_KEY, EXTRA_VALUE));276assertTrue(map.containsKey(EXTRA_KEY));277assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);278assertTrue(map.replace(EXTRA_KEY, EXTRA_VALUE, EXTRA_VALUE));279assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);280}281282@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")283public void testComputeIfAbsentNulls(String description, Map<IntegerEnum, String> map) {284// null -> null285assertTrue(map.containsKey(null), "null key absent");286assertNull(map.get(null), "value not null");287assertSame(map.computeIfAbsent(null, (k) -> null), null, "not expected result");288assertTrue(map.containsKey(null), "null key absent");289assertNull(map.get(null), "value not null");290assertSame(map.computeIfAbsent(null, (k) -> EXTRA_VALUE), EXTRA_VALUE, "not mapped to result");291// null -> EXTRA_VALUE292assertTrue(map.containsKey(null), "null key absent");293assertSame(map.get(null), EXTRA_VALUE, "not expected value");294assertSame(map.remove(null), EXTRA_VALUE, "removed unexpected value");295// null -> <absent>296assertFalse(map.containsKey(null), "null key present");297assertSame(map.computeIfAbsent(null, (k) -> EXTRA_VALUE), EXTRA_VALUE, "not mapped to result");298// null -> EXTRA_VALUE299assertTrue(map.containsKey(null), "null key absent");300assertSame(map.get(null), EXTRA_VALUE, "not expected value");301}302303@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")304public void testComputeIfAbsent(String description, Map<IntegerEnum, String> map) {305// 1 -> 1306assertTrue(map.containsKey(KEYS[1]));307Object expected = map.get(KEYS[1]);308assertTrue(null == expected || expected == VALUES[1], description + String.valueOf(expected));309expected = (null == expected) ? EXTRA_VALUE : expected;310assertSame(map.computeIfAbsent(KEYS[1], (k) -> EXTRA_VALUE), expected, description);311assertSame(map.get(KEYS[1]), expected, description);312313// EXTRA_KEY -> <absent>314assertFalse(map.containsKey(EXTRA_KEY));315assertNull(map.computeIfAbsent(EXTRA_KEY, (k) -> null));316assertFalse(map.containsKey(EXTRA_KEY));317assertSame(map.computeIfAbsent(EXTRA_KEY, (k) -> EXTRA_VALUE), EXTRA_VALUE);318// EXTRA_KEY -> EXTRA_VALUE319assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);320}321322@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")323public void testComputeIfAbsentNullFunction(String description, Map<IntegerEnum, String> map) {324assertThrowsNPE(() -> map.computeIfAbsent(KEYS[1], null));325}326327@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")328public void testComputeIfPresentNulls(String description, Map<IntegerEnum, String> map) {329assertTrue(map.containsKey(null), description + ": null key absent");330assertNull(map.get(null), description + ": value not null");331assertSame(map.computeIfPresent(null, (k, v) -> {332fail(description + ": null value is not deemed present");333return EXTRA_VALUE;334}), null, description);335assertTrue(map.containsKey(null));336assertNull(map.get(null), description);337assertNull(map.remove(EXTRA_KEY), description + ": unexpected mapping");338assertNull(map.put(EXTRA_KEY, null), description + ": unexpected value");339assertSame(map.computeIfPresent(EXTRA_KEY, (k, v) -> {340fail(description + ": null value is not deemed present");341return EXTRA_VALUE;342}), null, description);343assertNull(map.get(EXTRA_KEY), description + ": null mapping gone");344}345346@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")347public void testComputeIfPresent(String description, Map<IntegerEnum, String> map) {348assertTrue(map.containsKey(KEYS[1]));349Object value = map.get(KEYS[1]);350assertTrue(null == value || value == VALUES[1], description + String.valueOf(value));351Object expected = (null == value) ? null : EXTRA_VALUE;352assertSame(map.computeIfPresent(KEYS[1], (k, v) -> {353assertSame(v, value);354return EXTRA_VALUE;355}), expected, description);356assertSame(map.get(KEYS[1]), expected, description);357358assertFalse(map.containsKey(EXTRA_KEY));359assertSame(map.computeIfPresent(EXTRA_KEY, (k, v) -> {360fail();361return EXTRA_VALUE;362}), null);363assertFalse(map.containsKey(EXTRA_KEY));364assertSame(map.get(EXTRA_KEY), null);365}366367@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")368public void testComputeIfPresentNullFunction(String description, Map<IntegerEnum, String> map) {369assertThrowsNPE(() -> map.computeIfPresent(KEYS[1], null));370}371372@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")373public void testComputeNulls(String description, Map<IntegerEnum, String> map) {374assertTrue(map.containsKey(null), "null key absent");375assertNull(map.get(null), "value not null");376assertSame(map.compute(null, (k, v) -> {377assertNull(k);378assertNull(v);379return null;380}), null, description);381assertFalse(map.containsKey(null), description + ": null key present.");382assertSame(map.compute(null, (k, v) -> {383assertSame(k, null);384assertNull(v);385return EXTRA_VALUE;386}), EXTRA_VALUE, description);387assertTrue(map.containsKey(null));388assertSame(map.get(null), EXTRA_VALUE, description);389assertSame(map.remove(null), EXTRA_VALUE, description + ": removed value not expected");390// no mapping before and after391assertFalse(map.containsKey(null), description + ": null key present");392assertSame(map.compute(null, (k, v) -> {393assertNull(k);394assertNull(v);395return null;396}), null, description + ": expected null result" );397assertFalse(map.containsKey(null), description + ": null key present");398// compute with map not containing value399assertNull(map.remove(EXTRA_KEY), description + ": unexpected mapping");400assertFalse(map.containsKey(EXTRA_KEY), description + ": key present");401assertSame(map.compute(EXTRA_KEY, (k, v) -> {402assertSame(k, EXTRA_KEY);403assertNull(v);404return null;405}), null, description);406assertFalse(map.containsKey(EXTRA_KEY), description + ": null key present");407// ensure removal.408assertNull(map.put(EXTRA_KEY, EXTRA_VALUE));409assertSame(map.compute(EXTRA_KEY, (k, v) -> {410assertSame(k, EXTRA_KEY);411assertSame(v, EXTRA_VALUE);412return null;413}), null, description + ": null resulted expected");414assertFalse(map.containsKey(EXTRA_KEY), description + ": null key present");415// compute with map containing null value416assertNull(map.put(EXTRA_KEY, null), description + ": unexpected value");417assertSame(map.compute(EXTRA_KEY, (k, v) -> {418assertSame(k, EXTRA_KEY);419assertNull(v);420return null;421}), null, description);422assertFalse(map.containsKey(EXTRA_KEY), description + ": null key present");423assertNull(map.put(EXTRA_KEY, null), description + ": unexpected value");424assertSame(map.compute(EXTRA_KEY, (k, v) -> {425assertSame(k, EXTRA_KEY);426assertNull(v);427return EXTRA_VALUE;428}), EXTRA_VALUE, description);429assertTrue(map.containsKey(EXTRA_KEY), "null key present");430}431432@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")433public void testCompute(String description, Map<IntegerEnum, String> map) {434assertTrue(map.containsKey(KEYS[1]));435Object value = map.get(KEYS[1]);436assertTrue(null == value || value == VALUES[1], description + String.valueOf(value));437assertSame(map.compute(KEYS[1], (k, v) -> {438assertSame(k, KEYS[1]);439assertSame(v, value);440return EXTRA_VALUE;441}), EXTRA_VALUE, description);442assertSame(map.get(KEYS[1]), EXTRA_VALUE, description);443assertNull(map.compute(KEYS[1], (k, v) -> {444assertSame(v, EXTRA_VALUE);445return null;446}), description);447assertFalse(map.containsKey(KEYS[1]));448449assertFalse(map.containsKey(EXTRA_KEY));450assertSame(map.compute(EXTRA_KEY, (k, v) -> {451assertNull(v);452return EXTRA_VALUE;453}), EXTRA_VALUE);454assertTrue(map.containsKey(EXTRA_KEY));455assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);456}457458@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")459public void testComputeNullFunction(String description, Map<IntegerEnum, String> map) {460assertThrowsNPE(() -> map.compute(KEYS[1], null));461}462463@Test(dataProvider = "MergeCases")464private void testMerge(String description, Map<IntegerEnum, String> map, Merging.Value oldValue, Merging.Value newValue, Merging.Merger merger, Merging.Value put, Merging.Value result) {465// add and check initial conditions.466switch (oldValue) {467case ABSENT :468map.remove(EXTRA_KEY);469assertFalse(map.containsKey(EXTRA_KEY), "key not absent");470break;471case NULL :472map.put(EXTRA_KEY, null);473assertTrue(map.containsKey(EXTRA_KEY), "key absent");474assertNull(map.get(EXTRA_KEY), "wrong value");475break;476case OLDVALUE :477map.put(EXTRA_KEY, VALUES[1]);478assertTrue(map.containsKey(EXTRA_KEY), "key absent");479assertSame(map.get(EXTRA_KEY), VALUES[1], "wrong value");480break;481default:482fail("unexpected old value");483}484485String returned = map.merge(EXTRA_KEY,486newValue == Merging.Value.NULL ? (String) null : VALUES[2],487merger488);489490// check result491492switch (result) {493case NULL :494assertNull(returned, "wrong value");495break;496case NEWVALUE :497assertSame(returned, VALUES[2], "wrong value");498break;499case RESULT :500assertSame(returned, VALUES[3], "wrong value");501break;502default:503fail("unexpected new value");504}505506// check map507switch (put) {508case ABSENT :509assertFalse(map.containsKey(EXTRA_KEY), "key not absent");510break;511case NULL :512assertTrue(map.containsKey(EXTRA_KEY), "key absent");513assertNull(map.get(EXTRA_KEY), "wrong value");514break;515case NEWVALUE :516assertTrue(map.containsKey(EXTRA_KEY), "key absent");517assertSame(map.get(EXTRA_KEY), VALUES[2], "wrong value");518break;519case RESULT :520assertTrue(map.containsKey(EXTRA_KEY), "key absent");521assertSame(map.get(EXTRA_KEY), VALUES[3], "wrong value");522break;523default:524fail("unexpected new value");525}526}527528@Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")529public void testMergeNullMerger(String description, Map<IntegerEnum, String> map) {530assertThrowsNPE(() -> map.merge(KEYS[1], VALUES[1], null));531}532533/** A function that flipflops between running two other functions. */534static <T,U,V> BiFunction<T,U,V> twoStep(AtomicBoolean b,535BiFunction<T,U,V> first,536BiFunction<T,U,V> second) {537return (t, u) -> {538boolean bb = b.get();539try {540return (b.get() ? first : second).apply(t, u);541} finally {542b.set(!bb);543}};544}545546/**547* Simulates races by modifying the map within the mapping function.548*/549@Test550public void testConcurrentMap_computeIfAbsent_racy() {551final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();552final Long two = 2L;553Function<Long,Long> f, g;554555// race not detected if function returns null556f = (k) -> { map.put(two, 42L); return null; };557assertNull(map.computeIfAbsent(two, f));558assertEquals(42L, (long)map.get(two));559560map.clear();561f = (k) -> { map.put(two, 42L); return 86L; };562assertEquals(42L, (long)map.computeIfAbsent(two, f));563assertEquals(42L, (long)map.get(two));564565// mapping function ignored if value already exists566map.put(two, 99L);567assertEquals(99L, (long)map.computeIfAbsent(two, f));568assertEquals(99L, (long)map.get(two));569}570571/**572* Simulates races by modifying the map within the remapping function.573*/574@Test575public void testConcurrentMap_computeIfPresent_racy() {576final AtomicBoolean b = new AtomicBoolean(true);577final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();578final Long two = 2L;579BiFunction<Long,Long,Long> f, g;580581for (Long val : new Long[] { null, 86L }) {582map.clear();583584// Function not invoked if no mapping exists585f = (k, v) -> { map.put(two, 42L); return val; };586assertNull(map.computeIfPresent(two, f));587assertNull(map.get(two));588589map.put(two, 42L);590f = (k, v) -> { map.put(two, 86L); return val; };591g = (k, v) -> {592assertSame(two, k);593assertEquals(86L, (long)v);594return null;595};596assertNull(map.computeIfPresent(two, twoStep(b, f, g)));597assertFalse(map.containsKey(two));598assertTrue(b.get());599600map.put(two, 42L);601f = (k, v) -> { map.put(two, 86L); return val; };602g = (k, v) -> {603assertSame(two, k);604assertEquals(86L, (long)v);605return 99L;606};607assertEquals(99L, (long)map.computeIfPresent(two, twoStep(b, f, g)));608assertTrue(map.containsKey(two));609assertTrue(b.get());610}611}612613@Test614public void testConcurrentMap_compute_simple() {615final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();616BiFunction<Long,Long,Long> fun = (k, v) -> ((v == null) ? 0L : k + v);617assertEquals(Long.valueOf(0L), map.compute(3L, fun));618assertEquals(Long.valueOf(3L), map.compute(3L, fun));619assertEquals(Long.valueOf(6L), map.compute(3L, fun));620assertNull(map.compute(3L, (k, v) -> null));621assertTrue(map.isEmpty());622623assertEquals(Long.valueOf(0L), map.compute(new Long(3L), fun));624assertEquals(Long.valueOf(3L), map.compute(new Long(3L), fun));625assertEquals(Long.valueOf(6L), map.compute(new Long(3L), fun));626assertNull(map.compute(3L, (k, v) -> null));627assertTrue(map.isEmpty());628}629630/**631* Simulates races by modifying the map within the remapping function.632*/633@Test634public void testConcurrentMap_compute_racy() {635final AtomicBoolean b = new AtomicBoolean(true);636final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();637final Long two = 2L;638BiFunction<Long,Long,Long> f, g;639640// null -> null is a no-op; race not detected641f = (k, v) -> { map.put(two, 42L); return null; };642assertNull(map.compute(two, f));643assertEquals(42L, (long)map.get(two));644645for (Long val : new Long[] { null, 86L }) {646map.clear();647648f = (k, v) -> { map.put(two, 42L); return 86L; };649g = (k, v) -> {650assertSame(two, k);651assertEquals(42L, (long)v);652return k + v;653};654assertEquals(44L, (long)map.compute(two, twoStep(b, f, g)));655assertEquals(44L, (long)map.get(two));656assertTrue(b.get());657658f = (k, v) -> { map.remove(two); return val; };659g = (k, v) -> {660assertSame(two, k);661assertNull(v);662return 44L;663};664assertEquals(44L, (long)map.compute(two, twoStep(b, f, g)));665assertEquals(44L, (long)map.get(two));666assertTrue(map.containsKey(two));667assertTrue(b.get());668669f = (k, v) -> { map.remove(two); return val; };670g = (k, v) -> {671assertSame(two, k);672assertNull(v);673return null;674};675assertNull(map.compute(two, twoStep(b, f, g)));676assertNull(map.get(two));677assertFalse(map.containsKey(two));678assertTrue(b.get());679}680}681682/**683* Simulates races by modifying the map within the remapping function.684*/685@Test686public void testConcurrentMap_merge_racy() {687final AtomicBoolean b = new AtomicBoolean(true);688final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();689final Long two = 2L;690BiFunction<Long,Long,Long> f, g;691692for (Long val : new Long[] { null, 86L }) {693map.clear();694695f = (v, w) -> { throw new AssertionError(); };696assertEquals(99L, (long)map.merge(two, 99L, f));697assertEquals(99L, (long)map.get(two));698699f = (v, w) -> { map.put(two, 42L); return val; };700g = (v, w) -> {701assertEquals(42L, (long)v);702assertEquals(3L, (long)w);703return v + w;704};705assertEquals(45L, (long)map.merge(two, 3L, twoStep(b, f, g)));706assertEquals(45L, (long)map.get(two));707assertTrue(b.get());708709f = (v, w) -> { map.remove(two); return val; };710g = (k, v) -> { throw new AssertionError(); };711assertEquals(55L, (long)map.merge(two, 55L, twoStep(b, f, g)));712assertEquals(55L, (long)map.get(two));713assertTrue(map.containsKey(two));714assertFalse(b.get()); b.set(true);715}716}717718public enum IntegerEnum {719720e0, e1, e2, e3, e4, e5, e6, e7, e8, e9,721e10, e11, e12, e13, e14, e15, e16, e17, e18, e19,722e20, e21, e22, e23, e24, e25, e26, e27, e28, e29,723e30, e31, e32, e33, e34, e35, e36, e37, e38, e39,724e40, e41, e42, e43, e44, e45, e46, e47, e48, e49,725e50, e51, e52, e53, e54, e55, e56, e57, e58, e59,726e60, e61, e62, e63, e64, e65, e66, e67, e68, e69,727e70, e71, e72, e73, e74, e75, e76, e77, e78, e79,728e80, e81, e82, e83, e84, e85, e86, e87, e88, e89,729e90, e91, e92, e93, e94, e95, e96, e97, e98, e99,730EXTRA_KEY;731public static final int SIZE = values().length;732}733private static final int TEST_SIZE = IntegerEnum.SIZE - 1;734/**735* Realized keys ensure that there is always a hard ref to all test objects.736*/737private static final IntegerEnum[] KEYS = new IntegerEnum[TEST_SIZE];738/**739* Realized values ensure that there is always a hard ref to all test740* objects.741*/742private static final String[] VALUES = new String[TEST_SIZE];743744static {745IntegerEnum[] keys = IntegerEnum.values();746for (int each = 0; each < TEST_SIZE; each++) {747KEYS[each] = keys[each];748VALUES[each] = String.valueOf(each);749}750}751752private static final IntegerEnum FIRST_KEY = KEYS[0];753private static final String FIRST_VALUE = VALUES[0];754private static final IntegerEnum EXTRA_KEY = IntegerEnum.EXTRA_KEY;755private static final String EXTRA_VALUE = String.valueOf(TEST_SIZE);756757@DataProvider(name = "Map<IntegerEnum,String> rw=all keys=all values=all", parallel = true)758public static Iterator<Object[]> allMapProvider() {759return makeAllMaps().iterator();760}761762@DataProvider(name = "Map<IntegerEnum,String> rw=all keys=withNull values=withNull", parallel = true)763public static Iterator<Object[]> allMapWithNullsProvider() {764return makeAllMapsWithNulls().iterator();765}766767@DataProvider(name = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull", parallel = true)768public static Iterator<Object[]> rwNonNullMapProvider() {769return makeRWNoNullsMaps().iterator();770}771772@DataProvider(name = "Map<IntegerEnum,String> rw=true keys=nonNull values=all", parallel = true)773public static Iterator<Object[]> rwNonNullKeysMapProvider() {774return makeRWMapsNoNulls().iterator();775}776777@DataProvider(name = "Map<IntegerEnum,String> rw=true keys=all values=all", parallel = true)778public static Iterator<Object[]> rwMapProvider() {779return makeAllRWMaps().iterator();780}781782@DataProvider(name = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull", parallel = true)783public static Iterator<Object[]> rwNullsMapProvider() {784return makeAllRWMapsWithNulls().iterator();785}786787private static Collection<Object[]> makeAllRWMapsWithNulls() {788Collection<Object[]> all = new ArrayList<>();789790all.addAll(makeRWMaps(true, true));791792return all;793}794795private static Collection<Object[]> makeRWMapsNoNulls() {796Collection<Object[]> all = new ArrayList<>();797798all.addAll(makeRWNoNullKeysMaps(false));799all.addAll(makeRWNoNullsMaps());800801return all;802}803804private static Collection<Object[]> makeAllROMaps() {805Collection<Object[]> all = new ArrayList<>();806807all.addAll(makeROMaps(false));808all.addAll(makeROMaps(true));809810return all;811}812813private static Collection<Object[]> makeAllRWMaps() {814Collection<Object[]> all = new ArrayList<>();815816all.addAll(makeRWNoNullsMaps());817all.addAll(makeRWMaps(false,true));818all.addAll(makeRWMaps(true,true));819all.addAll(makeRWNoNullKeysMaps(true));820return all;821}822823private static Collection<Object[]> makeAllMaps() {824Collection<Object[]> all = new ArrayList<>();825826all.addAll(makeAllROMaps());827all.addAll(makeAllRWMaps());828829return all;830}831832private static Collection<Object[]> makeAllMapsWithNulls() {833Collection<Object[]> all = new ArrayList<>();834835all.addAll(makeROMaps(true));836all.addAll(makeRWMaps(true,true));837838return all;839}840841/**842* @param nullKeys include null keys843* @param nullValues include null values844* @return845*/846private static Collection<Object[]> makeRWMaps(boolean nullKeys, boolean nullValues) {847return Arrays.asList(848new Object[]{"HashMap", makeMap(HashMap::new, nullKeys, nullValues)},849new Object[]{"IdentityHashMap", makeMap(IdentityHashMap::new, nullKeys, nullValues)},850new Object[]{"LinkedHashMap", makeMap(LinkedHashMap::new, nullKeys, nullValues)},851new Object[]{"WeakHashMap", makeMap(WeakHashMap::new, nullKeys, nullValues)},852new Object[]{"Collections.checkedMap(HashMap)", Collections.checkedMap(makeMap(HashMap::new, nullKeys, nullValues), IntegerEnum.class, String.class)},853new Object[]{"Collections.synchronizedMap(HashMap)", Collections.synchronizedMap(makeMap(HashMap::new, nullKeys, nullValues))},854new Object[]{"ExtendsAbstractMap", makeMap(ExtendsAbstractMap::new, nullKeys, nullValues)});855}856857/**858* @param nulls include null values859* @return860*/861private static Collection<Object[]> makeRWNoNullKeysMaps(boolean nulls) {862return Arrays.asList(863// null key hostile864new Object[]{"EnumMap", makeMap(() -> new EnumMap(IntegerEnum.class), false, nulls)},865new Object[]{"TreeMap", makeMap(TreeMap::new, false, nulls)},866new Object[]{"ExtendsAbstractMap(TreeMap)", makeMap(() -> {return new ExtendsAbstractMap(new TreeMap());}, false, nulls)},867new Object[]{"Collections.synchronizedMap(EnumMap)", Collections.synchronizedMap(makeMap(() -> new EnumMap(IntegerEnum.class), false, nulls))}868);869}870871private static Collection<Object[]> makeRWNoNullsMaps() {872return Arrays.asList(873// null key and value hostile874new Object[]{"Hashtable", makeMap(Hashtable::new, false, false)},875new Object[]{"ConcurrentHashMap", makeMap(ConcurrentHashMap::new, false, false)},876new Object[]{"ConcurrentSkipListMap", makeMap(ConcurrentSkipListMap::new, false, false)},877new Object[]{"Collections.synchronizedMap(ConcurrentHashMap)", Collections.synchronizedMap(makeMap(ConcurrentHashMap::new, false, false))},878new Object[]{"Collections.checkedMap(ConcurrentHashMap)", Collections.checkedMap(makeMap(ConcurrentHashMap::new, false, false), IntegerEnum.class, String.class)},879new Object[]{"ExtendsAbstractMap(ConcurrentHashMap)", makeMap(() -> {return new ExtendsAbstractMap(new ConcurrentHashMap());}, false, false)},880new Object[]{"ImplementsConcurrentMap", makeMap(ImplementsConcurrentMap::new, false, false)}881);882}883884/**885* @param nulls include nulls886* @return887*/888private static Collection<Object[]> makeROMaps(boolean nulls) {889return Arrays.asList(new Object[][]{890new Object[]{"Collections.unmodifiableMap(HashMap)", Collections.unmodifiableMap(makeMap(HashMap::new, nulls, nulls))}891});892}893894/**895* @param supplier a supplier of mutable map instances.896*897* @param nullKeys include null keys898* @param nullValues include null values899* @return900*/901private static Map<IntegerEnum, String> makeMap(Supplier<Map<IntegerEnum, String>> supplier, boolean nullKeys, boolean nullValues) {902Map<IntegerEnum, String> result = supplier.get();903904for (int each = 0; each < TEST_SIZE; each++) {905IntegerEnum key = nullKeys ? (each == 0) ? null : KEYS[each] : KEYS[each];906String value = nullValues ? (each == 0) ? null : VALUES[each] : VALUES[each];907908result.put(key, value);909}910911return result;912}913914static class Merging {915public enum Value {916ABSENT,917NULL,918OLDVALUE,919NEWVALUE,920RESULT921}922923public enum Merger implements BiFunction<String,String,String> {924UNUSED {925public String apply(String oldValue, String newValue) {926fail("should not be called");927return null;928}929},930NULL {931public String apply(String oldValue, String newValue) {932return null;933}934},935RESULT {936public String apply(String oldValue, String newValue) {937return VALUES[3];938}939},940}941}942943@DataProvider(name = "MergeCases", parallel = true)944public Iterator<Object[]> mergeCasesProvider() {945Collection<Object[]> cases = new ArrayList<>();946947cases.addAll(makeMergeTestCases());948949return cases.iterator();950}951952static Collection<Object[]> makeMergeTestCases() {953Collection<Object[]> cases = new ArrayList<>();954955for (Object[] mapParams : makeAllRWMaps() ) {956cases.add(new Object[] { mapParams[0], mapParams[1], Merging.Value.ABSENT, Merging.Value.NEWVALUE, Merging.Merger.UNUSED, Merging.Value.NEWVALUE, Merging.Value.NEWVALUE });957}958959for (Object[] mapParams : makeAllRWMaps() ) {960cases.add(new Object[] { mapParams[0], mapParams[1], Merging.Value.OLDVALUE, Merging.Value.NEWVALUE, Merging.Merger.NULL, Merging.Value.ABSENT, Merging.Value.NULL });961}962963for (Object[] mapParams : makeAllRWMaps() ) {964cases.add(new Object[] { mapParams[0], mapParams[1], Merging.Value.OLDVALUE, Merging.Value.NEWVALUE, Merging.Merger.RESULT, Merging.Value.RESULT, Merging.Value.RESULT });965}966967return cases;968}969970public static void assertThrowsNPE(ThrowingRunnable r) {971assertThrows(NullPointerException.class, r);972}973974/**975* A simple mutable map implementation that provides only default976* implementations of all methods. ie. none of the Map interface default977* methods have overridden implementations.978*979* @param <K> Type of keys980* @param <V> Type of values981*/982public static class ExtendsAbstractMap<M extends Map<K,V>, K, V> extends AbstractMap<K,V> {983984protected final M map;985986public ExtendsAbstractMap() { this( (M) new HashMap<K,V>()); }987988protected ExtendsAbstractMap(M map) { this.map = map; }989990@Override public Set<Map.Entry<K,V>> entrySet() {991return new AbstractSet<Map.Entry<K,V>>() {992@Override public int size() {993return map.size();994}995996@Override public Iterator<Map.Entry<K,V>> iterator() {997final Iterator<Map.Entry<K,V>> source = map.entrySet().iterator();998return new Iterator<Map.Entry<K,V>>() {999public boolean hasNext() { return source.hasNext(); }1000public Map.Entry<K,V> next() { return source.next(); }1001public void remove() { source.remove(); }1002};1003}10041005@Override public boolean add(Map.Entry<K,V> e) {1006return map.entrySet().add(e);1007}1008};1009}10101011@Override public V put(K key, V value) {1012return map.put(key, value);1013}1014}10151016/**1017* A simple mutable concurrent map implementation that provides only default1018* implementations of all methods, i.e. none of the ConcurrentMap interface1019* default methods have overridden implementations.1020*1021* @param <K> Type of keys1022* @param <V> Type of values1023*/1024public static class ImplementsConcurrentMap<K,V> extends ExtendsAbstractMap<ConcurrentMap<K,V>, K, V> implements ConcurrentMap<K,V> {1025public ImplementsConcurrentMap() { super(new ConcurrentHashMap<K,V>()); }10261027// ConcurrentMap reabstracts these methods.1028//1029// Unlike ConcurrentHashMap, we have zero tolerance for null values.10301031@Override public V replace(K k, V v) {1032return map.replace(requireNonNull(k), requireNonNull(v));1033}10341035@Override public boolean replace(K k, V v, V vv) {1036return map.replace(requireNonNull(k),1037requireNonNull(v),1038requireNonNull(vv));1039}10401041@Override public boolean remove(Object k, Object v) {1042return map.remove(requireNonNull(k), requireNonNull(v));1043}10441045@Override public V putIfAbsent(K k, V v) {1046return map.putIfAbsent(requireNonNull(k), requireNonNull(v));1047}1048}1049}105010511052