java.util.concurrent.atomic.AtomicBoolean Java Examples

The following examples show how to use java.util.concurrent.atomic.AtomicBoolean. 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 File: ChangesListenersTestCase.java    From StoreBox with Apache License 2.0 7 votes vote down vote up
@UiThreadTest
@SmallTest
public void testListenerGarbageCollected() throws Exception {
    final AtomicBoolean called = new AtomicBoolean();

    uut.registerIntChangeListener(new OnPreferenceValueChangedListener<Integer>() {
        @Override
        public void onChanged(Integer newValue) {
            called.set(true);
        }
    });
    // nasty, but it does force collection of soft references...
    // TODO is there a better way to do this?
    try {
        Object[] ignored = new Object[(int) Runtime.getRuntime().maxMemory()];
    } catch (OutOfMemoryError e) {
        // NOP
    }
    uut.setInt(1);

    assertFalse(called.get());
}
 
Example #2
Source File: HudsonConnector.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void getJobBuildResult(HudsonJobBuild build, AtomicBoolean building, AtomicReference<Result> result) {
    Document doc = getDocument(build.getUrl() + XML_API_URL +
            "?xpath=/*/*[name()='result'%20or%20name()='building']&wrapper=root", true);
    if (doc == null) {
        return;
    }
    Element docEl = doc.getDocumentElement();
    Element resultEl = XMLUtil.findElement(docEl, "result", null);
    if (resultEl != null) {
        result.set(Result.valueOf(XMLUtil.findText(resultEl)));
    }
    Element buildingEl = XMLUtil.findElement(docEl, "building", null);
    if (buildingEl != null) {
        building.set(Boolean.parseBoolean(XMLUtil.findText(buildingEl)));
    }
}
 
Example #3
Source File: LoadAndDisplayImageTask.java    From letv with Apache License 2.0 6 votes vote down vote up
private boolean waitIfPaused() {
    AtomicBoolean pause = this.engine.getPause();
    if (pause.get()) {
        synchronized (this.engine.getPauseLock()) {
            if (pause.get()) {
                L.d(LOG_WAITING_FOR_RESUME, this.memoryCacheKey);
                try {
                    this.engine.getPauseLock().wait();
                    L.d(LOG_RESUME_AFTER_PAUSE, this.memoryCacheKey);
                } catch (InterruptedException e) {
                    L.e(LOG_TASK_INTERRUPTED, this.memoryCacheKey);
                    return true;
                }
            }
        }
    }
    return isTaskNotActual();
}
 
Example #4
Source File: QueryResultsOutputUtil.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the results of a {@link QueryResultStream} to the output stream as NTriples until the
 * shutdown signal is set.
 *
 * @param out - The stream the NTriples data will be written to. (not null)
 * @param resultsStream - The results stream that will be polled for results to
 *   write to {@code out}. (not null)
 * @param shutdownSignal - Setting this signal will cause the thread that
 *   is processing this function to finish and leave. (not null)
 * @throws RDFHandlerException A problem was encountered while
 *   writing the NTriples to the output stream.
 * @throws IllegalStateException The {@code resultsStream} is closed.
 * @throws RyaStreamsException Could not fetch the next set of results.
 */
public static void toNtriplesFile(
        final OutputStream out,
        final QueryResultStream<VisibilityStatement> resultsStream,
        final AtomicBoolean shutdownSignal) throws RDFHandlerException, IllegalStateException, RyaStreamsException {
    requireNonNull(out);
    requireNonNull(resultsStream);
    requireNonNull(shutdownSignal);

    final RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, out);
    writer.startRDF();

    while(!shutdownSignal.get()) {
        final Iterable<VisibilityStatement> it = resultsStream.poll(1000);
        for(final VisibilityStatement result : it) {
            writer.handleStatement(result);
        }
    }

    writer.endRDF();
}
 
