Java 类java.util.concurrent.atomic.AtomicBoolean 实例源码

项目:openjdk-jdk10    文件:LockSupportTest.java   
public void testParkAfterUnpark(final ParkMethod parkMethod) {
    final CountDownLatch pleaseUnpark = new CountDownLatch(1);
    final AtomicBoolean pleasePark = new AtomicBoolean(false);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            pleaseUnpark.countDown();
            while (!pleasePark.get())
                Thread.yield();
            parkMethod.park();
        }});

    await(pleaseUnpark);
    LockSupport.unpark(t);
    pleasePark.set(true);
    awaitTermination(t);
}
项目:jdk8u-jdk    文件:BadHandshakeTest.java   
private static Process launch(String address, String class_name) throws Exception {
    String[] args = VMConnection.insertDebuggeeVMOptions(new String[] {
        "-agentlib:jdwp=transport=dt_socket" +
        ",server=y" + ",suspend=y" + ",address=" + address,
        class_name
    });

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args);

    final AtomicBoolean success = new AtomicBoolean();
    Process p = ProcessTools.startProcess(
        class_name,
        pb,
        (line) -> {
            // The first thing that will get read is
            //    Listening for transport dt_socket at address: xxxxx
            // which shows the debuggee is ready to accept connections.
            success.set(line.contains("Listening for transport dt_socket at address:"));
            return true;
        },
        Integer.MAX_VALUE,
        TimeUnit.MILLISECONDS
    );

    return success.get() ? p : null;
}
项目:openjdk-jdk10    文件:FileHandlerPath.java   
public SimplePolicy(TestCase test, AtomicBoolean allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null)); // needed by new FileHandler()
    permissions.add(new FilePermission("<<ALL FILES>>", "read")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(logFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(userDir, "write")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpDir, "write")); // needed by new FileHandler()
    permissions.add(new PropertyPermission("user.dir", "read"));
    permissions.add(new PropertyPermission("java.io.tmpdir", "read"));
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
项目:textmd    文件:EditorExitItem.java   
@Override
public void getClickAction(final Stage stage, final TabFactory tabFactory) {
    List<Tab> tabs = FXCollections.observableArrayList(tabFactory.getTabPane().getTabs());
    Collections.reverse(tabs);
    AtomicBoolean close = new AtomicBoolean(true);
    tabs.forEach(t -> {
        if(close.get()){
            EditorTab eTab = ((EditorTab) t);
            if(!eTab.getEditorPane().exit()){
                close.set(false);
                return;
            }else{
                logger.debug("Closing tab {}", eTab.getEditorPane().getFile().getPath());
                tabFactory.getTabPane().getTabs().remove(eTab);
            }
        }
    });
    if(close.get())
        stage.close();
}
项目:monarch    文件:PartitionedRegionRebalanceOp.java   
/**
 * Create a rebalance operation for a single region.
 * 
 * @param region the region to rebalance
 * @param simulate true to only simulate rebalancing, without actually doing anything
 * @param replaceOfflineData true to replace offline copies of buckets with new live copies of
 *        buckets
 * @param isRebalance true if this op is a full rebalance instead of a more limited redundancy
 *        recovery
 * @param cancelled the AtomicBoolean reference used for cancellation; if any code sets the AB
 *        value to true then the rebalance will be cancelled
 * @param stats the ResourceManagerStats to use for rebalancing stats
 */
