@Override
 public void close() throws IOException, InterruptedException {
   try {
     m_outstandingWriteTasksLock.lock();
     try {
       while (m_outstandingWriteTasks.get() > 0) {
         m_noMoreOutstandingWriteTasksCondition.await();
       }
     } finally {
       m_outstandingWriteTasksLock.unlock();
     }
     m_syncTask.cancel(false);
     m_channel.force(false);
   } finally {
     m_bytesAllowedBeforeSync.release(m_bytesWrittenSinceLastSync.getAndSet(0));
   }
   m_channel.position(8);
   ByteBuffer completed = ByteBuffer.allocate(1);
   if (m_writeFailed) {
     completed.put((byte) 0).flip();
   } else {
     completed.put((byte) 1).flip();
   }
   m_channel.write(completed);
   m_channel.force(false);
   m_channel.close();
   if (m_onCloseHandler != null) {
     m_onCloseHandler.run();
   }
 }
Exemplo n.º 2
0
  /**
   * Destroys this catalyst instance, waiting for any other threads in CatalystQueueConfiguration
   * (besides the UI thread) to finish running. Must be called from the UI thread so that we can
   * fully shut down other threads.
   */
  /* package */ void destroy() {
    UiThreadUtil.assertOnUiThread();

    if (mDestroyed) {
      return;
    }

    // TODO: tell all APIs to shut down
    mDestroyed = true;
    mJavaRegistry.notifyCatalystInstanceDestroy();
    mCatalystQueueConfiguration.destroy();
    boolean wasIdle = (mPendingJSCalls.getAndSet(0) == 0);
    if (!wasIdle && !mBridgeIdleListeners.isEmpty()) {
      for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) {
        listener.onTransitionToBridgeIdle();
      }
    }

    if (mTraceListener != null) {
      Systrace.unregisterListener(mTraceListener);
    }

    // We can access the Bridge from any thread now because we know either we are on the JS thread
    // or the JS thread has finished via CatalystQueueConfiguration#destroy()
    Assertions.assertNotNull(mBridge).dispose();
  }