Example #5
Source File: CathInstallation.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
public CathInstallation(String cacheLocation, boolean usingCDDF, boolean parseCF) {
	setCacheLocation(cacheLocation);

	useCathDomainDescriptionFile = usingCDDF;
	parseCathFragments = parseCF;

	installedDomainDescription = new AtomicBoolean(false);
	installedDomainList = new AtomicBoolean(false);
	installedNodeList = new AtomicBoolean(false);
	installedDomall = new AtomicBoolean(false);

	cathVersion = DEFAULT_VERSION;
	cathDownloadUrl = CATH_DOWNLOAD_URL;

	pdbMap = new HashMap<String, List<CathDomain>>();
	domainMap = new HashMap<String ,CathDomain>();
	cathTree = new HashMap<String, CathNode>();

	if (parseCathFragments) fragmentMap = new HashMap<String,List<CathFragment>>();

}
 
Example #6
Source File: ClientSessionStateTest.java    From copycat with Apache License 2.0 6 votes vote down vote up
/**
 * Tests session state change callbacks.
 */
public void testSessionStateChange() {
  ClientSessionState state = new ClientSessionState(UUID.randomUUID().toString());
  AtomicBoolean changed = new AtomicBoolean();
  AtomicReference<Session.State> change = new AtomicReference<>();
  Listener<Session.State> listener = state.onStateChange(s -> {
    changed.set(true);
    change.set(s);
  });

  assertEquals(state.getState(), Session.State.CLOSED);
  state.setState(Session.State.CLOSED);
  assertFalse(changed.get());

  state.setState(Session.State.OPEN);
  assertTrue(changed.get());
  assertEquals(change.get(), Session.State.OPEN);

  changed.set(false);
  listener.close();

  state.setState(Session.State.EXPIRED);
  assertFalse(changed.get());
}
 
Example #7
Source File: TestReader.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
public TestReader(String name,
                  DistributedLogManager dlm,
                  DLSN startDLSN,
                  boolean simulateErrors,
                  int delayMs,
                  CountDownLatch readyLatch,
                  CountDownLatch countLatch,
                  CountDownLatch completionLatch) {
    this.readerName = name;
    this.dlm = dlm;
    this.startDLSN = startDLSN;
    this.simulateErrors = simulateErrors;
    this.delayMs = delayMs;
    this.readyLatch = readyLatch;
    this.countLatch = countLatch;
    this.completionLatch = completionLatch;
    // States
    this.errorsFound = new AtomicBoolean(false);
    this.readCount = new AtomicInteger(0);
    this.positionReaderCount = new AtomicInteger(0);
    // Executors
    this.executorService = Executors.newSingleThreadScheduledExecutor();
}
 
Example #8
Source File: ClusterTopicManipulationService.java    From kafka-monitor with Apache License 2.0 6 votes vote down vote up
public ClusterTopicManipulationService(String name, AdminClient adminClient) {
  LOGGER.info("ClusterTopicManipulationService constructor initiated {}", this.getClass().getName());

  _isOngoingTopicCreationDone = true;
  _isOngoingTopicDeletionDone = true;
  _adminClient = adminClient;
  _executor = Executors.newSingleThreadScheduledExecutor();
  _reportIntervalSecond = Duration.ofSeconds(1);
  _running = new AtomicBoolean(false);
  _configDefinedServiceName = name;
  // TODO: instantiate a new instance of ClusterTopicManipulationMetrics(..) here.

  MetricConfig metricConfig = new MetricConfig().samples(60).timeWindow(1000, TimeUnit.MILLISECONDS);
  List<MetricsReporter> reporters = new ArrayList<>();
  reporters.add(new JmxReporter(Service.JMX_PREFIX));
  Metrics metrics = new Metrics(metricConfig, reporters, new SystemTime());

  Map<String, String> tags = new HashMap<>();
  tags.put("name", name);
  _clusterTopicManipulationMetrics = new ClusterTopicManipulationMetrics(metrics, tags);
}
 
