List of usage examples for java.util.concurrent.atomic AtomicInteger AtomicInteger
public AtomicInteger()
From source file:de.bund.bfr.math.MultivariateOptimization.java
@Override public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful, Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations, DoubleConsumer progessListener, ExecutionContext exec) throws CanceledExecutionException { if (exec != null) { exec.checkCanceled();//from w ww. j a va2 s. c om } progessListener.accept(0.0); List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues, nParameterSpace); ranges.set(parameters.indexOf(sdParam), new ParamRange(1.0, 1, 1.0)); List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations, values -> optimizerFunction.value(Doubles.toArray(values)), progress -> progessListener.accept(0.5 * progress), exec); Result result = new Result(); AtomicInteger currentIteration = new AtomicInteger(); SimplexOptimizer optimizer = new SimplexOptimizer(new SimpleValueChecker(1e-10, 1e-10) { @Override public boolean converged(int iteration, PointValuePair previous, PointValuePair current) { if (super.converged(iteration, previous, current)) { return true; } return currentIteration.incrementAndGet() >= maxIterations; } }); int count = 0; for (StartValues startValues : startValuesList) { if (exec != null) { exec.checkCanceled(); } progessListener.accept(0.5 * count++ / startValuesList.size() + 0.5); try { PointValuePair optimizerResults = optimizer.optimize(new MaxEval(Integer.MAX_VALUE), new MaxIter(maxIterations), new InitialGuess(Doubles.toArray(startValues.getValues())), new ObjectiveFunction(optimizerFunction), GoalType.MAXIMIZE, new NelderMeadSimplex(parameters.size())); double logLikelihood = optimizerResults.getValue() != null ? optimizerResults.getValue() : Double.NaN; if (result.logLikelihood == null || logLikelihood > result.logLikelihood) { result = getResults(optimizerResults); if (result.logLikelihood == 0.0 || stopWhenSuccessful) { break; } } } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) { } } return result; }
From source file:org.eclipse.hono.service.credentials.impl.FileBasedCredentialsService.java
protected void loadCredentialsData() { if (filename != null) { final FileSystem fs = vertx.fileSystem(); log.debug("trying to load credentials information from file {}", filename); if (fs.existsBlocking(filename)) { final AtomicInteger credentialsCount = new AtomicInteger(); fs.readFile(filename, readAttempt -> { if (readAttempt.succeeded()) { JsonArray allObjects = new JsonArray(new String(readAttempt.result().getBytes())); for (Object obj : allObjects) { JsonObject tenant = (JsonObject) obj; String tenantId = tenant.getString(FIELD_TENANT); Map<String, JsonArray> credentialsMap = new HashMap<>(); for (Object credentialsObj : tenant.getJsonArray(ARRAY_CREDENTIALS)) { JsonObject credentials = (JsonObject) credentialsObj; JsonArray authIdCredentials; if (credentialsMap.containsKey(credentials.getString(FIELD_AUTH_ID))) { authIdCredentials = credentialsMap.get(credentials.getString(FIELD_AUTH_ID)); } else { authIdCredentials = new JsonArray(); }// w w w . j a v a 2 s . c om authIdCredentials.add(credentials); credentialsMap.put(credentials.getString(FIELD_AUTH_ID), authIdCredentials); credentialsCount.incrementAndGet(); } credentials.put(tenantId, credentialsMap); } log.info("successfully loaded {} credentials from file [{}]", credentialsCount.get(), filename); } else { log.warn("could not load credentials from file [{}]", filename, readAttempt.cause()); } }); } else { log.debug("credentials file {} does not exist (yet)", filename); } } }
From source file:com.cloudant.http.interceptors.Replay429Interceptor.java
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { // Get or init the stored context for this interceptor try {/*from w w w . ja v a2 s .c o m*/ HttpURLConnection urlConnection = context.connection.getConnection(); int code = urlConnection.getResponseCode(); // We only want to take action on a 429 response if (code != 429) { return context; } // We received a 429 // Get the counter from the request context state AtomicInteger attemptCounter = context.getState(this, ATTEMPT, AtomicInteger.class); // If there was no counter yet, then this is the first 429 received for this request if (attemptCounter == null) { context.setState(this, ATTEMPT, (attemptCounter = new AtomicInteger())); } // Get the current value, and then increment for the next time round int attempt = attemptCounter.getAndIncrement(); // Check if we have remaining replays if (attempt < numberOfReplays && context.connection.getNumberOfRetriesRemaining() > 0) { // Calculate the backoff time, 2^n * initial sleep long sleepTime = initialSleep * Math.round(Math.pow(2, attempt)); // If the response includes a Retry-After then that is when we will retry, otherwise // we use the doubling sleep String retryAfter = preferRetryAfter ? urlConnection.getHeaderField("Retry-After") : null; if (retryAfter != null) { // See https://tools.ietf.org/html/rfc6585#section-4 // Whilst not specified for 429 for 3xx or 503 responses the Retry-After header // is expressed as an integer number of seconds or a date in one of the 3 HTTP // date formats https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 // Cloudant servers should give us an integer number of seconds, so don't worry // about parsing dates for now. try { sleepTime = Long.parseLong(retryAfter) * 1000; if (sleepTime > RETRY_AFTER_CAP) { sleepTime = RETRY_AFTER_CAP; logger.severe("Server specified Retry-After value in excess of one " + "hour, capping retry."); } } catch (NumberFormatException nfe) { logger.warning( "Invalid Retry-After value from server falling back to " + "default backoff."); } } // Read the reasons and log a warning InputStream errorStream = urlConnection.getErrorStream(); try { String errorString = IOUtils.toString(errorStream, "UTF-8"); logger.warning(errorString + " will retry in " + sleepTime + " ms"); } finally { errorStream.close(); } logger.fine("Too many requests backing off for " + sleepTime + " ms."); // Sleep the thread for the appropriate backoff time try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException e) { logger.fine("Interrupted during 429 backoff wait."); // If the thread was interrupted we'll just continue and try again a bit earlier // than planned. } // Get ready to replay the request after the backoff time context.replayRequest = true; return context; } else { return context; } } catch (IOException e) { throw new HttpConnectionInterceptorException(e); } }
From source file:com.netflix.curator.framework.recipes.atomic.TestDistributedAtomicLong.java
@Test public void testSimulation() throws Exception { final int threadQty = 20; final int executionQty = 50; final AtomicInteger optimisticTries = new AtomicInteger(); final AtomicInteger promotedLockTries = new AtomicInteger(); final AtomicInteger failures = new AtomicInteger(); final AtomicInteger errors = new AtomicInteger(); final SummaryStatistics timingStats = new SynchronizedSummaryStatistics(); List<Future<Void>> procs = Lists.newArrayList(); ExecutorService executorService = Executors.newFixedThreadPool(threadQty); for (int i = 0; i < threadQty; ++i) { Callable<Void> proc = new Callable<Void>() { @Override/* ww w .ja va2s. co m*/ public Void call() throws Exception { doSimulation(executionQty, timingStats, optimisticTries, promotedLockTries, failures, errors); return null; } }; procs.add(executorService.submit(proc)); } for (Future<Void> f : procs) { f.get(); } System.out.println("OptimisticTries: " + optimisticTries.get()); System.out.println("PromotedLockTries: " + promotedLockTries.get()); System.out.println("Failures: " + failures.get()); System.out.println("Errors: " + errors.get()); System.out.println(); System.out.println("Avg time: " + timingStats.getMean()); System.out.println("Max time: " + timingStats.getMax()); System.out.println("Min time: " + timingStats.getMin()); System.out.println("Qty: " + timingStats.getN()); Assert.assertEquals(errors.get(), 0); Assert.assertTrue(optimisticTries.get() > 0); Assert.assertTrue(promotedLockTries.get() > 0); }
From source file:com.intuit.karate.http.apache.ApacheHttpClient.java
@Override public void configure(HttpConfig config) { clientBuilder = HttpClientBuilder.create(); cookieStore = new BasicCookieStore(); clientBuilder.setDefaultCookieStore(cookieStore); AtomicInteger counter = new AtomicInteger(); clientBuilder.addInterceptorLast(new RequestLoggingInterceptor(counter)); clientBuilder.addInterceptorLast(new ResponseLoggingInterceptor(counter)); if (config.isSslEnabled()) { // System.setProperty("jsse.enableSNIExtension", "false"); String sslAlgorithm = config.getSslAlgorithm(); logger.info("ssl enabled, initializing generic trusted certificate / key-store with algorithm: {}", sslAlgorithm);//www . j a v a2s. co m SSLContext sslContext = HttpUtils.getSslContext(sslAlgorithm); SSLConnectionSocketFactory socketFactory = new LenientSslConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); clientBuilder.setSSLSocketFactory(socketFactory); } RequestConfig.Builder configBuilder = RequestConfig.custom().setConnectTimeout(config.getConnectTimeout()) .setSocketTimeout(config.getReadTimeout()); clientBuilder.setDefaultRequestConfig(configBuilder.build()); if (config.getProxyUri() != null) { try { URI proxyUri = new URIBuilder(config.getProxyUri()).build(); clientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme())); if (config.getProxyUsername() != null && config.getProxyPassword() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); clientBuilder.setDefaultCredentialsProvider(credsProvider); } } catch (Exception e) { throw new RuntimeException(e); } } }
From source file:org.excalibur.aqmp.handler.InstanceConfigurationHandler.java
public void handleInstanceConfigurationTasks(RemoteTasks tasks) { NodeManagerFactory.getManagerReference(); final ListeningExecutorService executionHandlerService = newListeningDynamicScalingThreadPool( "instances-remote-task-result-handler", tasks.size()); VirtualMachine remoteHost = instanceService_ .getInstanceByPublicIp(tasks.first().getHostAndPort().getHost()); if (remoteHost == null) { LOG.debug("Remote host was null. Ignoring [{}] task(s)", tasks.size()); return;/*from w ww .ja va 2 s . c o m*/ } UserProviderCredentials credentials = null; LoginCredentials loginCredentials = null; File sshKey = null; final AtomicInteger count = new AtomicInteger(); for (final RemoteTask task : tasks) { try { LOG.debug("Configuring the execution of task [{}] on host [{}] with username [{}]", task.getApplication().getName(), task.getHostAndPort().getHost(), task.getUsername()); ProviderSupport provider = (ProviderSupport) this.providerRepository_ .findByExactlyProviderName(task.getHostAndPort().getProvider()); Zone zone = this.regionRepository_.findZoneByName(task.getZone().getName()); if (remoteHost == null) { LOG.debug("Reference for host [{}] was null!", task.getHostAndPort().getHost()); VmConfiguration configuration = new VmConfiguration() .setKeyName(task.getKeyPairs().getPrivateKey().getKeyName()) .setKeyPairs(new KeyPairs().setPrivateKey(task.getKeyPairs().getPrivateKey())) .setPlatformUserName(task.getUsername()) .setPublicIpAddress(task.getHostAndPort().getHost()) .setPublicDnsName(task.getHostAndPort().getHost()); remoteHost = new VirtualMachine().setConfiguration(configuration) .setType(new InstanceType().setProvider(provider)); } if (credentials == null) { credentials = this.userService_.findUserProviderCredentials(task.getOwner(), provider); credentials .setLoginCredentials(credentials.getLoginCredentials().toBuilder() .credentialName(task.getKeyPairs().getName()).authenticateAsSudo(true).build()) .setRegion(zone.getRegion()); remoteHost.getConfiguration().setCredentials(credentials); sshKey = File.createTempFile(String.format("%s_key_", task.getUsername()), ".key"); Files.write(decrypt(task.getKeyPairs().getPrivateKey().getKeyMaterial()).getBytes(), sshKey); loginCredentials = new LoginCredentials.Builder().authenticateAsSudo(true).privateKey(sshKey) .user(task.getUsername()).build(); } try (RemoteScriptStatementExecutor executor = new RemoteScriptStatementExecutor(remoteHost, loginCredentials, executionHandlerService)) { executor.execute(task.getApplication(), new RemoteTaskExecutionHandler(task, count)); } LOG.debug("Task [{}] executed on host [{}]", task.getApplication().getName(), task.getHostAndPort().getHost()); } catch (Exception exception) { LOG.error( "Error on executing the task: [{}] on host/username [{}/{}]. Error message: [{}]. Cause: [{}]", task.getApplication().getName(), task.getHostAndPort().getHost(), task.getUsername(), exception.getMessage(), exception.getCause() != null ? exception.getCause().getMessage() : "", exception); AnyThrow.throwUncheked(exception); } } awaitTerminationAndShutdownAndIgnoreInterruption(executionHandlerService, 1, TimeUnit.MINUTES); LOG.debug("[{}] of [{}] tasks finished successfully on node [{}]", count.get(), tasks.size(), remoteHost.getConfiguration().getPublicDnsName()); boolean isExcaliburRunning = startExcaliburApplication(remoteHost, tasks.first(), loginCredentials); if (isExcaliburRunning) { LOG.debug("Registering the new instance [{}/{}] on application manager", remoteHost.getName(), remoteHost.getConfiguration().getPublicIpAddress()); NodeManagerFactory.getManagerReference().addIdleInstance(remoteHost); LOG.debug("Instance [{}] registered on application manager [{}]", remoteHost.getName(), NodeManagerFactory.getManagerReference().getThisNodeReference().getName()); } }
From source file:com.netflix.spring.sample.membership.Membership.java
@Bean public MethodInvokingMessageSource integerMessageSource() { MethodInvokingMessageSource source = new MethodInvokingMessageSource(); source.setObject(new AtomicInteger()); source.setMethodName("getAndIncrement"); return source; }
From source file:com.adobe.acs.commons.httpcache.store.jcr.impl.visitor.mock.RootNodeMockFactory.java
private Node[] generateBucketNodeChain(Node rootNode, boolean isEmpty) throws RepositoryException { final Node[] bucketNodeChain = new Node[settings.bucketDepth]; Node currentParentNode = rootNode; for (int i = 0; i < settings.bucketDepth; i++) { final Node node = mockStandardNode("bucketnode" + (isEmpty ? "-empty" : "") + "-level-" + (i + 1)); bucketNodeChain[i] = node;/*from w w w . ja v a2 s .c om*/ when(node.getParent()).thenReturn(currentParentNode); when(node.getProperties()).thenReturn(new MockPropertyIterator(IteratorUtils.EMPTY_ITERATOR)); when(node.hasProperty(JCRHttpCacheStoreConstants.PN_ISCACHEENTRYNODE)).thenReturn(false); when(node.hasProperty(JCRHttpCacheStoreConstants.PN_ISBUCKETNODE)).thenReturn(true); currentParentNode = node; } for (int i = 0; i < settings.bucketDepth; i++) { if (i < settings.bucketDepth) { final Node node = bucketNodeChain[i]; final Node childNode = bucketNodeChain[i]; final AtomicInteger deleteCounter = new AtomicInteger(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { deleteCounter.getAndIncrement(); return null; } }).when(node).remove(); when(node.getParent().getNodes()).thenAnswer(new Answer<NodeIterator>() { @Override public NodeIterator answer(InvocationOnMock invocationOnMock) throws Throwable { if (deleteCounter.get() > 0) { return new MockNodeIterator(); } else { return new MockNodeIterator(new Node[] { childNode }); } } }); } } return bucketNodeChain; }
From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java
@Test public void testReplaceConfigurer() throws IOException { try {/* w w w . j a v a2 s . c o m*/ final AtomicInteger counter = new AtomicInteger(); HttpClientConfigurer custom = new HttpClientConfigurer() { @Override public void configure(DefaultHttpClient httpClient, SolrParams config) { super.configure(httpClient, config); counter.set(config.getInt("custom-param", -1)); } }; HttpClientUtil.setConfigurer(custom); ModifiableSolrParams params = new ModifiableSolrParams(); params.set("custom-param", 5); HttpClientUtil.createClient(params).close(); assertEquals(5, counter.get()); } finally { //restore default configurer HttpClientUtil.setConfigurer(new HttpClientConfigurer()); } }
From source file:dk.netarkivet.common.utils.arc.ARCUtils.java
/** * Create new ARCWriter, writing to arcfile newFile. * @param newFile the ARCfile, that the ARCWriter writes to. * @return new ARCWriter, writing to arcfile newFile. *//*w ww. j a va 2 s . c om*/ public static ARCWriter createARCWriter(File newFile) { ARCWriter aw; PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream(newFile)); aw = new ARCWriter(new AtomicInteger(), ps, //This name is used for the first (file metadata) record newFile, false, //Don't compress //Use current time ArchiveUtils.get14DigitDate(System.currentTimeMillis()), null //No particular file metadata to add ); } catch (IOException e) { if (ps != null) { ps.close(); } String message = "Could not create ARCWriter to file '" + newFile + "'.\n"; log.warn(message); throw new IOFailure(message, e); } return aw; }