List of usage examples for java.util.concurrent ThreadLocalRandom current
public static ThreadLocalRandom current()
From source file:xyz.lejon.sampling.GammaDistribution.java
public static double nextExpGamma(double shape, double scale, double bias, boolean slowCode) { double sample; double accept; int iters = 0; if (slowCode) { // for testing purposes -- this can get stuck completely for small bias parameters do {// w w w. jav a 2 s .co m sample = nextGamma(shape, scale); accept = Math.exp(-1.0 / (bias * sample)); } while (ThreadLocalRandom.current().nextDouble() > accept); } else { if (shape < 0) { //return scale / (nextExpGamma(-shape, scale, bias) * bias); return 1.0 / nextExpGamma(-shape, bias, scale); } if (shape == 0) { // sample from the restriction to x >= median, and sample the other half by using // the self-similarity transformation x -> scale / (bias*x) double median = Math.sqrt(scale / bias); double rejection_mode = 1.0 / bias; // mode of rejection distribution, x^-1 e^(-1/bias x) if (rejection_mode < median) rejection_mode = median; double rejection_norm = (1.0 / rejection_mode) * Math.exp(-1.0 / (bias * rejection_mode)); do { sample = nextGamma(1.0, scale) + median; accept = (1.0 / sample) * Math.exp(-1.0 / (sample * bias)) / rejection_norm; iters += 1; } while (ThreadLocalRandom.current().nextDouble() > accept && iters < 10000); if (iters == 10000) { System.out.println( "Severe Warning: nextExpGamma (shape=0) failed to generate a sample - returning bogus value!"); } if (ThreadLocalRandom.current().nextDouble() > 0.5) { sample = scale / (bias * sample); } return sample; } // Current algorithm works for all shape parameters > 0, but it becomes very inefficient // for v. small shape parameters. if (shape <= 0.0) { System.out.println("nextExpGamma: Illegal argument (shape parameter is must be positive)"); throw new IllegalArgumentException(""); } // the function -1/(bias*x) is bounded by x/(bias x0^2) + C, with C = -2/(bias*x0), so that these functions // coincide precisely when x=x0. This gives the scale parameter of the majorating Gamma distribution // // First calculate the value that maximizes the acceptance probability at the mean of the proposal distribution double x0 = (shape * scale + Math.sqrt(4 * scale / bias + shape * shape * scale * scale)) / 2.0; // calculate the scale parameter of the majorating Gamma distribution double majorandScale = 1.0 / ((1.0 / scale) - 1.0 / (bias * x0 * x0)); // now do rejection sampling do { sample = nextGamma(shape, majorandScale); accept = Math.exp(-(sample / x0 - 1) * (sample / x0 - 1) / (bias * sample)); iters += 1; } while (ThreadLocalRandom.current().nextDouble() > accept && iters < 10000); if (accept > 1.0) { System.out.println("PROBLEM!! This should be impossible!! Contact the authors."); } if (majorandScale < 0.0) { System.out.println("PROBLEM!! This should be impossible too!! Contact the authors."); } if (iters == 10000) { System.out.println( "Severe Warning: nextExpGamma failed to generate a sample - returning bogus value!"); } } return sample; }
From source file:org.neo4j.kernel.api.impl.index.LuceneSchemaIndexUniquenessVerificationIT.java
private Set<PropertyValue> randomArrays(int minLength, int maxLength) { Randoms randoms = new Randoms(ThreadLocalRandom.current(), new ArraySizeConfig(minLength, maxLength)); return IntStream.range(0, nodesToCreate).mapToObj(i -> randoms.array()).map(PropertyValue::new) .collect(toSet());/*from www.ja v a2s .c o m*/ }
From source file:org.neo4j.kernel.api.impl.index.LuceneSchemaIndexUniquenessVerificationIT.java
private static List<PropertyValue> withDuplicate(Set<PropertyValue> set) { List<PropertyValue> data = new ArrayList<>(set); if (data.isEmpty()) { throw new IllegalStateException(); } else if (data.size() == 1) { data.add(data.get(0));/* ww w. j a v a 2 s . c om*/ } else { int duplicateIndex = (int) randomLongInRange(0, data.size()); int duplicateValueIndex; do { duplicateValueIndex = ThreadLocalRandom.current().nextInt(data.size()); } while (duplicateValueIndex == duplicateIndex); PropertyValue duplicateValue = data.get(duplicateValueIndex); data.set(duplicateIndex, duplicateValue); } return data; }
From source file:org.neo4j.kernel.api.impl.index.LuceneSchemaIndexUniquenessVerificationIT.java
private Set<PropertyValue> randomPropertyValues() { Randoms randoms = new Randoms(ThreadLocalRandom.current(), new ArraySizeConfig(5, 100)); return IntStream.range(0, nodesToCreate).mapToObj(i -> randoms.propertyValue()).map(PropertyValue::new) .collect(toSet());//from www . j a v a 2 s . c om }
From source file:org.neo4j.kernel.api.impl.index.LuceneSchemaIndexUniquenessVerificationIT.java
private static long randomLongInRange(long min, long max) { return ThreadLocalRandom.current().nextLong(min, max); }
From source file:org.apache.metron.maas.discovery.ServiceDiscoverer.java
/** * Retrieve an endpoint at random of a given model * @param model/* w w w . j a v a2 s .co m*/ * @return */ public ModelEndpoint getEndpoint(Model model) { rwLock.readLock().lock(); try { List<ModelEndpoint> endpoints = state.get(model); ModelEndpoint ret = null; if (endpoints != null) { for (int j = 0; j < 10; ++j) { int i = ThreadLocalRandom.current().nextInt(endpoints.size()); ret = endpoints.get(i); try { if (blacklist.asMap().containsKey(toUrl(ret.getEndpoint().getUrl()))) { continue; } else { return ret; } } catch (IllegalStateException ise) { /* If an exception happens on an attempt then we move on. Frankly this is an excess of caution since we parse the URLs in the Runner before they go into zookeeper, so they are valid. */ } } } return ret; } finally { rwLock.readLock().unlock(); } }
From source file:org.neo4j.kernel.api.impl.index.LuceneSchemaIndexUniquenessVerificationIT.java
private static double randomDoubleInRange(double min, double max) { return ThreadLocalRandom.current().nextDouble(min, max); }
From source file:org.apache.bookkeeper.stream.storage.impl.TestStorageContainerStoreImpl.java
@SuppressWarnings("unchecked") @Before// ww w . j a v a2s. c o m public void setUp() throws Exception { Endpoint endpoint = createEndpoint("127.0.0.1", 0); // create the client manager MVCCStoreFactory storeFactory = mock(MVCCStoreFactory.class); MVCCAsyncStore<byte[], byte[]> store = mock(MVCCAsyncStore.class); when(storeFactory.openStore(anyLong(), anyLong(), anyLong())).thenReturn(FutureUtils.value(store)); when(storeFactory.closeStores(anyLong())).thenReturn(FutureUtils.Void()); RangeStoreServiceFactory rangeStoreServiceFactory = mock(RangeStoreServiceFactory.class); mockRangeStoreService = mock(RangeStoreService.class); when(mockRangeStoreService.start()).thenReturn(FutureUtils.Void()); when(mockRangeStoreService.stop()).thenReturn(FutureUtils.Void()); when(rangeStoreServiceFactory.createService(anyLong())).thenReturn(mockRangeStoreService); rangeStore = new StorageContainerStoreImpl(storageConf, (storeConf, rgRegistry) -> new LocalStorageContainerManager(endpoint, storeConf, rgRegistry, 2), new RangeStoreContainerServiceFactoryImpl(rangeStoreServiceFactory), null, NullStatsLogger.INSTANCE); rangeStore.start(); final String serverName = "test-server"; Collection<ServerServiceDefinition> grpcServices = GrpcServices.create(null); ProxyHandlerRegistry.Builder registryBuilder = ProxyHandlerRegistry.newBuilder(); grpcServices.forEach(service -> registryBuilder.addService(service)); ProxyHandlerRegistry registry = registryBuilder.setChannelFinder(rangeStore).build(); server = InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(registry).directExecutor() .build().start(); channel = InProcessChannelBuilder.forName(serverName).usePlaintext().build(); scId = ThreadLocalRandom.current().nextInt(2); // intercept the channel with storage container information. channel = ClientInterceptors.intercept(channel, new StorageContainerClientInterceptor(scId)); tableService = TableServiceGrpc.newFutureStub(channel); metaRangeService = MetaRangeServiceGrpc.newFutureStub(channel); rootRangeService = RootRangeServiceGrpc.newFutureStub(channel); }
From source file:com.spotify.helios.system.SystemTestBase.java
@Before public void dockerSetup() throws Exception { final String portRange = System.getenv("DOCKER_PORT_RANGE"); final AllocatedPort allocatedPort; final int probePort; if (portRange != null) { final String[] parts = portRange.split(":", 2); dockerPortRange = Range.closedOpen(Integer.valueOf(parts[0]), Integer.valueOf(parts[1])); allocatedPort = Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable<AllocatedPort>() { @Override//w w w . j a v a 2s.c o m public AllocatedPort call() throws Exception { final int port = ThreadLocalRandom.current().nextInt(dockerPortRange.lowerEndpoint(), dockerPortRange.upperEndpoint()); return temporaryPorts.tryAcquire("docker-probe", port); } }); probePort = allocatedPort.port(); } else { dockerPortRange = temporaryPorts.localPortRange("docker", 10); probePort = dockerPortRange().lowerEndpoint(); allocatedPort = null; } try { assertDockerReachable(probePort); } finally { if (allocatedPort != null) { allocatedPort.release(); } } }
From source file:com.itdhq.contentLoader.ContentLoaderComponent.java
/** * Creates document. Most likely this function would be changed. * * @param parent - parent node//from w w w . ja v a2 s . c o m * @param cmname - new node name * @return NodeRef of new document */ public NodeRef createDocument(NodeRef parent, String cmname, RepoObject object) { logger.debug("createDocument"); NodeRef res = this.getChildNodeRefByName(parent, cmname); if (res != null) { logger.debug("exist"); return res; } res = fileFolderService.create(parent, cmname, object.getType()).getNodeRef(); fillNodeProperties(res); // TODO here will be many types if (object.hasContent()) { ContentWriter writer = this.contentService.getWriter(res, ContentModel.PROP_CONTENT, true); writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); writer.setEncoding("UTF-8"); writer.putContent(genPlainText( ThreadLocalRandom.current().nextInt(object.getMinSize(), object.getMaxSize() + 1))); } // TODO null check //logger.debug("created: " + nodeService.getProperty(res, ContentModel.PROP_NAME)); return res; }