Java Code Examples for java.util.concurrent.atomic.AtomicBoolean#get()

The following examples show how to use java.util.concurrent.atomic.AtomicBoolean#get() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: consulo   File: ControlledCycle.java    License: Apache License 2.0 6 votes vote down vote up
public ControlledCycle(final Project project, final Getter<Boolean> callback, @Nonnull final String name, final int refreshInterval) {
  myRefreshInterval = (refreshInterval <= 0) ? ourRefreshInterval : refreshInterval;
  myActive = new AtomicBoolean(false);
  myRunnable = new Runnable() {
    boolean shouldBeContinued = true;
    @Override
    public void run() {
      if (! myActive.get() || project.isDisposed()) return;
      try {
        shouldBeContinued = callback.get();
      } catch (ProcessCanceledException e) {
        return;
      } catch (RuntimeException e) {
        LOG.info(e);
      }
      if (! shouldBeContinued) {
        myActive.set(false);
      } else {
        mySimpleAlarm.addRequest(myRunnable, myRefreshInterval);
      }
    }
  };
  mySimpleAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, project);
}
 
Example 2
@Override
public boolean computeIfPinned(final K key, final BiFunction<K,V,V> remappingFunction, final Function<V,Boolean> unpinFunction) {
  final AtomicBoolean unpin = new AtomicBoolean();
  computeIfPresentWithMetadata(key, (k, current) -> {
    if ((current.metadata() & Metadata.PINNED) != 0) {
      V oldValue = current.value();
      V newValue = remappingFunction.apply(k, oldValue);
      Boolean unpinLocal = unpinFunction.apply(oldValue);

      if (newValue == null) {
        unpin.set(true);
        return null;
      } else if (oldValue == newValue) {
        unpin.set(unpinLocal);
        return metadataTuple(oldValue, current.metadata() & (unpinLocal ? ~Metadata.PINNED : -1));
      } else {
        unpin.set(false);
        return metadataTuple(newValue, (evictionAdvisor.adviseAgainstEviction(k, newValue) ? ADVISED_AGAINST_EVICTION : 0));
      }
    } else {
      return current;
    }
  });
  return unpin.get();
}
 
Example 3
void updateTaskStatus(TaskStatus newValue)
{
    // change to new value if old value is not changed and new value has a newer version
    AtomicBoolean taskMismatch = new AtomicBoolean();
    taskStatus.setIf(newValue, oldValue -> {
        // did the task instance id change
        if (!isNullOrEmpty(oldValue.getTaskInstanceId()) && !oldValue.getTaskInstanceId().equals(newValue.getTaskInstanceId())) {
            taskMismatch.set(true);
            return false;
        }

        if (oldValue.getState().isDone()) {
            // never update if the task has reached a terminal state
            return false;
        }
        if (newValue.getVersion() < oldValue.getVersion()) {
            // don't update to an older version (same version is ok)
            return false;
        }
        return true;
    });

    if (taskMismatch.get()) {
        // This will also set the task status to FAILED state directly.
        // Additionally, this will issue a DELETE for the task to the worker.
        // While sending the DELETE is not required, it is preferred because a task was created by the previous request.
        onFail.accept(new PrestoException(REMOTE_TASK_MISMATCH, format("%s (%s)", REMOTE_TASK_MISMATCH_ERROR, HostAddress.fromUri(getTaskStatus().getSelf()))));
    }
}
 
Example 4
Source Project: java-dcp-client   File: SessionState.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if the current sequence numbers for all partitions are >= the ones set as end.
 *
 * @return true if all are at the end, false otherwise.
 */
public boolean isAtEnd() {
  final AtomicBoolean atEnd = new AtomicBoolean(true);
  foreachPartition(ps -> {
    if (!ps.isAtEnd()) {
      atEnd.set(false);
    }
  });
  return atEnd.get();
}
 
Example 5
Source Project: flow   File: StateNode.java    License: Apache License 2.0 5 votes vote down vote up
private boolean hasChildAssert(StateNode child) {
    AtomicBoolean found = new AtomicBoolean(false);
    forEachChild(c -> {
        if (c == child) {
            found.set(true);
        }
    });
    return found.get();
}
 