Exemplo n.º 3
0
  public void newCharacter(CharacterEvent ce) {
    int oldChar2type;

    // Previous character not typed correctly - 1 point penalty
    if (ce.source == generator.get()) {
      oldChar2type = char2type.getAndSet(ce.character); // 接收随机字母

      if (oldChar2type != -1) {
        score.decrementAndGet();
        setScore();
      }
    }
    // If character is extraneous - 1 point penalty
    // If character does not match - 1 point penalty
    else if (ce.source == typist.get()) {
      // 在此有个假设:即正在使用的该变量值不会被变更且程序代码完成时也是如此
      // 所有已经被我们设定的具有特定值的变量就应当是那个值。
      while (true) {
        oldChar2type = char2type.get(); // 获取上次已接收到的随机字母

        if (oldChar2type != ce.character) { // ce.character是用户输入的字母,现在作比较
          score.decrementAndGet();
          break;
        } else if (char2type.compareAndSet(oldChar2type, -1)) {
          score.incrementAndGet();
          break;
        }
      }

      setScore();
    }
  }
 // Runs on a SECONDARY thread
 @Override
 public void processFrame(android.media.audiofx.Visualizer visualizer, boolean playing) {
   if (!lock.lockLowPriority()) return;
   try {
     if (transmitting) {
       // We use ignoreInput, because sampling 1024, 60 times a seconds,
       // is useless, as there are only 44100 or 48000 samples in one second
       if (ignoreInput == 0) {
         // WE MUST NEVER call any method from visualizer
         // while the player is not actually playing
         if (!playing) Arrays.fill(waveform, 0, 1024, (byte) 0x80);
         else visualizer.getWaveForm(waveform);
       }
       if (framesToSkip <= 0) {
         framesToSkip = framesToSkipOriginal;
         bt.getOutputStream()
             .write(
                 waveform,
                 0,
                 SimpleVisualizerJni.commonProcess(waveform, size | ignoreInput | dataType));
         packetsSent++;
       } else {
         SimpleVisualizerJni.commonProcess(waveform, ignoreInput | dataType);
         framesToSkip--;
       }
       ignoreInput ^= IGNORE_INPUT;
     }
     int stateI = state.getAndSet(0);
     if (stateI != 0) {
       // Build and send a Player state message
       waveform[0] = StartOfHeading;
       waveform[1] = (byte) MessagePlayerState;
       waveform[3] = 0;
       int len = 0;
       len = writeByte(waveform, len, stateI & 3);
       len = writeByte(waveform, len, stateVolume);
       stateI = stateSongPosition;
       len = writeByte(waveform, len, stateI);
       len = writeByte(waveform, len, stateI >> 8);
       len = writeByte(waveform, len, stateI >> 16);
       len = writeByte(waveform, len, stateI >> 24);
       stateI = stateSongLength;
       len = writeByte(waveform, len, stateI);
       len = writeByte(waveform, len, stateI >> 8);
       len = writeByte(waveform, len, stateI >> 16);
       len = writeByte(waveform, len, stateI >> 24);
       waveform[2] = (byte) (len << 1);
       waveform[4 + len] = EndOfTransmission;
       bt.getOutputStream().write(waveform, 0, len + 5);
       packetsSent++;
     }
   } catch (IOException ex) {
     // Bluetooth error
     if (connected) MainHandler.sendMessage(this, MSG_BLUETOOTH_RXTX_ERROR);
   } catch (Throwable ex) {
     ex.printStackTrace();
   } finally {
     lock.releaseLowPriority();
   }
 }
  /**
   * Destroys this catalyst instance, waiting for any other threads in ReactQueueConfiguration
   * (besides the UI thread) to finish running. Must be called from the UI thread so that we can
   * fully shut down other threads.
   */
  @Override
  public void destroy() {
    UiThreadUtil.assertOnUiThread();

    synchronized (mTeardownLock) {
      if (mDestroyed) {
        return;
      }

      // TODO: tell all APIs to shut down
      mDestroyed = true;
      mJavaRegistry.notifyCatalystInstanceDestroy();

      Systrace.unregisterListener(mTraceListener);

      synchronouslyDisposeBridgeOnJSThread();
    }

    mReactQueueConfiguration.destroy();

    boolean wasIdle = (mPendingJSCalls.getAndSet(0) == 0);
    if (!wasIdle && !mBridgeIdleListeners.isEmpty()) {
      for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) {
        listener.onTransitionToBridgeIdle();
      }
    }
  }
Exemplo n.º 6
0
  /**
   * Releases a permit, returning it to the semaphore.
   *
   * <p>Releases a permit, increasing the number of available permits by one. If any threads are
   * trying to acquire a permit, then one is selected and given the permit that was just released.
   * That thread is (re)enabled for thread scheduling purposes.
   *
   * <p>There is no requirement that a thread that releases a permit must have acquired that permit
   * by calling {@link #acquire}. Correct usage of a semaphore is established by programming
   * convention in the application.
   */
  public void release() {
    if (cancel.get() > 0 && count.get() < 0) {
      processCancels(cancel.getAndSet(0));
    }

    if (count.addAndGet(1) <= 0) {
      sem.release();
    }
  }