public PartitionedRegionRebalanceOp(PartitionedRegion region, boolean simulate,
    RebalanceDirector director, boolean replaceOfflineData, boolean isRebalance,
    AtomicBoolean cancelled, ResourceManagerStats stats) {

  PartitionedRegion leader = ColocationHelper.getLeaderRegion(region);
  Assert.assertTrue(leader != null);

  // set the region we are rebalancing to be leader of the colocation group.
  this.leaderRegion = leader;
  this.targetRegion = region;
  this.simulate = simulate;
  this.director = director;
  this.cancelled = cancelled;
  this.replaceOfflineData = replaceOfflineData;
  this.isRebalance = isRebalance;
  this.stats = simulate ? null : stats;
}
项目:GitHub    文件:OsSharedRealmTests.java   
@Test
public void registerSchemaChangedCallback_beginTransaction() {
    final AtomicBoolean listenerCalled = new AtomicBoolean(false);

    assertFalse(sharedRealm.hasTable("NewTable"));

    sharedRealm.registerSchemaChangedCallback(new OsSharedRealm.SchemaChangedCallback() {
        @Override
        public void onSchemaChanged() {
            assertTrue(sharedRealm.hasTable("NewTable"));
            listenerCalled.set(true);
        }
    });
    changeSchemaByAnotherRealm();
    sharedRealm.beginTransaction();
    assertTrue(listenerCalled.get());
}
项目:incubator-netbeans    文件:GoToSuperTypeAction.java   
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    final JavaSource js = JavaSource.forDocument(target.getDocument());

    if (js == null) {
        StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(GoToSupport.class, "WARN_CannotGoToGeneric",1));
        return;
    }

    final int caretPos = target.getCaretPosition();
    final AtomicBoolean cancel = new AtomicBoolean();

    ProgressUtils.runOffEventDispatchThread(new Runnable() {
        @Override
        public void run() {
            goToImpl(target, js, caretPos, cancel);
        }
    }, NbBundle.getMessage(JavaKit.class, "goto-super-implementation"), cancel, false);
}
项目:kafka-0.11.0.0-src-with-comment    文件:KafkaConsumerTest.java   
private AtomicBoolean prepareOffsetCommitResponse(MockClient client, Node coordinator, final Map<TopicPartition, Long> partitionOffsets) {
    final AtomicBoolean commitReceived = new AtomicBoolean(true);
    Map<TopicPartition, Errors> response = new HashMap<>();
    for (TopicPartition partition : partitionOffsets.keySet())
        response.put(partition, Errors.NONE);

    client.prepareResponseFrom(new MockClient.RequestMatcher() {
        @Override
        public boolean matches(AbstractRequest body) {
            OffsetCommitRequest commitRequest = (OffsetCommitRequest) body;
            for (Map.Entry<TopicPartition, Long> partitionOffset : partitionOffsets.entrySet()) {
                OffsetCommitRequest.PartitionData partitionData = commitRequest.offsetData().get(partitionOffset.getKey());
                // verify that the expected offset has been committed
                if (partitionData.offset != partitionOffset.getValue()) {
                    commitReceived.set(false);
                    return false;
                }
            }
            return true;
        }
    }, offsetCommitResponse(response), coordinator);
    return commitReceived;
}
项目:incubator-netbeans    文件:BasicCustomizer.java   
@Messages({
    "PROGRESS_loading_data=Loading project information",
    "# {0} - project display name", "LBL_CustomizerTitle=Project Properties - {0}"
})
public void showCustomizer(String preselectedCategory, final String preselectedSubCategory) {
    if (dialog != null) {
        dialog.setVisible(true);
    } else {
        final String category = (preselectedCategory != null) ? preselectedCategory : lastSelectedCategory;
        final AtomicReference<Lookup> context = new AtomicReference<Lookup>();
        ProgressUtils.runOffEventDispatchThread(new Runnable() {
            @Override public void run() {
                context.set(new ProxyLookup(prepareData(), Lookups.fixed(new SubCategoryProvider(category, preselectedSubCategory))));
            }
        }, PROGRESS_loading_data(), /* currently unused */new AtomicBoolean(), false);
        if (context.get() == null) { // canceled
            return;
        }
        OptionListener listener = new OptionListener();
        dialog = ProjectCustomizer.createCustomizerDialog(layerPath, context.get(), category, listener, null);
        dialog.addWindowListener(listener);
        dialog.setTitle(LBL_CustomizerTitle(ProjectUtils.getInformation(getProject()).getDisplayName()));
        dialog.setVisible(true);
    }
}
项目:fdt    文件:SelectionManager.java   
SelectionTask(Selector selector) {

            renewQueue = new ArrayDeque<FDTSelectionKey>();
            newQueue = new ArrayDeque<FDTSelectionKey>();

            hasToRun = new AtomicBoolean(false);

            if (selector == null) {
                throw new NullPointerException("Selector cannot be null in SelectionTask constructor");
            }

            if (!selector.isOpen()) {
                throw new IllegalArgumentException("Selector is not open in SelectionTask constructor");
            }

            this.selector = selector;
            hasToRun.set(true);
        }