Example #9
Source File: RemoteDockerImageTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test(timeout=5000L)
public void toStringDoesntResolveLazyFuture() throws Exception {
    String imageName = Base58.randomString(8).toLowerCase();
    AtomicBoolean resolved = new AtomicBoolean(false);
    Future<String> imageNameFuture = new LazyFuture<String>() {
        @Override
        protected String resolve() {
            resolved.set(true);
            return imageName;
        }
    };

    // verify that we've set up the test properly
    assertFalse(imageNameFuture.isDone());

    RemoteDockerImage remoteDockerImage = new RemoteDockerImage(imageNameFuture);
    assertThat(remoteDockerImage.toString(), containsString("imageName=<resolving>"));

    // Make sure the act of calling toString doesn't resolve the imageNameFuture
    assertFalse(imageNameFuture.isDone());
    assertFalse(resolved.get());

    // Trigger resolve
    imageNameFuture.get();
    assertThat(remoteDockerImage.toString(), containsString("imageName=" + imageName));
}
 
Example #10
Source File: CompositeRetryListenerTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldPropagateRetryToEveryListener() {
    final AtomicBoolean success = new AtomicBoolean(false);

    final RequestArguments arguments = RequestArguments.create();
    final IllegalStateException exception = new IllegalStateException();

    Failsafe.with(new RetryPolicy<ClientHttpResponse>()
            .withMaxRetries(3)
            .onRetry(new RetryRequestPolicy.RetryListenerAdapter(unit, arguments)))
            .run(() -> {
                if (!success.getAndSet(true)) {
                    throw exception;
                }
            });

    verify(first).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastResult, nullValue())));
    verify(first).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastFailure, notNullValue())));
    verify(second).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastResult, nullValue())));
    verify(second).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastFailure, notNullValue())));
}
 
Example #11
Source File: HostSelectionWithFallbackTest.java    From dyno with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangingHashPartitioner() {
    cpConfig.setLoadBalancingStrategy(LoadBalancingStrategy.TokenAware);
    cpConfig.withTokenSupplier(getTokenMapSupplier());
    cpConfig.withHashPartitioner(getMockHashPartitioner(1000000000L));

    HostSelectionWithFallback<Integer> selection = new HostSelectionWithFallback<Integer>(cpConfig, cpMonitor);
    Map<Host, HostConnectionPool<Integer>> pools = new HashMap<Host, HostConnectionPool<Integer>>();

    for (Host host : hosts) {
        poolStatus.put(host, new AtomicBoolean(true));
        pools.put(host, getMockHostConnectionPool(host, poolStatus.get(host)));
    }

    selection.initWithHosts(pools);

    Connection<Integer> connection = selection.getConnection(testOperation, 10, TimeUnit.MILLISECONDS);

    // Verify that h1 has been selected instead of h2
    assertEquals("h1", connection.getHost().getHostAddress());
}
 
Example #12
Source File: OpenCookieFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void open() {
    if ( SwingUtilities.isEventDispatchThread()){
        final AtomicBoolean cancel = new AtomicBoolean();
        ProgressUtils.runOffEventDispatchThread(new Runnable() {
            @Override
            public void run() {
                doOpen();
            }
        },
        NbBundle.getMessage(OpenCookieFactory.class, "TXT_OpenResource"),    // NOI18N
        cancel,
        false);
    }
    else {
        doOpen();
    }
}
 
Example #13
Source File: FluxUsingWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void errorResourcePublisherAfterEmitIsDropped() {
	AtomicBoolean commitDone = new AtomicBoolean();
	AtomicBoolean rollbackDone = new AtomicBoolean();

	TestPublisher<String> testPublisher = TestPublisher.createCold();
	testPublisher.next("Resource").error(new IllegalStateException("boom"));

	Flux<String> test = Flux.usingWhen(testPublisher,
			Mono::just,
			tr -> Mono.fromRunnable(() -> commitDone.set(true)),
			(tr, err) -> Mono.fromRunnable(() -> rollbackDone.set(true)),
			tr -> Mono.fromRunnable(() -> rollbackDone.set(true)));

	StepVerifier.create(test)
	            .expectNext("Resource")
	            .expectComplete()
	            .verifyThenAssertThat(Duration.ofSeconds(2))
	            .hasDroppedErrorWithMessage("boom")
	            .hasNotDroppedElements();

	assertThat(commitDone).isTrue();
	assertThat(rollbackDone).isFalse();

	testPublisher.assertCancelled();
}
 