Exemplo n.º 7
0
  @Override
  public List<DataPointSet> getMetrics(long now) {
    DataPointSet dps = new DataPointSet(REPORTING_METRIC_NAME);
    dps.addTag("host", m_hostName);
    dps.addTag("method", "putm");
    dps.addDataPoint(m_longFactory.createDataPoint(now, m_counter.getAndSet(0)));

    return (Collections.singletonList(dps));
  }
  @Override
  public final void run() {
    String oldName = null;

    try {
      _thread = Thread.currentThread();
      _thread.setContextClassLoader(_classLoader);
      oldName = _thread.getName();
      _thread.setName(getThreadName());

      onThreadStart();

      long now = getCurrentTimeActual();

      long expires = now + _workerIdleTimeout;

      do {
        while (_taskState.getAndSet(TASK_SLEEP) == TASK_READY) {
          _thread.setContextClassLoader(_classLoader);

          long delta = runTask();

          now = getCurrentTimeActual();

          if (delta < 0) {
            expires = now + _workerIdleTimeout;
          } else {
            expires = now + delta;
          }
        }

        if (isClosed()) return;

        if (_taskState.compareAndSet(TASK_SLEEP, TASK_PARK)) {
          Thread.interrupted();
          LockSupport.parkUntil(expires);

          if (isPermanent()) _taskState.set(TASK_READY);
        }
      } while (_taskState.get() == TASK_READY || isPermanent() || getCurrentTimeActual() < expires);
    } catch (Throwable e) {
      WarningService.sendCurrentWarning(this, e);
      log.log(Level.WARNING, e.toString(), e);
    } finally {
      Thread thread = _thread;
      _thread = null;

      _isActive.set(false);

      if (_taskState.get() == TASK_READY) wake();

      onThreadComplete();

      if (thread != null && oldName != null) thread.setName(oldName);
    }
  }
Exemplo n.º 9
0
    public boolean updatePriorityLevel() {
      int newPriority = calculatePriorityLevel(taskHandle.getThreadUsageNanos());
      if (newPriority == priorityLevel.getAndSet(newPriority)) {
        return false;
      }

      // update thread usage while if level changed
      threadUsageNanos.set(taskHandle.getThreadUsageNanos());
      return true;
    }
Exemplo n.º 10
0
 public void setEnabled(boolean enabled) {
   mEnabled = enabled;
   if (!mEnabled) {
     int count = mCount.getAndSet(0);
     if (count > 0) {
       LogUtils.e(LOG_TAG, "Disable UiHandler. Dropping %d Runnables.", count);
     }
     mHandler.removeCallbacksAndMessages(null);
   }
 }
Exemplo n.º 11
0
 public Object getState() {
   LOG.debug("Getting metrics for server on port {}", port);
   HashMap<String, Object> ret = new HashMap<>();
   ret.put("dequeuedMessages", messagesDequeued.getAndSet(0));
   HashMap<String, Integer> enqueued = new HashMap<String, Integer>();
   Iterator<Map.Entry<String, AtomicInteger>> it = messagesEnqueued.entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry<String, AtomicInteger> ent = it.next();
     // Yes we can delete something that is not 0 because of races, but that is OK for metrics
     AtomicInteger i = ent.getValue();
     if (i.get() == 0) {
       it.remove();
     } else {
       enqueued.put(ent.getKey(), i.getAndSet(0));
     }
   }
   ret.put("enqueued", enqueued);
   return ret;
 }
 public void setEnabled(boolean paramBoolean) {
   mEnabled = paramBoolean;
   if (!mEnabled) {
     int i = mCount.getAndSet(0);
     if (i > 0) {
       LogUtils.e(
           "Gmail",
           "Disable UiHandler. Dropping %d Runnables.",
           new Object[] {Integer.valueOf(i)});
     }
     mHandler.removeCallbacksAndMessages(null);
   }
 }