Example 6
Source Project: netbeans   File: TaskProvider.java    License: Apache License 2.0 5 votes vote down vote up
private static synchronized void updateErrorsInRoot(
        final Callback callback,
        final FileObject root,
        final AtomicBoolean cancelled) {
    Set<FileObject> filesWithErrors = getFilesWithAttachedErrors(root);
    Set<FileObject> fixedFiles = new HashSet<FileObject>(filesWithErrors);
    Set<FileObject> nueFilesWithErrors = new HashSet<FileObject>();

    try {
        for (URL u : TaskCache.getDefault().getAllFilesWithRecord(root.toURL())) {
            if (cancelled.get()) {
                return;
            }
            FileObject file = URLMapper.findFileObject(u);

            if (file != null) {
                List<Task> result = TaskCache.getDefault().getErrors(file);

                LOG.log(Level.FINE, "Setting {1} for {0}\n", new Object[] {file, result});

                callback.setTasks(file, result);

                if (!fixedFiles.remove(file)) {
                    nueFilesWithErrors.add(file);
                }
            }
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
    
    for (FileObject f : fixedFiles) {
        LOG.log(Level.FINE, "Clearing errors for {0}", f);
        callback.setTasks(f, Collections.<Task>emptyList());
    }
    
    filesWithErrors.addAll(nueFilesWithErrors);
}
 
Example 7
Source Project: elasticsearch   File: Resources.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isPortAvailable(List<Protos.Resource> resourcesList, Integer port) {
    final AtomicBoolean available = new AtomicBoolean(false);
    resourcesList.stream().filter(resource -> resource.getType().equals(org.apache.mesos.Protos.Value.Type.RANGES))
            .forEach(resource -> resource.getRanges().getRangeList().stream().forEach(range -> {
                if (range.getBegin() <= port && port <= range.getEnd()) {
                    available.set(true);
                }
            }));
    return available.get();
}
 
Example 8
Source Project: jdk8u-jdk   File: Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean waitForConditionEx(final AtomicBoolean condition, long timeout)
throws InterruptedException
  {
      synchronized (condition) {
          long startTime = System.currentTimeMillis();
          while (!condition.get()) {
              condition.wait(timeout);
              if (System.currentTimeMillis() - startTime >= timeout ) {
                  break;
              }
          }
      }
      return condition.get();
  }
 
Example 9
Source Project: tddl   File: SoftRefLogWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void perfTest(final int concurrent, final int seconds) throws InterruptedException {
    final Random rand = new Random();
    final AtomicBoolean exit = new AtomicBoolean(false);
    final AtomicLong counter = new AtomicLong();
    final AtomicLong latency = new AtomicLong();
    Thread[] threads = new Thread[concurrent];
    for (int j = 0; j < concurrent; j++) {
        threads[j] = new Thread() {

            @Override
            public void run() {
                while (!exit.get()) {
                    String db = "db_" + rand.nextInt(512);
                    String key = "key_" + (rand.nextInt(64));
                    String status = "status_" + (rand.nextInt(8));
                    final long delay = 1000 + Math.abs(rand.nextLong()) % 2000;
                    final long nanos = System.nanoTime();
                    logger.stat(db, key, status, delay);
                    latency.addAndGet(System.nanoTime() - nanos);
                    counter.incrementAndGet();
                    LockSupport.parkNanos(1000);
                }
            }
        };
        threads[j].start();
    }

    Thread.sleep(seconds * 1000);
    System.out.println("concurrent: " + concurrent + ", seconds: " + seconds + ", number: " + counter.get()
                       + ", RT: " + (latency.get() / counter.get()) + ", TPS: "
                       + ((long) (counter.get() * 100 / seconds)) / 100);

    exit.set(true);
    for (Thread thread : threads) {
        thread.join();
    }
}
 
Example 10
Source Project: tinkerpop   File: ResultSetTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHaveAllItemsAvailableOnReadCompleteWhileLoading() throws Exception {
    assertThat(resultSet.allItemsAvailable(), is(false));

    final AtomicBoolean atLeastOnce = new AtomicBoolean(false);
    addToQueue(1000, 1, true, true);
    while (!readCompleted.isDone()) {
        atLeastOnce.set(true);
        if (!atLeastOnce.get())
            assertThat(resultSet.allItemsAvailable(), is(false));
    }

    assertThat(atLeastOnce.get(), is(true));
    assertThat(resultSet.allItemsAvailable(), is(true));
}
 
Example 11
Source Project: jdk8u_jdk   File: Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean waitForConditionEx(final AtomicBoolean condition, long timeout)
throws InterruptedException
  {
      synchronized (condition) {
          long startTime = System.currentTimeMillis();
          while (!condition.get()) {
              condition.wait(timeout);
              if (System.currentTimeMillis() - startTime >= timeout ) {
                  break;
              }
          }
      }
      return condition.get();
  }
 
Example 12
Source Project: j2objc   File: AbstractCollectionTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_toArray() throws Exception {
  final ConcurrentHashMap<Integer, Integer> m = new ConcurrentHashMap<Integer, Integer>();
  final AtomicBoolean finished = new AtomicBoolean(false);

  Thread reader = new Thread(new Runnable() {
    @Override public void run() {
      while (!finished.get()) {
        m.values().toArray();
        m.values().toArray(new Integer[m.size()]);
      }
    }
  });

  Thread mutator = new Thread(new Runnable() {
    @Override public void run() {
      for (int i = 0; i < 100; ++i) {
        m.put(-i, -i);
      }
      for (int i = 0; i < 4096; ++i) {
        m.put(i, i);
        m.remove(i);
      }
      finished.set(true);
    }
  });

  reader.start();
  mutator.start();
  reader.join();
  mutator.join();
}
 
Example 13
private boolean triggerExists(TestContext context, String name) {
  AtomicBoolean exists = new AtomicBoolean();
  Async async = context.async();
  PostgresClient postgresClient = PostgresClient.getInstance(vertx, tenant);
  postgresClient.selectSingle(
      "SELECT count(*) FROM pg_trigger " +
      "WHERE tgrelid = '" + schema + ".test_tenantapi'::regclass AND tgname='" + name + "'",
      context.asyncAssertSuccess(count -> {
        exists.set(count.getInteger(0) == 1);
        async.complete();
  }));
  async.await(5000);
  return exists.get();
}
 
Example 14
Source Project: jfilter   File: MockUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean beanFilterConverterLoaded(List<Object> registeredConverters) {
    final AtomicBoolean result = new AtomicBoolean(false);
    registeredConverters.forEach(i -> {
        if (i instanceof FilterConverter) {
            result.set(true);
        } else if (i instanceof MappingJackson2HttpMessageConverter &&
                ((MappingJackson2HttpMessageConverter) i).getObjectMapper() instanceof FilterObjectMapper) {
            result.set(true);
        } else if (i instanceof MappingJackson2XmlHttpMessageConverter &&
                ((MappingJackson2XmlHttpMessageConverter) i).getObjectMapper() instanceof FilterXmlMapper) {
            result.set(true);
        }
    });
    return result.get();
}
 
Example 15
@Override
public boolean testImpl(Creature effector, Creature effected, Skill skill, ItemTemplate item) {
    final AtomicBoolean canSweep = new AtomicBoolean(false);
    if (effector.getActingPlayer() != null) {
        final Player sweeper = effector.getActingPlayer();
        if (skill != null) {
            skill.forEachTargetAffected(sweeper, effected, o ->
            {
                if (isAttackable(o)) {
                    final Attackable target = (Attackable) o;
                    if (target.isDead()) {
                        if (target.isSpoiled()) {
                            canSweep.set(target.checkSpoilOwner(sweeper, true));
                            if (canSweep.get()) {
                                canSweep.set(!target.isOldCorpse(sweeper, Config.CORPSE_CONSUME_SKILL_ALLOWED_TIME_BEFORE_DECAY, true));
                            }
                            if (canSweep.get()) {
                                canSweep.set(sweeper.getInventory().checkInventorySlotsAndWeight(target.getSpoilLootItems(), true, true));
                            }
                        } else {
                            sweeper.sendPacket(SystemMessageId.SWEEPER_FAILED_TARGET_NOT_SPOILED);
                        }
                    }
                }
            });
        }
    }
    return (_val == canSweep.get());
}
 
Example 16
private static void throwExceptionIfInterruptedOrCancelled(AtomicBoolean isCanceled)
    throws InterruptedException {
  if (Thread.interrupted() || (isCanceled != null && isCanceled.get())) {
    throw new InterruptedException();
  }
}
 
Example 17
Source Project: java-client-api   File: WBFailover.java    License: Apache License 2.0 4 votes vote down vote up
@Test(timeout = 350000)
public void testStopTwoNodes() throws Exception {
	Assume.assumeTrue(hostNames.length > 1);

	System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
	try {
		final AtomicInteger successCount = new AtomicInteger(0);
		final AtomicBoolean failState = new AtomicBoolean(false);
		final AtomicInteger failCount = new AtomicInteger(0);

		WriteBatcher ihb2 = dmManager.newWriteBatcher();
		ihb2.withBatchSize(25);
		ihb2.withThreadCount(2);

		HostAvailabilityListener.getInstance(ihb2).withSuspendTimeForHostUnavailable(Duration.ofSeconds(15))
				.withMinHosts(1);
		NoResponseListener.getInstance(ihb2).withSuspendTimeForHostUnavailable(Duration.ofSeconds(15))
				.withMinHosts(1);

		ihb2.onBatchSuccess(batch -> {
			successCount.addAndGet(batch.getItems().length);
		}).onBatchFailure((batch, throwable) -> {
			throwable.printStackTrace();
			failState.set(true);
			failCount.addAndGet(batch.getItems().length);
			if (throwable.getMessage().contains("XDMP-XDQPNOSESSION")) {
				ihb2.retry(batch);
			}
		});

		writeTicket = dmManager.startJob(ihb2);
		AtomicBoolean isNode1Running = new AtomicBoolean(true);
		AtomicBoolean isNode2Running = new AtomicBoolean(true);
		for (int j = 0; j < 40000; j++) {
			String uri = "/local/ABC-" + j;
			ihb2.add(uri, stringHandle);
			if (dmManager.getJobReport(writeTicket).getSuccessEventsCount() > 50 && isNode1Running.get()) {
				isNode1Running.set(false);
				serverStartStop(hostNames[hostNames.length - 1], "stop");
			}

			if (dmManager.getJobReport(writeTicket).getSuccessEventsCount() > 350 && isNode2Running.get()) {
				isNode2Running.set(false);
				serverStartStop(hostNames[hostNames.length - 2], "stop");
				Thread.currentThread().sleep(5000L);
				serverStartStop(hostNames[hostNames.length - 1], "start");
			}
		}

		ihb2.flushAndWait();
		Thread.sleep(2000L);
		Assert.assertTrue(isRunning(hostNames[hostNames.length - 3]));
		Assert.assertTrue(isRunning(hostNames[hostNames.length - 1]));
		System.out.println("Fail : " + failCount.intValue());
		System.out.println("Success : " + successCount.intValue());
		System.out.println(
				"Count : " + evalClient.newServerEval().xquery(query1).eval().next().getNumber().intValue());

		Assert.assertTrue(evalClient.newServerEval().xquery(query1).eval().next().getNumber().intValue() == 40000);

	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 18
@Override
public void analyze( TypeElement element, WebBeansModel model,
        AtomicBoolean cancel ,
        Result result )
{
    if ( !AnnotationUtil.hasAnnotation(element, 
            AnnotationUtil.INTERCEPTOR_BINDING_FQN , model.getCompilationController()))
    {
        return;
    }
    result.requireCdiEnabled(element, model);
    InterceptorTargetAnalyzer analyzer = new InterceptorTargetAnalyzer(
            element, model, result );
    if ( cancel.get() ){
        return;
    }
    if (!analyzer.hasRuntimeRetention()) {
        result.addError(element, model,   
                        NbBundle.getMessage(InterceptorBindingAnalyzer.class,
                                INCORRECT_RUNTIME));
    }
    if ( cancel.get() ){
        return;
    }
    if (!analyzer.hasTarget()) {
        result.addError(element, model,   
                        NbBundle.getMessage(InterceptorBindingAnalyzer.class,
                        "ERR_IncorrectInterceptorBindingTarget")); // NOI18N
    }
    else {
        if ( cancel.get() ){
            return;
        }
        Set<ElementType> declaredTargetTypes = analyzer.getDeclaredTargetTypes();
        if ( cancel.get() ){
            return;
        }
        checkTransitiveInterceptorBindings( element, declaredTargetTypes, 
                model , result );
    }
}
 
Example 19
Source Project: java-client-api   File: QBFailover.java    License: Apache License 2.0 4 votes vote down vote up
@Test(timeout = 450000)
public void testStopTwoNodes() throws Exception {
	Assume.assumeTrue(hostNames.length > 1);

	System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
	try {
		final AtomicInteger success = new AtomicInteger(0);

		AtomicBoolean isNode3Running = new AtomicBoolean(true);
		AtomicBoolean isNode2Running = new AtomicBoolean(true);
		QueryBatcher batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("XmlTransform"))
				.withBatchSize(5).withThreadCount(6);

		HostAvailabilityListener.getInstance(batcher).withSuspendTimeForHostUnavailable(Duration.ofSeconds(15))
				.withMinHosts(1);
		NoResponseListener.getInstance(batcher).withSuspendTimeForHostUnavailable(Duration.ofSeconds(15))
				.withMinHosts(1);

		batcher.onUrisReady((batch) -> {
			success.addAndGet(batch.getItems().length);
		}).onQueryFailure(queryException -> {
			queryException.printStackTrace();
		});
		ticket = dmManager.startJob(batcher);
		while (!batcher.isStopped()) {
			if (isNode3Running.get() && dmManager.getJobReport(ticket).getSuccessEventsCount() > 0) {
				isNode3Running.set(false);
				serverStartStop(hostNames[hostNames.length - 1], "stop");
			}
			if (isNode2Running.get() && dmManager.getJobReport(ticket).getSuccessEventsCount() > 50) {
				isNode2Running.set(false);
				serverStartStop(hostNames[hostNames.length - 2], "stop");
				Thread.currentThread().sleep(5000L);
				serverStartStop(hostNames[hostNames.length - 1], "start");
			}
		}
		batcher.awaitCompletion();
		dmManager.stopJob(ticket);
		Thread.sleep(2000L);
		Assert.assertTrue(isRunning(hostNames[hostNames.length - 3]));
		Assert.assertTrue(isRunning(hostNames[hostNames.length - 1]));
		System.out.println("Success " + success.intValue());
		assertEquals("document count", 20000, success.intValue());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 20
Source Project: ehcache3   File: AbstractOffHeapStore.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ReplaceStatus replace(final K key, final V oldValue, final V newValue) throws NullPointerException, IllegalArgumentException, StoreAccessException {
  checkKey(key);
  checkValue(oldValue);
  checkValue(newValue);

  conditionalReplaceObserver.begin();

  final AtomicBoolean replaced = new AtomicBoolean(false);
  final StoreEventSink<K, V> eventSink = eventDispatcher.eventSink();
  final AtomicBoolean mappingExists = new AtomicBoolean();

  BiFunction<K, OffHeapValueHolder<V>, OffHeapValueHolder<V>> mappingFunction = (mappedKey, mappedValue) -> {
    long now = timeSource.getTimeMillis();

    if (mappedValue == null || mappedValue.isExpired(now)) {
      if (mappedValue != null) {
        onExpiration(mappedKey, mappedValue, eventSink);
      }
      return null;
    } else if (oldValue.equals(mappedValue.get())) {
      replaced.set(true);
      return newUpdatedValueHolder(mappedKey, newValue, mappedValue, now, eventSink);
    } else {
      mappingExists.set(true);
      return setAccessTimeAndExpiryThenReturnMapping(mappedKey, mappedValue, now, eventSink);
    }
  };

  try {
    computeWithRetry(key, mappingFunction, false);
    eventDispatcher.releaseEventSink(eventSink);
    if (replaced.get()) {
      conditionalReplaceObserver.end(StoreOperationOutcomes.ConditionalReplaceOutcome.REPLACED);
      return ReplaceStatus.HIT;
    } else {
      conditionalReplaceObserver.end(StoreOperationOutcomes.ConditionalReplaceOutcome.MISS);
      if (mappingExists.get()) {
        return ReplaceStatus.MISS_PRESENT;
      } else {
        return ReplaceStatus.MISS_NOT_PRESENT;
      }
    }
  } catch (StoreAccessException | RuntimeException caex) {
    eventDispatcher.releaseEventSinkAfterFailure(eventSink, caex);
    throw caex;
  }
}