Path: blob/master/test/jdk/java/util/Collection/RandomizedIteration.java
41149 views
/*1* Copyright (c) 2018, 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 820151826* @key randomness27* @summary Ensure that randomized iteration order of unmodifiable sets28* and maps is actually randomized. Must be run othervm so that29* the per-VM-instance salt value differs.30* @run main/othervm RandomizedIteration 031* @run main/othervm RandomizedIteration 132* @run main/othervm RandomizedIteration 233* @run main/othervm RandomizedIteration 334* @run main/othervm RandomizedIteration 435* @run main/othervm RandomizedIteration verify 536*/3738import java.io.IOException;39import java.io.PrintStream;40import java.nio.file.Files;41import java.nio.file.Paths;42import java.util.Arrays;43import java.util.HashSet;44import java.util.Map;45import java.util.Set;4647import static java.util.stream.Collectors.toUnmodifiableMap;4849/**50* Test of randomized iteration of unmodifiable sets and maps.51*52* Usage: RandomizedIteration n53* - writes files suffixed with 'n' containing set elements and map keys54* in iteration order55* RandomizedIteration "verify" count56* - reads files 0..count-1 and checks to ensure that their orders differ57*58* The idea is to generate several test files by invoking this test with an arg59* of 0 through count-1. Then invoke the test once more with two args, the first being60* the word "verify" and the second arg being the count. This will read all the generated61* files and perform verification.62*63* The test is considered to pass if any of the runs result in different iteration64* orders. The randomization is not actually very random, so over many runs there is65* the possibility of a couple of the test files having the same order. That's ok, as66* long as the iteration order is usually different. The test fails if *all* of the67* iteration orders are the same.68*/69public class RandomizedIteration {70/**71* Generates a set and a map from the word array, and then writes72* text files "set.#" and "map.#" containing the set elements and73* map keys in iteration order.74*75* @param suffix number used for the file suffix76*/77static void writeFiles(int suffix) throws IOException {78try (PrintStream setOut = new PrintStream("set." + suffix)) {79Set.of(WORDS)80.forEach(setOut::println);81}8283try (PrintStream mapOut = new PrintStream("map." + suffix)) {84var map = Map.ofEntries(Arrays.stream(WORDS)85.map(word -> Map.entry(word, ""))86.toArray(Map.Entry<?, ?>[]::new));87map.keySet()88.forEach(mapOut::println);89}90}9192/**93* Reads lines from each file derived from the prefix and index from 0..count-194* into a list, computes its hashcode, and returns a set of those hashcodes.95* The hashcode of the list is order sensitive, so the same lines in a different96* order should have different hashcodes.97*98* @param prefix the file prefix99* @param count the number of files to read100* @return a set of hashcodes of each file101*/102static Set<Integer> readFiles(String prefix, int count) throws IOException {103Set<Integer> hashes = new HashSet<>();104for (int suffix = 0; suffix < count; suffix++) {105String name = prefix + suffix;106int hash = Files.readAllLines(Paths.get(name)).hashCode();107System.out.println(name + ": " + hash);108hashes.add(hash);109}110return hashes;111}112113/**114* Test main routine.115*116* @param args n | "verify" count117* @throws IOException if an error occurred118*/119public static void main(String[] args) throws IOException {120if ("verify".equals(args[0])) {121int count = Integer.parseInt(args[1]);122System.out.println("Verifying " + count + " files.");123Set<Integer> setHashes = readFiles("set.", count);124Set<Integer> mapHashes = readFiles("map.", count);125if (setHashes.size() > 1 && mapHashes.size() > 1) {126System.out.println("Passed: differing iteration orders were detected.");127} else {128throw new AssertionError("FAILED: iteration order not randomized!");129}130} else {131int suffix = Integer.parseInt(args[0]);132System.out.println("Generating files: " + suffix);133writeFiles(suffix);134}135}136137/**138* List of 63 words of 22 or more letters from BSD /usr/share/dict/words.139*/140static final String[] WORDS = {141"anatomicophysiological",142"anthropomorphologically",143"aquopentamminecobaltic",144"blepharoconjunctivitis",145"blepharosphincterectomy",146"cholecystenterorrhaphy",147"cholecystoduodenostomy",148"choledochoduodenostomy",149"counterexcommunication",150"dacryocystoblennorrhea",151"dacryocystosyringotomy",152"deanthropomorphization",153"duodenocholecystostomy",154"electroencephalography",155"electrotelethermometer",156"epididymodeferentectomy",157"formaldehydesulphoxylate",158"formaldehydesulphoxylic",159"gastroenteroanastomosis",160"hematospectrophotometer",161"hexamethylenetetramine",162"hexanitrodiphenylamine",163"historicocabbalistical",164"hydropneumopericardium",165"hyperconscientiousness",166"laparocolpohysterotomy",167"lymphangioendothelioma",168"macracanthrorhynchiasis",169"microcryptocrystalline",170"naphthylaminesulphonic",171"nonrepresentationalism",172"omnirepresentativeness",173"pancreaticoduodenostomy",174"pancreaticogastrostomy",175"pathologicohistological",176"pathologicopsychological",177"pericardiomediastinitis",178"phenolsulphonephthalein",179"philosophicohistorical",180"philosophicotheological",181"photochronographically",182"photospectroheliograph",183"pneumohydropericardium",184"pneumoventriculography",185"polioencephalomyelitis",186"Prorhipidoglossomorpha",187"Pseudolamellibranchiata",188"pseudolamellibranchiate",189"pseudomonocotyledonous",190"pyopneumocholecystitis",191"scientificogeographical",192"scientificophilosophical",193"scleroticochorioiditis",194"stereophotomicrography",195"tetraiodophenolphthalein",196"theologicoastronomical",197"theologicometaphysical",198"thymolsulphonephthalein",199"thyroparathyroidectomize",200"thyroparathyroidectomy",201"transubstantiationalist",202"ureterocystanastomosis",203"zoologicoarchaeologist"204};205}206207208