项目:cyberduck    文件:ComparisonServiceFilterTest.java   
@Test
public void testCompareLocalOnlyDirectory() throws Exception {
    final AtomicBoolean found = new AtomicBoolean();
    final Find find = new Find() {
        @Override
        public boolean find(final Path file) throws BackgroundException {
            found.set(true);
            return false;
        }

        @Override
        public Find withCache(Cache<Path> cache) {
            return this;
        }
    };
    ComparisonServiceFilter s = new ComparisonServiceFilter(new NullSession(new Host(new TestProtocol())) {
    }, TimeZone.getDefault(), new DisabledProgressListener()).withFinder(find);
    assertEquals(Comparison.local, s.compare(new Path("t", EnumSet.of(Path.Type.directory)), new NullLocal("t") {
        @Override
        public boolean exists() {
            return true;
        }
    }));
    assertTrue(found.get());
}
项目:letv    文件:LoadAndDisplayImageTask.java   
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();
}
项目:WeatherWeight    文件:ForecastPresenterTest.java   
@Test
public void searchOnSuccess() {
    String location = "San Francisco, CA";
    Channel channel = WeatherResponseFactory.createChannel();
    when(weatherRepository.getForecast(location)).thenReturn(Single.just(channel));

    final AtomicBoolean completableSubscribed = new AtomicBoolean(false);
    Completable saveCompletable = Completable.complete().doOnSubscribe(new Consumer<Disposable>() {
        @Override
        public void accept(Disposable disposable) throws Exception {
            completableSubscribed.set(true);
        }
    });
    when(lastForecastStore.save(channel)).thenReturn(saveCompletable);

    presenter.search(location);

    verify(view).showLoading(false);
    checkChannelSet(channel);
    assertThat(completableSubscribed.get(), is(true));
    assertThat(presenter.getAttributionUrl(), is(channel.getLink()));
}
项目:java-red    文件:TestRedFuture.java   
/**
 * Test the completion and callback invocation of {@link RedFutureHub}
 * pessimistic union of provided futures that later were successfully resolved
 */