Example #14
Source File: SanityChecker.java    From rheem with Apache License 2.0 6 votes vote down vote up
private PlanTraversal.Callback getFlatAlternativeCallback(AtomicBoolean testOutcome) {
    return (operator, fromInputSlot, fromOutputSlot) -> {
        if (operator.isAlternative()) {
            final OperatorAlternative operatorAlternative = (OperatorAlternative) operator;
            for (OperatorAlternative.Alternative alternative : operatorAlternative.getAlternatives()) {
                final Collection<Operator> containedOperators = alternative.getContainedOperators();
                if (containedOperators.size() == 1) {
                    Operator containedOperator = RheemCollections.getSingle(containedOperators);
                    if (containedOperator.isAlternative()) {
                        this.logger.warn("Improper alternative {}: contains alternatives.", alternative);
                        testOutcome.set(false);
                    }
                } else {
                    // We could check if there are singleton Subplans with an OperatorAlternative embedded,
                    // but this would violate the singleton Subplan rule anyway.
                    alternative.traverse(this.getFlatAlternativeCallback(testOutcome));
                }
            }
        }
    };
}
 
Example #15
Source File: RestClusterClientSavepointTriggerTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testTriggerSavepointRetry() throws Exception {
	final TriggerId triggerId = new TriggerId();
	final String expectedSavepointDir = "hello";

	final AtomicBoolean failRequest = new AtomicBoolean(true);
	try (final RestServerEndpoint restServerEndpoint = createRestServerEndpoint(
		request -> triggerId,
		trigger -> {
			if (failRequest.compareAndSet(true, false)) {
				throw new RestHandlerException("expected", HttpResponseStatus.SERVICE_UNAVAILABLE);
			} else {
				return new SavepointInfo(expectedSavepointDir, null);
			}
		})) {

		final RestClusterClient<?> restClusterClient = createRestClusterClient(restServerEndpoint.getServerAddress().getPort());

		final String savepointPath = restClusterClient.triggerSavepoint(new JobID(), null).get();
		assertEquals(expectedSavepointDir, savepointPath);
	}
}
 
Example #16
Source File: ProcessMonitor.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
private static Future<?> monitor(InputStream input,
                                 Predicate<String> filter,
                                 Function<String, String> transform,
                                 Consumer<String> output,
                                 AtomicBoolean running) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
    return EXECUTOR.submit(() -> {
        while (running.get()) {
            reader.lines().forEach(line -> {
                if (filter.test(line)) {
                    output.accept(transform.apply(line));
                }
            });
        }
    });
}
 
Example #17
Source File: LinuxNotifier235632Test.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test of nextEvent method, of class LinuxNotifier.
 *
 * @throws java.lang.Exception
 */
public void testNextEvent() throws Exception {

    prepareFiles();

    final AtomicBoolean folder2refreshed = new AtomicBoolean(false);
    Logger log = Logger.getLogger(FolderObj.class.getName());

    Handler h = createHandler(folder2refreshed);
    log.addHandler(h);
    try {
        FileChangeListener l = new FileChangeAdapter();
        FileUtil.addFileChangeListener(l, folder1text1Txt);
        // This causes an IN_IGNORED native event.
        FileUtil.removeFileChangeListener(l, folder1text1Txt);
        // Native listeners may need some time.
        Thread.sleep(2000);
    } finally {
        log.removeHandler(h);
    }
    assertFalse("Folder folder2 should not be refreshed.",
            folder2refreshed.get());
}
 
Example #18
Source File: MobiusLoopDisposalBehavior.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void eventsFromEffectHandlerDuringDisposeAreIgnored() throws Exception {
  // Events emitted by the effect handler during dispose should be ignored.

  AtomicBoolean updateWasCalled = new AtomicBoolean();

  final MobiusLoop.Builder<String, TestEvent, TestEffect> builder =
      Mobius.loop(
          (model, event) -> {
            updateWasCalled.set(true);
            return Next.noChange();
          },
          new EmitDuringDisposeEffectHandler());

  builder.startFrom("foo").dispose();

  assertFalse(updateWasCalled.get());
}
 