Exemplo n.º 13
0
    /**
     * Callback invoked when there is any change to any SubscriptionInfo. Typically this method
     * would invoke {@link SubscriptionManager#getActiveSubscriptionInfoList}
     */
    @Override
    public void onSubscriptionsChanged() {
      if (DBG) log("SubscriptionListener.onSubscriptionInfoChanged");
      // Set the network type, in case the radio does not restore it.
      int subId = mPhoneBase.getSubId();
      if (mPreviousSubId.getAndSet(subId) != subId) {
        if (SubscriptionManager.isValidSubscriptionId(subId)) {
          Context context = mPhoneBase.getContext();
          int networkType = PhoneFactory.calculatePreferredNetworkType(context, subId);
          mCi.setPreferredNetworkType(networkType, null);

          mPhoneBase.notifyCallForwardingIndicator();

          boolean skipRestoringSelection =
              context
                  .getResources()
                  .getBoolean(com.android.internal.R.bool.skip_restoring_network_selection);
          if (!skipRestoringSelection) {
            // restore the previous network selection.
            mPhoneBase.restoreSavedNetworkSelection(null);
          }

          mPhoneBase.setSystemProperty(
              TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
              ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology()));

          if (mSpnUpdatePending) {
            mSubscriptionController.setPlmnSpn(
                mPhoneBase.getPhoneId(), mCurShowPlmn, mCurPlmn, mCurShowSpn, mCurSpn);
            mSpnUpdatePending = false;
          }

          // Remove old network selection sharedPreferences since SP key names are now
          // changed to include subId. This will be done only once when upgrading from an
          // older build that did not include subId in the names.
          SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
          String oldNetworkSelectionName = sp.getString(PhoneBase.NETWORK_SELECTION_NAME_KEY, "");
          String oldNetworkSelection = sp.getString(PhoneBase.NETWORK_SELECTION_KEY, "");
          if (!TextUtils.isEmpty(oldNetworkSelectionName)
              || !TextUtils.isEmpty(oldNetworkSelection)) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(PhoneBase.NETWORK_SELECTION_NAME_KEY + subId, oldNetworkSelectionName);
            editor.putString(PhoneBase.NETWORK_SELECTION_KEY + subId, oldNetworkSelection);
            editor.remove(PhoneBase.NETWORK_SELECTION_NAME_KEY);
            editor.remove(PhoneBase.NETWORK_SELECTION_KEY);
            editor.commit();
          }
        }
      }
    }
Exemplo n.º 14
0
  public final void wake() {
    int oldState = _taskState.getAndSet(TASK_READY);

    if (!_isActive.getAndSet(true)) {
      startWorkerThread();
    }

    if (oldState == TASK_PARK) {
      Thread thread = _thread;

      if (thread != null) {
        LockSupport.unpark(thread);
      }
    }
  }
 /**
  * Called when we have cancelled a scheduled timer task. Do work, if possible to fix bug 37574.
  */
 public void incCancels() {
   int pc = pendingCancels.incrementAndGet();
   if (pc > MAX_PENDING_CANCELS) {
     pc = pendingCancels.getAndSet(0);
     if (pc > MAX_PENDING_CANCELS) {
       this.timer.timerPurge();
       //        int purgedCancels = CFactory.timerPurge(this.timer);
       // we could try to do some fancy stuff here but the value
       // of the atomic is just a hint so don't bother adjusting it
       //         // take the diff between the number of actual cancels we purged
       //         // "purgedCancels" and the number we said we would purge "pc".
       //         int diff = purgedCancels - pc;
     } else {
       // some other thread beat us to it so add back in the cancels
       // we just removed by setting it to 0
       pendingCancels.addAndGet(pc);
     }
   }
 }
Exemplo n.º 16
0
 @Override
 public boolean resetDirtyArrays() {
   return dirtyBlocks.getAndSet(0) > 0;
 }
 /**
  * Attempts to write lock the lock.
  *
  * @return the old sequence number, or OptimisticReadWriteLock.UNSTABLE on fail
  */
 public int tryWriteLock() {
   return sequence.getAndSet(UNSTABLE);
 }
Exemplo n.º 18
0
 @Override
 public void onError(Throwable e) {
   if (counter.getAndSet(num) < num) {
     observer.onError(e);
   }
 }
