Path: blob/master/test/jdk/java/security/SecureRandom/ThreadSafe.java
41149 views
/*1* Copyright (c) 2016, 2020, 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*/2223import java.security.Provider;24import java.security.SecureRandom;25import java.security.SecureRandomSpi;26import java.util.Map;2728/*29* @test30* @bug 700496731* @summary SecureRandom should be more explicit about threading32*/33public class ThreadSafe {34public static void main(String[] args) throws Exception {35Provider p = new P();36NoSync.test(SecureRandom.getInstance("S1", p), 5, 5);37try {38NoSync.test(SecureRandom.getInstance("S2", p), 5, 5);39throw new Exception("Failed");40} catch (RuntimeException re) {41// Good42}43NoSync.test(SecureRandom.getInstance("S3", p), 5, 5);44try {45NoSync.test(SecureRandom.getInstance("S4", p), 5, 5);46throw new Exception("Failed");47} catch (RuntimeException re) {48// Good49}50}5152public static class P extends Provider {53public P() {5455super("P", 1.0d, "Haha");5657// Good. No attribute.58put("SecureRandom.S1", S.class.getName());5960// Bad. Boasting ThreadSafe but isn't61put("SecureRandom.S2", S.class.getName());62put("SecureRandom.S2 ThreadSafe", "true");6364// Good. No attribute.65putService(new Service(this, "SecureRandom", "S3",66S.class.getName(), null, null));6768// Bad. Boasting ThreadSafe but isn't69putService(new Service(this, "SecureRandom", "S4",70S.class.getName(), null, Map.of("ThreadSafe", "true")));71}72}7374// This implementation is not itself thread safe.75public static class S extends SecureRandomSpi {76@java.lang.Override77protected void engineSetSeed(byte[] seed) {78return;79}8081private volatile boolean inCall = false;82@Override83protected void engineNextBytes(byte[] bytes) {84if (inCall) {85throw new RuntimeException("IN CALL");86}87inCall = true;88try {89Thread.sleep(500);90} catch (Exception e) {91// OK92}93inCall = false;94}9596@Override97protected byte[] engineGenerateSeed(int numBytes) {98return new byte[numBytes];99}100}101}102103104