Example #19
Source File: BaseCommandManager.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
protected <T> Future<T> submitToExecutorService(Callable<T> callable, Command<?> commandExecuting,
    CommandStatus originalCommandStatusObject, AtomicBoolean running) {
  Future<T> future = _executorServiceWorker.submit(callable);
  Long instanceExecutionId = getInstanceExecutionId();
  ResponseFuture<T> responseFuture = new ResponseFuture<T>(_runningCacheTombstoneTime, future,
      commandExecuting, originalCommandStatusObject, running);
  _workerRunningMap.put(instanceExecutionId, responseFuture);
  return responseFuture;
}
 
Example #20
Source File: AbstractMiningCoordinator.java    From besu with Apache License 2.0 5 votes vote down vote up
private synchronized boolean haltCurrentMiningOperation() {
  final AtomicBoolean wasHalted = new AtomicBoolean(false);
  currentRunningMiner.ifPresent(
      (miner) -> {
        haltMiner(miner);
        wasHalted.set(true);
      });
  currentRunningMiner = Optional.empty();
  return wasHalted.get();
}
 
Example #21
Source File: FileSystemReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
private CloseableIterator<T> createIterator(
    final FileSystemClient client,
    final RangeReaderParams<T> readerParams,
    final GeoWaveRowIteratorTransformer<T> rowTransformer,
    final Collection<SinglePartitionQueryRanges> ranges,
    final Set<String> authorizations,
    final boolean async) {
  final Iterator<CloseableIterator> it =
      Arrays.stream(ArrayUtils.toObject(readerParams.getAdapterIds())).map(
          adapterId -> new FileSystemQueryExecution(
              client,
              adapterId,
              readerParams.getInternalAdapterStore().getTypeName(adapterId),
              readerParams.getIndex().getName(),
              client.getFormat(),
              rowTransformer,
              ranges,
              new ClientVisibilityFilter(authorizations),
              DataStoreUtils.isMergingIteratorRequired(
                  readerParams,
                  client.isVisibilityEnabled()),
              async,
              FileSystemUtils.isGroupByRowAndIsSortByTime(readerParams, adapterId),
              FileSystemUtils.isSortByKeyRequired(readerParams)).results()).iterator();
  final CloseableIterator<T>[] itArray = Iterators.toArray(it, CloseableIterator.class);
  return new CloseableIteratorWrapper<>(new Closeable() {
    AtomicBoolean closed = new AtomicBoolean(false);

    @Override
    public void close() throws IOException {
      if (!closed.getAndSet(true)) {
        Arrays.stream(itArray).forEach(it -> it.close());
      }
    }
  }, Iterators.concat(itArray));
}
 
Example #22
Source File: Base.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
protected void chooseAttackersRace() {
	AtomicBoolean next = new AtomicBoolean(Math.random() < 0.5);
	for (Race race : list) {
		if (race == null) {
			throw new NullPointerException("Base:" + race + " race is null chooseAttackersRace!");
		}
		else if (!race.equals(getRace())) {
			if (next.compareAndSet(true, false)) {
				continue;
			}
			spawnAttackers(race);
		}
	}
}
 
Example #23
Source File: AbstractSMTPServerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisconnectHandler() throws Exception {
    
    final AtomicBoolean called = new AtomicBoolean(false);
    DisconnectHandler<SMTPSession> handler = session -> called.set(true);
    
    ProtocolServer server = null;
    try {
        server = createServer(createProtocol(handler));
        server.bind();
        
        SMTPClient client = createClient();
        InetSocketAddress bindedAddress = new ProtocolServerUtils(server).retrieveBindedAddress();
        client.connect(bindedAddress.getAddress().getHostAddress(), bindedAddress.getPort());
        assertThat(SMTPReply.isPositiveCompletion(client.getReplyCode())).as("Reply=" + client.getReplyString()).isTrue();
        
        client.disconnect();
        
        Thread.sleep(1000);
        assertThat(called.get()).isTrue();


    } finally {
        if (server != null) {
            server.unbind();
        }
    }
    
}
 
