Path: blob/master/test/jdk/java/net/InetAddress/HashSpread.java
41149 views
/*1* Copyright (c) 2002, 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 468790926* @summary Check Inet6Address.hashCode returns a reasonable spread of hash27* codes.28* @key randomness29*/30import java.net.InetAddress;31import java.net.UnknownHostException;32import java.util.Random;3334public class HashSpread {3536static Random r = new Random();3738/**39* Generate and return a random IPv6 address.40*/41static InetAddress randomIPv6Adress() {42StringBuffer sb = new StringBuffer();4344for (int i=0; i<8; i++) {4546if (i > 0)47sb.append(":");4849for (int j=0; j<4; j++) {50int v = r.nextInt(16);51if (v < 10) {52sb.append(Integer.toString(v));53} else {54char c = (char) ('A' + v - 10);55sb.append(c);56}57}58}5960try {61return InetAddress.getByName(sb.toString());62} catch (UnknownHostException x) {63throw new Error("Internal error in test");64}65}6667public static void main(String args[]) throws Exception {6869int iterations = 10000;70if (args.length > 0) {71iterations = Integer.parseInt(args[0]);72}7374int MIN_SHORT = (int)Short.MIN_VALUE;75int MAX_SHORT = (int)Short.MAX_VALUE;7677/*78* Iterate through 10k hash codes and count the number79* in the MIN_SHORT-MAX_SHORT range.80*/81int narrow = 0;82for (int i=0; i<iterations; i++) {83int hc = randomIPv6Adress().hashCode();84if (hc >= MIN_SHORT && hc <= MAX_SHORT) {85narrow++;86}87}8889/*90* If >85% of hash codes in the range then fail.91*/92double percent = (double)narrow / (double)iterations * 100.0;93if (percent > 85.0) {94throw new RuntimeException(percent + " of hash codes were in " +95MIN_SHORT + " to " + MAX_SHORT + " range.");96}9798}99100}101102103