Exemplo n.º 19
0
 public void reset() {
   counter.getAndSet(0);
   messages = new LinkedList<MessageData>();
 }
  @Test(timeout = 5000L)
  public void testCacheLoaderAsyncLoadAll() throws InterruptedException {
    final AtomicInteger loads = new AtomicInteger();

    final CacheLoader<String, Integer> cacheLoader =
        new CacheLoader<String, Integer>() {
          @Override
          public Integer load(String key) throws CacheLoaderException {
            loads.incrementAndGet();

            return Integer.valueOf(key);
          }

          @Override
          public Map<String, Integer> loadAll(Iterable<? extends String> keys)
              throws CacheLoaderException {
            throw new UnsupportedOperationException("Not supported yet.");
          }
        };

    final AtomicBoolean completed = new AtomicBoolean(false);

    final CompletionListener completionListener =
        new CompletionListener() {
          @Override
          public void onCompletion() {
            completed.set(true);
          }

          @Override
          public void onException(Exception e) {
            System.err.println(e);
          }
        };

    try (CachingProvider cachingProvider =
        Caching.getCachingProvider(GuavaCachingProvider.class.getName())) {
      CacheManager cacheManager = cachingProvider.getCacheManager();

      MutableConfiguration<String, Integer> custom = new MutableConfiguration<>();

      custom.setStoreByValue(false);
      custom.setTypes(String.class, Integer.class);
      custom.setReadThrough(true);
      custom.setCacheLoaderFactory(
          new Factory<CacheLoader<String, Integer>>() {
            @Override
            public CacheLoader<String, Integer> create() {
              return cacheLoader;
            }
          });

      Cache<String, Integer> loadingCache = cacheManager.createCache("loadingCache", custom);

      loadingCache.put("1", 1);
      loadingCache.put("2", 2);
      loadingCache.put("3", 3);

      Set<String> keys = Sets.newHashSet("1", "2", "3", "4", "5", "6");

      loadingCache.loadAll(keys, false, completionListener);

      while (!completed.get()) {
        Thread.sleep(250);
      }

      assertEquals(3, loads.getAndSet(0));

      completed.set(false);

      loadingCache.loadAll(keys, true, completionListener);

      while (!completed.get()) {
        Thread.sleep(250);
      }

      assertEquals(6, loads.get());
      assertEquals(Integer.valueOf(1), loadingCache.getAndRemove("1"));
      assertEquals(Integer.valueOf(2), loadingCache.getAndRemove("2"));
      assertEquals(Integer.valueOf(3), loadingCache.getAndRemove("3"));
      assertEquals(Integer.valueOf(4), loadingCache.getAndRemove("4"));
      assertEquals(Integer.valueOf(5), loadingCache.getAndRemove("5"));
      assertEquals(Integer.valueOf(6), loadingCache.getAndRemove("6"));
    }
  }
Exemplo n.º 21
0
 public static final int getWriteOps() {
   return writeOps.getAndSet(0);
 }
Exemplo n.º 22
0
 // number of positional reads
 public static final int getPreadOps() {
   return preadOps.getAndSet(0);
 }
Exemplo n.º 23
0
 /**
  * Set this reduction variable to the given value and return the previous value.
  *
  * @param value New value.
  * @return Previous value.
  */
 public int getAndSet(int value) {
   return myValue.getAndSet(value);
 }
 public void forcePurge() {
   pendingCancels.getAndSet(0);
   this.timer.timerPurge();
 }
Exemplo n.º 25
0
 /** 1. 重新设置AtomicInteger中维护的int值, 并将原先的值返回。 */
 public void testGetAndSet() {
   AtomicInteger ai = new AtomicInteger();
   System.out.println(ai.getAndSet(10)); // 0
 }
Exemplo n.º 26
0
 /** getAndSet returns previous value and sets to given value */
 public void testGetAndSet() {
   AtomicInteger ai = new AtomicInteger(1);
   assertEquals(1, ai.getAndSet(0));
   assertEquals(0, ai.getAndSet(-10));
   assertEquals(-10, ai.getAndSet(1));
 }
Exemplo n.º 27
0
 @Override
 public void onCompleted() {
   if (counter.getAndSet(num) < num) {
     observer.onCompleted();
   }
 }