Example #24
Source File: Discovery.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** GemStoneAddition - tell the waiter it can start its countdown now */
public final void wakeWaiter(AtomicBoolean waiter_sync) {
    synchronized(waiter_sync) {
      waiter_sync.set(true);
      waiter_sync.notifyAll();
    }
}
 
Example #25
Source File: EndlessRecyclerViewAdapter.java    From double-direction-adapter-endless with MIT License 5 votes vote down vote up
public EndlessRecyclerViewAdapter(Context context,  Adapter wrapped, RequestToLoadMoreListener requestToLoadMoreListener, @LayoutRes int pendingViewResId, boolean keepOnAppendingAfter, boolean keepOnAppendingBefore) {
    super(wrapped);
    this.context = context;
    this.requestToLoadMoreListener = requestToLoadMoreListener;
    this.pendingViewResId = pendingViewResId;
    this.keepOnAppendingAfter = new AtomicBoolean(keepOnAppendingAfter);
    this.keepOnAppendingBefore = new AtomicBoolean(keepOnAppendingBefore);
    dataPendingAfter = new AtomicBoolean(false);
    dataPendingBefore = new AtomicBoolean(false);
}
 
Example #26
Source File: QueryEventWorkerTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void stoppedWork() throws Exception {
    // The signal that will kill the working thread.
    final AtomicBoolean shutdownSignal = new AtomicBoolean(false);

    // The queue used to send the execute work to the thread.
    final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);

    // The message that indicates a query needs to be stopped.
    final UUID queryId = UUID.randomUUID();
    final QueryEvent stoppedEvent = QueryEvent.stopped("rya", queryId);

    // Release a latch if the stopQuery method on the queryExecutor is invoked with the correct values.
    final CountDownLatch stopQueryInvoked = new CountDownLatch(1);
    final QueryExecutor queryExecutor = mock(QueryExecutor.class);
    doAnswer(invocation -> {
        stopQueryInvoked.countDown();
        return null;
    }).when(queryExecutor).stopQuery(queryId);

    final Thread queryEventWorker = new Thread(new QueryEventWorker(queue,
            queryExecutor, 50, TimeUnit.MILLISECONDS, shutdownSignal));
    try {
        // The thread that will perform the QueryEventWorker task.
        queryEventWorker.start();

        // Provide a message indicating a query needs to be executing.
        queue.put(stoppedEvent);

        // Verify the Query Executor was told to stop the query.
        assertTrue( stopQueryInvoked.await(150, TimeUnit.MILLISECONDS) );
    } finally {
        shutdownSignal.set(true);
        queryEventWorker.join();
    }
}
 
Example #27
Source File: CASFileCacheTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Test
public void expireEntryWaitsForUnreferencedEntry()
    throws ExecutionException, IOException, InterruptedException {
  byte[] bigData = new byte[1023];
  Arrays.fill(bigData, (byte) 1);
  ByteString bigContent = ByteString.copyFrom(bigData);
  Digest bigDigest = DIGEST_UTIL.compute(bigContent);
  blobs.put(bigDigest, bigContent);
  Path bigPath = fileCache.put(bigDigest, /* isExecutable=*/ false);

  AtomicBoolean started = new AtomicBoolean(false);
  ExecutorService service = newSingleThreadExecutor();
  Future<Void> putFuture =
      service.submit(
          new Callable<Void>() {
            @Override
            public Void call() throws IOException, InterruptedException {
              started.set(true);
              ByteString content = ByteString.copyFromUtf8("CAS Would Exceed Max Size");
              Digest digest = DIGEST_UTIL.compute(content);
              blobs.put(digest, content);
              fileCache.put(digest, /* isExecutable=*/ false);
              return null;
            }
          });
  while (!started.get()) {
    MICROSECONDS.sleep(1);
  }
  // minimal test to ensure that we're blocked
  assertThat(putFuture.isDone()).isFalse();
  decrementReference(bigPath);
  try {
    putFuture.get();
  } finally {
    if (!shutdownAndAwaitTermination(service, 1, SECONDS)) {
      throw new RuntimeException("could not shut down service");
    }
  }
}
 