@Test
public void testPessimisticProvidePostResolveSuccess() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    RedFutureHub hub = RedFuture.hub();
    OpenRedFuture future1 = hub.provideFuture();
    OpenRedFuture future2 = hub.provideFuture();
    OpenRedFutureOf<Object> futureOf = hub.provideFutureOf();
    RedFuture union = hub.unitePessimistically();
    union.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    union.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    union.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    Assert.assertFalse(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
    future1.resolve();
    future2.resolve();
    futureOf.resolve(new Object());
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertTrue(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
}
项目:googles-monorepo-demo    文件:AtomicLongMap.java   
/**
 * If {@code key} is not already associated with a value or if {@code key} is associated with
 * zero, associate it with {@code newValue}. Returns the previous value associated with
 * {@code key}, or zero if there was no mapping for {@code key}.
 */
long putIfAbsent(K key, long newValue) {
  AtomicBoolean noValue = new AtomicBoolean(false);
  Long result =
      map.compute(
          key,
          (k, oldValue) -> {
            if (oldValue == null || oldValue == 0) {
              noValue.set(true);
              return newValue;
            } else {
              return oldValue;
            }
          });
  return noValue.get() ? 0L : result.longValue();
}
项目:GitHub    文件:RxJavaTests.java   
@Test
@UiThreadTest
public void realmObject_emittedOnSubscribe() {
    realm.beginTransaction();
    final AllTypes obj = realm.createObject(AllTypes.class);
    realm.commitTransaction();

    final AtomicBoolean subscribedNotified = new AtomicBoolean(false);
    subscription = obj.<AllTypes>asFlowable().subscribe(new Consumer <AllTypes>() {
        @Override
        public void accept(AllTypes rxObject) throws Exception {
            assertTrue(rxObject == obj);
            subscribedNotified.set(true);
        }
    });
    assertTrue(subscribedNotified.get());
    subscription.dispose();
}
项目:cordova-plugin-smartconfig    文件:__EsptouchTask.java   
public __EsptouchTask(String apSsid, String apBssid, String apPassword,
        Context context, IEsptouchTaskParameter parameter,
        boolean isSsidHidden) {
    Log.i(TAG, "Welcome Esptouch " + ESPTOUCH_VERSION);
    if (TextUtils.isEmpty(apSsid)) {
        throw new IllegalArgumentException(
                "the apSsid should be null or empty");
    }
    if (apPassword == null) {
        apPassword = "";
    }
    mContext = context;
    mApSsid = apSsid;
    mApBssid = apBssid;
    mApPassword = apPassword;
    mIsCancelled = new AtomicBoolean(false);
    mSocketClient = new UDPSocketClient();
    mParameter = parameter;
    mSocketServer = new UDPSocketServer(mParameter.getPortListening(),
            mParameter.getWaitUdpTotalMillisecond(), context);
    mIsSsidHidden = isSsidHidden;
    mEsptouchResultList = new ArrayList<IEsptouchResult>();
    mBssidTaskSucCountMap = new HashMap<String, Integer>();
}
项目:incubator-netbeans    文件:LinuxNotifier235632Test.java   
/**
 * Create a logging handler that sets value in an AtomicBoolean to true if
 * folder2 or text2.txt is refreshed.
 *
 * @param refreshedFlag The AtomicBoolean to be set to true if incorrect
 * refreshing was triggered.
 * @return The new logging handler.
 */
private Handler createHandler(final AtomicBoolean refreshedFlag) {
    Handler h = new Handler() {

        @Override
        public void publish(LogRecord record) {
            if (record.getMessage() != null
                    && record.getMessage().startsWith("refreshImpl for ")
                    && record.getParameters() != null
                    && record.getParameters().length > 0
                    && (record.getParameters()[0] == folder2FO
                    || record.getParameters()[0] == folder2text2TxtFO)) {
                refreshedFlag.set(true);
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    return h;
}
项目:booter-injector    文件:Suppliers.java   
/**
 * This method transforms input supplier which creates instances of other suppliers into lazily instantiating
 * supplier. In other words, input factory which creates instances of suppliers will be invoked only once and only
 * when first call to created supplier will be made. Note that after creation of supplier, resulting supplier
 * becomes very thin wrapper around created supplier and is subject of HotSpot optimizations during
 * further calls.
 *
 * @param factory
 *          Factory supplier which provides instances of supplier of specified type. Invoked only once.
 * @return Lazily instantiating supplier.
 */
public static <T> Supplier<T> factoryLazy(final Supplier<Supplier<T>> factory) {
    Utils.validateNotNull(factory);

    return new Supplier<T>() {
        private final Supplier<T> defaultDelegate = this::init;
        private final AtomicBoolean initialized = new AtomicBoolean();
        private Supplier<T> delegate = defaultDelegate;

        private T init() {
            if (initialized.compareAndSet(false, true)) {
                delegate = factory.get();
            } else {
                while (delegate == defaultDelegate) {
                    //Intentionally left empty
                }
            }
            return delegate.get();
        }

        public T get() {
            return delegate.get();
        }
    };
}
项目:jdk8u-jdk    文件:FileHandlerPath.java   
public SimplePolicy(TestCase test, AtomicBoolean allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null)); // needed by new FileHandler()
    permissions.add(new FilePermission("<<ALL FILES>>", "read")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(logFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(userDir, "write")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpDir, "write")); // needed by new FileHandler()
    permissions.add(new PropertyPermission("user.dir", "read"));
    permissions.add(new PropertyPermission("java.io.tmpdir", "read"));
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
项目:RxJava3-preview    文件:FlowableCollectTest.java   
@Test
public void testCollectorFailureDoesNotResultInErrorAndOnNextEmissions() {
    final RuntimeException e = new RuntimeException();
    final AtomicBoolean added = new AtomicBoolean();
    BiConsumer<Object, Integer> throwOnFirstOnly = new BiConsumer<Object, Integer>() {

        boolean once = true;

        @Override
        public void accept(Object o, Integer t) {
            if (once) {
                once = false;
                throw e;
            } else {
                added.set(true);
            }
        }
    };
    Burst.items(1, 2).create() //
            .collect(callableListCreator(), throwOnFirstOnly)//
            .test() //
            .assertError(e) //
            .assertNoValues() //
            .assertNotComplete();
    assertFalse(added.get());
}
项目:incubator-netbeans    文件:RunOffEDTTest.java   
public void testDlgIsShown() throws Exception {
    final R r = new R();
    r.l = new CountDownLatch(1);
    final boolean[] shown = new boolean[] { false };
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
            if (w != null) {
                r.l.countDown();
                shown[0] = true;
            }
        }
    });
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
            ProgressUtils.runOffEventDispatchThread(r, "Test", new AtomicBoolean(false), true, 10, 100);
        }
    });
    if (!shown[0]) {
        fail("Dialog was not shown");
    }
}
项目:flume-release-1.7.0    文件:SinkRunner.java   
@Override
public void start() {
  SinkProcessor policy = getPolicy();

  policy.start();

  runner = new PollingRunner();

  runner.policy = policy;
  runner.counterGroup = counterGroup;
  runner.shouldStop = new AtomicBoolean();

  runnerThread = new Thread(runner);
  runnerThread.setName("SinkRunner-PollingRunner-" +
      policy.getClass().getSimpleName());
  runnerThread.start();

  lifecycleState = LifecycleState.START;
}
项目:cyberduck    文件:SFTPSessionTest.java   
@Test(expected = LoginCanceledException.class)
public void testValidateNoValidCredentials() throws Exception {
    final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch");
    final Session session = new SFTPSession(host);
    final AtomicBoolean change = new AtomicBoolean();
    final LoginConnectionService login = new LoginConnectionService(new DisabledLoginCallback() {
        @Override
        public Credentials prompt(final Host bookmark, String username,
                                  String title, String reason, LoginOptions options)
            throws LoginCanceledException {
            assertEquals("Login test.cyberduck.ch", title);
            assertEquals("Login test.cyberduck.ch – SFTP with username and password. No login credentials could be found in the Keychain.", reason);
            change.set(true);
            throw new LoginCanceledException();
        }
    }, new DisabledHostKeyCallback(), new DisabledPasswordStore(),
        new DisabledProgressListener());
    try {
        login.check(session, PathCache.empty(), new DisabledCancelCallback());
    }
    catch(LoginCanceledException e) {
        assertTrue(change.get());
        throw e;
    }
}
项目:GitHub    文件:MediaVariationsFallbackProducerTest.java   
@Test
public void testLooksForAllVariantsFromIndexIfNotFound() {
  when(mImageRequest.getMediaVariations()).thenReturn(mEmptyMediaVariations);
  whenIndexDbContainsAllVariants();

  mMediaVariationsFallbackProducer.produceResults(mConsumer, mProducerContext);

  // Check they're requested in the correct order
  InOrder inOrder = inOrder(mDefaultBufferedDiskCache);
  inOrder.verify(mDefaultBufferedDiskCache).get(eq(CACHE_KEY_M), any(AtomicBoolean.class));
  inOrder.verify(mDefaultBufferedDiskCache).get(eq(CACHE_KEY_L), any(AtomicBoolean.class));
  inOrder.verify(mDefaultBufferedDiskCache).get(eq(CACHE_KEY_S), any(AtomicBoolean.class));

  verifyInputProducerProduceResultsWithNewConsumer(true);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  verifySuccessSentToListener(
      NOT_FOUND,
      USED_AS_LAST_FLAG_NOT_EXPECTED,
      MediaVariations.SOURCE_INDEX_DB,
      VARIANTS_COUNT);
  verifyZeroInteractions(mConsumer, mSmallImageBufferedDiskCache);
}
项目:pooled-jms    文件:JmsPoolJMSProducerTest.java   
private void doTestSendAppliesPriorityWithMessageBody(Class<?> bodyType) throws JMSException {
    JMSProducer producer = context.createProducer();

    final AtomicBoolean lowPriority = new AtomicBoolean();
    final AtomicBoolean highPriority = new AtomicBoolean();

    MockJMSConnection connection = (MockJMSConnection) context.getConnection();
    connection.addConnectionListener(new MockJMSDefaultConnectionListener() {

        @Override
        public void onMessageSend(MockJMSSession session, Message message) throws JMSException {
            if (!lowPriority.get()) {
                assertEquals(0, message.getJMSPriority());
                lowPriority.set(true);
            } else {
                assertEquals(7, message.getJMSPriority());
                highPriority.set(true);
            }
        }
    });

    producer.setPriority(0);
    producer.send(JMS_DESTINATION, "text");

    producer.setPriority(7);
    producer.send(JMS_DESTINATION, "text");

    assertTrue(lowPriority.get());
    assertTrue(highPriority.get());
}
项目:incubator-netbeans    文件:CopyFinderBasedBulkSearch.java   
@Override
public BulkPattern create(Collection<? extends String> code, Collection<? extends Tree> patterns, Collection<? extends AdditionalQueryConstraints> additionalConstraints, AtomicBoolean cancel) {
    Map<Tree, String> pattern2Code = new HashMap<Tree, String>();

    Iterator<? extends String> itCode = code.iterator();
    Iterator<? extends Tree>   itPatt = patterns.iterator();

    while (itCode.hasNext() && itPatt.hasNext()) {
        pattern2Code.put(itPatt.next(), itCode.next());
    }

    return new BulkPatternImpl(additionalConstraints, pattern2Code);
}
项目:incubator-servicecomb-java-chassis    文件:TestEventBus.java   
@Test
public void test() throws InterruptedException {
  AtomicBoolean eventReceived = new AtomicBoolean(false);

  EventListener listener = new EventListener() {
    @Override
    public Class<? extends Event> getConcernedEvent() {
      return TestEvent.class;
    }

    @Override
    public void process(Event data) {
      eventReceived.set(true);
    }
  };

  EventUtils.registerEventListener(listener);
  EventUtils.triggerEvent(new TestEvent());
  await().atMost(1, TimeUnit.SECONDS)
      .until(eventReceived::get);
  Assert.assertTrue(eventReceived.get());

  eventReceived.set(false);

  EventUtils.unregisterEventListener(listener);
  EventUtils.triggerEvent(new TestEvent());
  Thread.sleep(1000);
  Assert.assertFalse(eventReceived.get());
}
项目:incubator-netbeans    文件:HtmlPaletteCompletionProvider.java   
@Override
protected boolean canFilter(final JTextComponent component) {
    final Collection<PaletteCompletionItem> currentItems = items;
    if(currentItems == null) {
        return false;
    }
    final Document doc = component.getDocument();
    final AtomicBoolean retval = new AtomicBoolean();
    doc.render(new Runnable() {

        @Override
        public void run() {
            try {
                int offset = component.getCaretPosition();
                if (completionExpressionStartOffset < 0  || offset < completionExpressionStartOffset) {
                    retval.set(false);
                    return;
                }
                String prefix = doc.getText(completionExpressionStartOffset, offset - completionExpressionStartOffset);
                //check the items
                for (PaletteCompletionItem item : currentItems) {
                    if (startsWithIgnoreCase(item.getItemName(), prefix)) {
                        retval.set(true); //at least one item will remain
                        return;
                    }
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });


    return retval.get();

}
项目:incubator-netbeans    文件:Analyzer.java   
public static void process(Lookup context, HintsSettings hintsSettings) {
    final AtomicBoolean abCancel = new AtomicBoolean();
    class Cancel implements Cancellable {
        public boolean cancel() {
            abCancel.set(true);
            return true;
        }
    }

    ProgressHandle h = ProgressHandleFactory.createHandle(NbBundle.getMessage(Analyzer.class, "LBL_AnalyzingJavadoc"), new Cancel()); // NOI18N

    RP.post(new Analyzer(context, abCancel, h, hintsSettings));
}
项目:FJ-VDMJ    文件:TCForIndexStatement.java   
@Override
public TCNameSet getFreeVariables(Environment globals, Environment env, AtomicBoolean returns)
{
    TCNameSet names = from.getFreeVariables(globals, env);
    names.addAll(to.getFreeVariables(globals, env));

    if (by != null)
    {
        names.addAll(by.getFreeVariables(globals, env));
    }

    return names;
}
项目:Matcher    文件:FileMenu.java   
private static boolean clearDir(Path path, Predicate<Path> disallowed) throws IOException {
    try (Stream<Path> stream = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {
        if (stream.anyMatch(disallowed)) return false;
    }

    AtomicBoolean ret = new AtomicBoolean(true);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (disallowed.test(file)) {
                ret.set(false);

                return FileVisitResult.TERMINATE;
            } else {
                Files.delete(file);

                return FileVisitResult.CONTINUE;
            }
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc != null) throw exc;
            if (!dir.equals(path)) Files.delete(dir);

            return FileVisitResult.CONTINUE;
        }
    });

    return ret.get();
}
项目:nativescript-simple-networking    文件:TcpServer.java   
public TcpServer(int maxClients, TcpServerListener listener) {
    mMaxClients = maxClients;
    mListener = listener;
    mExecutor = Executors.newFixedThreadPool(maxClients + 2);
    mClients = new ConcurrentHashMap<>();
    mIsAccepting = new AtomicBoolean(false);
    mId = new AtomicInteger();
}
项目:openjdk-jdk10    文件:HandlersOnComplexUpdate.java   
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null));
    permissions.add(new FilePermission(PREFIX+".lck", "read,write,delete"));
    permissions.add(new FilePermission(PREFIX, "read,write"));

    // these are used for configuring the test itself...
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());

}
项目:grooves    文件:QueryExecutor.java   
/**
 * Decides how to proceed after inspecting the response of a method that returns an
 * {@link EventApplyOutcome}.
 *
 * @param stopApplyingEvents Whether a previous decision has been made to stop applying new
 *                           events
 * @param snapshot           The snapshot on which events are being added
 * @param methodName         The name of the method that was called
 * @param retval             The outcome of calling the method
 *
 * @return The snapshot after deciding what to do with the {@link EventApplyOutcome}
 */
