java.util.concurrent.atomic.AtomicBoolean#get()源码实例Demo

下面列出了java.util.concurrent.atomic.AtomicBoolean#get() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: consulo   文件: ControlledCycle.java
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);
}
 
@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();
}
 
源代码3 项目: presto   文件: ContinuousTaskStatusFetcher.java
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()))));
    }
}
 
源代码4 项目: java-dcp-client   文件: SessionState.java
/**
 * 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();
}
 
源代码5 项目: flow   文件: StateNode.java
private boolean hasChildAssert(StateNode child) {
    AtomicBoolean found = new AtomicBoolean(false);
    forEachChild(c -> {
        if (c == child) {
            found.set(true);
        }
    });
    return found.get();
}
 
源代码6 项目: netbeans   文件: TaskProvider.java
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);
}
 
源代码7 项目: elasticsearch   文件: Resources.java
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();
}
 
源代码8 项目: jdk8u-jdk   文件: Util.java
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();
  }
 
源代码9 项目: tddl   文件: SoftRefLogWriterTest.java
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();
    }
}
 
源代码10 项目: tinkerpop   文件: ResultSetTest.java
@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));
}
 
源代码11 项目: jdk8u_jdk   文件: Util.java
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();
  }
 
源代码12 项目: j2objc   文件: AbstractCollectionTest.java
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();
}
 
源代码13 项目: raml-module-builder   文件: SchemaMakerIT.java
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();
}
 
源代码14 项目: jfilter   文件: MockUtils.java
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();
}
 
源代码15 项目: L2jOrg   文件: ConditionPlayerCanSweep.java
@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());
}
 
源代码16 项目: Telegram-FOSS   文件: CacheUtil.java
private static void throwExceptionIfInterruptedOrCancelled(AtomicBoolean isCanceled)
    throws InterruptedException {
  if (Thread.interrupted() || (isCanceled != null && isCanceled.get())) {
    throw new InterruptedException();
  }
}
 
源代码17 项目: java-client-api   文件: WBFailover.java
@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();
	}

}
 
源代码18 项目: netbeans   文件: InterceptorBindingAnalyzer.java
@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 );
    }
}
 
源代码19 项目: java-client-api   文件: QBFailover.java
@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();
	}
}
 
源代码20 项目: ehcache3   文件: AbstractOffHeapStore.java
@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;
  }
}