Example #28
Source File: FirebaseDatabaseAuthTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static void doRead(
    DatabaseReference ref, final boolean shouldSucceed, final boolean shouldTimeout)
    throws InterruptedException {
  final CountDownLatch lock = new CountDownLatch(1);
  final AtomicBoolean success = new AtomicBoolean(false);
  ref.addListenerForSingleValueEvent(
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          success.compareAndSet(false, true);
          lock.countDown();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
          lock.countDown();
        }
      });

  boolean finished = lock.await(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  if (shouldTimeout) {
    assertTrue("Read finished (expected to timeout).", !finished);
  } else if (shouldSucceed) {
    assertTrue("Read timed out (expected to succeed).", finished);
    assertTrue("Read failed (expected to succeed).", success.get());
  } else {
    assertTrue("Read timed out (expected to fail).", finished);
    assertTrue("Read successful (expected to fail).", !success.get());
  }
}
 
Example #29
Source File: N4JSAllContainersState.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles the given {@link IResourceChangeEvent} and updates the project state (cache of available projects and
 * project descriptions) accordingly.
 *
 * If the event contains a {@link IResourceDelta}, this method traverses the resource delta tree and invokes
 * {@link #updateProjectState(IResourceDelta)} accordingly.
 */
private void updateProjectState(IResourceChangeEvent event) {
	if (event.getDelta() != null) {
		IResourceDelta eventDelta = event.getDelta();
		try {
			AtomicBoolean mustClear = new AtomicBoolean(false);
			// traverse all resource deltas to a depth of 2 (projects and their direct children)
			eventDelta.accept(new IResourceDeltaVisitor() {
				@Override
				public boolean visit(IResourceDelta delta) throws CoreException {
					final IResource resource = delta.getResource();
					if (resource == null) {
						return true;
					}
					final IPath path = resource.getFullPath();
					final int pathLength = path.segmentCount();

					if (pathLength <= 2) {
						if (updateProjectState(delta)) {
							mustClear.set(true);
							return false;
						}
					}
					// only traverse the children of project-deltas (e.g. project description files)
					return pathLength == 0 || resource instanceof IProject;
				}
			});
			if (mustClear.get()) {
				projectsHelper.clearProjectCache();
			}
		} catch (CoreException e) {
			LOGGER.error("Failed to process IResourceDelta", e);
		}
	}
}
 
Example #30
Source File: ChannelConnectionTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    Utils.setMockClock(); // Use mock clock
    Context.propagate(new Context(PARAMS, 3, Coin.ZERO, false)); // Shorter event horizon for unit tests.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    wallet.addExtension(new StoredPaymentChannelClientStates(wallet, failBroadcaster));
    serverWallet = new Wallet(PARAMS);
    serverWallet.addExtension(new StoredPaymentChannelServerStates(serverWallet, failBroadcaster));
    serverWallet.freshReceiveKey();
    // Use an atomic boolean to indicate failure because fail()/assert*() dont work in network threads
    fail = new AtomicBoolean(false);

    // Set up a way to monitor broadcast transactions. When you expect a broadcast, you must release a permit
    // to the broadcastTxPause semaphore so state can be queried in between.
    broadcasts = new LinkedBlockingQueue<>();
    broadcastTxPause = new Semaphore(0);
    mockBroadcaster = new TransactionBroadcaster() {
        @Override
        public TransactionBroadcast broadcastTransaction(Transaction tx) {
            broadcastTxPause.acquireUninterruptibly();
            SettableFuture<Transaction> future = SettableFuture.create();
            future.set(tx);
            broadcasts.add(tx);
            return TransactionBroadcast.createMockBroadcast(tx, future);
        }
    };

    // Because there are no separate threads in the tests here (we call back into client/server in server/client
    // handlers), we have lots of lock cycles. A normal user shouldn't have this issue as they are probably not both
    // client+server running in the same thread.
    Threading.warnOnLockCycles();

    ECKey.FAKE_SIGNATURES = true;
}