private Flowable<? extends SnapshotT> handleMethodResponse(
        AtomicBoolean stopApplyingEvents, SnapshotT snapshot, String methodName,
        EventApplyOutcome retval) {
    switch (retval) {
        case RETURN:
            stopApplyingEvents.set(true);
            return just(snapshot);
        case CONTINUE:
            return just(snapshot);
        default:
            throw new GroovesException(
                    String.format("Unexpected value from calling '%s'", methodName));
    }
}
项目:incubator-netbeans    文件:LuceneIndex.java   
@Override
public <T> void queryTermFrequencies(
        final @NonNull Collection<? super T> result,
        final @NullAllowed Term seekTo,
        final @NonNull StoppableConvertor<Index.WithTermFrequencies.TermFreq,T> filter,
        final @NullAllowed AtomicBoolean cancel) throws IOException, InterruptedException {
    queryTermsImpl(result, seekTo, Convertors.newTermEnumToFreqConvertor(filter), cancel);
}
项目:incubator-netbeans    文件:UnitTestLibrariesNode.java   
private void refreshKeys() {
    ImportantFilesNodeFactory.getNodesSyncRP().post(new Runnable() {

        @Override
        public void run() {
            try {
                ProjectManager.mutex().readAccess(new Mutex.ExceptionAction<Object>() {
                    public @Override Object run() throws Exception {
                        final Collection<TestModuleDependency> deps = new TreeSet<TestModuleDependency>(TestModuleDependency.CNB_COMPARATOR);
                        final AtomicBoolean missingJUnit4 = new AtomicBoolean(true);
                        Set<TestModuleDependency> tmds = new ProjectXMLManager(project).getTestDependencies(project.getModuleList()).get(testType);
                        if (tmds != null) { // will be null if have no <test-dependencies> of this type
                            for (TestModuleDependency tmd : tmds) {
                                deps.add(tmd);
                                if (tmd.getModule().getCodeNameBase().equals("org.netbeans.libs.junit4")) { // NOI18N
                                    missingJUnit4.set(false);
                                }
                            }
                        }
                        ImportantFilesNodeFactory.getNodesSyncRP().post(new Runnable() {
                            public @Override void run() {
                                ((UnitTestLibrariesNode) getNode()).setMissingJUnit4(missingJUnit4.get());
                                setKeys(deps);
                            }
                        });
                        return null;
                    }
                });
            } catch (MutexException e) {
                LOG.log(Level.INFO, null, e);
            }
        }
    });
}
项目:uavstack    文件:BooleanCodec.java   
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    final JSONLexer lexer = parser.getLexer();

    Boolean boolObj;
    if (lexer.token() == JSONToken.TRUE) {
        lexer.nextToken(JSONToken.COMMA);
        boolObj = Boolean.TRUE;
    } else if (lexer.token() == JSONToken.FALSE) {
        lexer.nextToken(JSONToken.COMMA);
        boolObj = Boolean.FALSE;
    } else if (lexer.token() == JSONToken.LITERAL_INT) {
        int intValue = lexer.intValue();
        lexer.nextToken(JSONToken.COMMA);

        if (intValue == 1) {
            boolObj = Boolean.TRUE;
        } else {
            boolObj = Boolean.FALSE;
        }
    } else {
        Object value = parser.parse();

        if (value == null) {
            return null;
        }

        boolObj = TypeUtils.castToBoolean(value);
    }

    if (clazz == AtomicBoolean.class) {
        return (T) new AtomicBoolean(boolObj.booleanValue());
    }

    return (T) boolObj;
}
项目:incubator-netbeans    文件:ComputeOffAWT.java   
public static <T> T computeOffAWT(Worker<T> w, String featureName, final JavaSource source, Phase phase) {
    AtomicBoolean cancel = new AtomicBoolean();
    Compute<T> c = new Compute(cancel, source, phase, w);

    ProgressUtils.runOffEventDispatchThread(c, featureName, cancel, false);

    return c.result;
}
项目:htsjdk-s3-plugin    文件:PartReader.java   
PartReader(AmazonS3URI uri, long from, long to, AtomicBoolean canceledFlag,
        S3InputStreamFactory factory) {
    this.canceledFlag = canceledFlag;
    this.uri = uri;
    this.from = from;
    this.to = to;

    this.threadName = "[" + from + " : " + to + "](" + uri.toString() + ")";

    this.factory = factory;
}