@Override
 public void run() {
   try {
     String threadName = Thread.currentThread().getName();
     lock1.lock();
     try {
       System.out.println(threadName + " has lock1");
       lock2.lock();
       try {
         System.out.println(threadName + " has lock2");
         lock1.lock();
         try {
           System.out.println(threadName + " reenters lock1");
           condition.await(1, TimeUnit.SECONDS);
         } finally {
           lock1.unlock();
         }
       } finally {
         lock2.unlock();
       }
     } finally {
       lock1.unlock();
     }
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 2
0
  public int StartCapture(int width, int height, int frameRate) {
    Log.d(TAG, "StartCapture width " + width + " height " + height + " frame rate " + frameRate);
    // Get the local preview SurfaceHolder from the static render class
    localPreview = ViERenderer.GetLocalRenderer();
    if (localPreview != null) {
      if (localPreview.getSurface() != null && localPreview.getSurface().isValid()) {
        surfaceCreated(localPreview);
      }
      localPreview.addCallback(this);
    } else {
      // No local renderer.  Camera won't capture without
      // setPreview{Texture,Display}, so we create a dummy SurfaceTexture
      // and hand it over to Camera, but never listen for frame-ready
      // callbacks, and never call updateTexImage on it.
      captureLock.lock();
      try {
        dummySurfaceTexture = new SurfaceTexture(42);
        camera.setPreviewTexture(dummySurfaceTexture);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      captureLock.unlock();
    }

    captureLock.lock();
    isCaptureStarted = true;
    mCaptureWidth = width;
    mCaptureHeight = height;
    mCaptureFPS = frameRate;

    int res = tryStartCapture(mCaptureWidth, mCaptureHeight, mCaptureFPS);

    captureLock.unlock();
    return res;
  }
  /**
   * Called after media player has been prepared. This method is executed on the caller's thread.
   */
  void onPrepared(final boolean startWhenPrepared) {
    playerLock.lock();

    if (playerStatus != PlayerStatus.PREPARING) {
      playerLock.unlock();
      throw new IllegalStateException("Player is not in PREPARING state");
    }

    if (BuildConfig.DEBUG) Log.d(TAG, "Resource prepared");

    if (mediaType == MediaType.VIDEO) {
      VideoPlayer vp = (VideoPlayer) mediaPlayer;
      videoSize = new Pair<Integer, Integer>(vp.getVideoWidth(), vp.getVideoHeight());
    }

    if (media.getPosition() > 0) {
      mediaPlayer.seekTo(media.getPosition());
    }

    if (media.getDuration() == 0) {
      if (BuildConfig.DEBUG) Log.d(TAG, "Setting duration of media");
      media.setDuration(mediaPlayer.getDuration());
    }
    setPlayerStatus(PlayerStatus.PREPARED, media);

    if (startWhenPrepared) {
      resumeSync();
    }

    playerLock.unlock();
  }
Ejemplo n.º 4
0
  /** closeFile Close the current file, but keep its path so we can easily open it again. */
  public void closeFile() throws NexusException {
    try {
      if (m_nfFile != null) {
        m_nfFile.close();
        m_nfFile.finalize();
      }
      m_nfFile = null;

    } catch (Throwable t) {
      if (g_mutex.isLocked() && g_curFile.equals(m_sFilePath)) {
        if (g_mutex.getHoldCount() - 1 == 0) {
          g_curFile = "";
        }
        g_mutex.unlock();
      }
      if (t instanceof NexusException) {
        throw (NexusException) t;
      } else {
        t.printStackTrace();
        return;
      }
    }
    if (g_mutex.isLocked() && g_curFile.equals(m_sFilePath)) {
      if (g_mutex.getHoldCount() - 1 == 0) {
        g_curFile = "";
      }

      g_mutex.unlock();
    }
  }
  /** Moves the movie to the requested seek position */
  public boolean seekTo(int position) {
    if (!isPlayableOnTexture()) {
      // DebugLog.LOGD("Cannot seek-to on this video since it is not on texture");
      return false;
    }

    if ((mCurrentState == MEDIA_STATE.NOT_READY) || (mCurrentState == MEDIA_STATE.ERROR)) {
      // DebugLog.LOGD("Cannot seek-to on this video if it is not ready");
      return false;
    }

    boolean result = false;
    mMediaPlayerLock.lock();
    if (mMediaPlayer != null) {
      try {
        mMediaPlayer.seekTo(position);
      } catch (Exception e) {
        mMediaPlayerLock.unlock();
        DebugLog.LOGE("Could not seek to position");
      }
      result = true;
    }
    mMediaPlayerLock.unlock();

    return result;
  }
  /** Pauses the current movie being played */
  public boolean pause() {
    if (!isPlayableOnTexture()) {
      // DebugLog.LOGD("Cannot pause this video since it is not on texture");
      return false;
    }

    if ((mCurrentState == MEDIA_STATE.NOT_READY) || (mCurrentState == MEDIA_STATE.ERROR)) {
      // DebugLog.LOGD("Cannot pause this video if it is not ready");
      return false;
    }

    boolean result = false;

    mMediaPlayerLock.lock();
    if (mMediaPlayer != null) {
      if (mMediaPlayer.isPlaying()) {
        try {
          mMediaPlayer.pause();
        } catch (Exception e) {
          mMediaPlayerLock.unlock();
          DebugLog.LOGE("Could not pause playback");
        }
        mCurrentState = MEDIA_STATE.PAUSED;
        result = true;
      }
    }
    mMediaPlayerLock.unlock();

    return result;
  }
Ejemplo n.º 7
0
  @Override
  public void writeBytes(byte[] message) throws IOException {
    lock.lock();
    try {
      // Network buffers are not unlimited (and are often smaller than some messages we may wish to
      // send), and
      // thus we have to buffer outbound messages sometimes. To do this, we use a queue of
      // ByteBuffers and just
      // append to it when we want to send a message. We then let tryWriteBytes() either send the
      // message or
      // register our SelectionKey to wakeup when we have free outbound buffer space available.

      if (bytesToWriteRemaining + message.length > OUTBOUND_BUFFER_BYTE_COUNT)
        throw new IOException("Outbound buffer overflowed");
      // Just dump the message onto the write buffer and call tryWriteBytes
      // TODO: Kill the needless message duplication when the write completes right away
      bytesToWrite.offer(ByteBuffer.wrap(Arrays.copyOf(message, message.length)));
      bytesToWriteRemaining += message.length;
      setWriteOps();
    } catch (IOException e) {
      lock.unlock();
      log.error("Error writing message to connection, closing connection", e);
      closeConnection();
      throw e;
    } catch (CancelledKeyException e) {
      lock.unlock();
      log.error("Error writing message to connection, closing connection", e);
      closeConnection();
      throw new IOException(e);
    }
    lock.unlock();
  }
Ejemplo n.º 8
0
 public Object get(int i)
 {
     Object obj;
     if (entities == null)
     {
         break MISSING_BLOCK_LABEL_111;
     }
     obj = entities.get(i);
     if (obj != null)
     {
         break MISSING_BLOCK_LABEL_99;
     }
     lock.lock();
     obj = entities.get(i);
     if (obj != null)
     {
         break MISSING_BLOCK_LABEL_92;
     }
     obj = loadEntity(i);
     entities.set(i, obj);
     loadedCount = 1 + loadedCount;
     if (loadedCount == size)
     {
         cursor.close();
     }
     lock.unlock();
     return obj;
     Exception exception;
     exception;
     lock.unlock();
     throw exception;
     return loadEntity(i);
 }
Ejemplo n.º 9
0
  @Override
  public void fetchSucceeded(
      String host,
      InputAttemptIdentifier srcAttemptIdentifier,
      FetchedInput fetchedInput,
      long fetchedBytes,
      long decompressedLength,
      long copyDuration)
      throws IOException {
    InputIdentifier inputIdentifier = srcAttemptIdentifier.getInputIdentifier();

    LOG.info(
        "Completed fetch for attempt: " + srcAttemptIdentifier + " to " + fetchedInput.getType());

    // Count irrespective of whether this is a copy of an already fetched input
    lock.lock();
    try {
      lastProgressTime = System.currentTimeMillis();
    } finally {
      lock.unlock();
    }

    boolean committed = false;
    if (!completedInputSet.contains(inputIdentifier)) {
      synchronized (completedInputSet) {
        if (!completedInputSet.contains(inputIdentifier)) {
          fetchedInput.commit();
          committed = true;

          // Processing counters for completed and commit fetches only. Need
          // additional counters for excessive fetches - which primarily comes
          // in after speculation or retries.
          shuffledInputsCounter.increment(1);
          bytesShuffledCounter.increment(fetchedBytes);
          if (fetchedInput.getType() == Type.MEMORY) {
            bytesShuffledToMemCounter.increment(fetchedBytes);
          } else {
            bytesShuffledToDiskCounter.increment(fetchedBytes);
          }
          decompressedDataSizeCounter.increment(decompressedLength);

          registerCompletedInput(fetchedInput);
        }
      }
    }
    if (!committed) {
      fetchedInput.abort(); // If this fails, the fetcher may attempt another abort.
    } else {
      lock.lock();
      try {
        // Signal the wakeLoop to check for termination.
        wakeLoop.signal();
      } finally {
        lock.unlock();
      }
    }
    // TODO NEWTEZ Maybe inform fetchers, in case they have an alternate attempt of the same task in
    // their queue.
  }
Ejemplo n.º 10
0
  @Override
  public byte[] get(byte[] key, ReadOptions options) throws DBException {
    checkBackgroundException();
    LookupKey lookupKey;
    mutex.lock();
    try {
      SnapshotImpl snapshot = getSnapshot(options);
      lookupKey = new LookupKey(Slices.wrappedBuffer(key), snapshot.getLastSequence());

      // First look in the memtable, then in the immutable memtable (if any).
      LookupResult lookupResult = memTable.get(lookupKey);
      if (lookupResult != null) {
        Slice value = lookupResult.getValue();
        if (value == null) {
          return null;
        }
        return value.getBytes();
      }
      if (immutableMemTable != null) {
        lookupResult = immutableMemTable.get(lookupKey);
        if (lookupResult != null) {
          Slice value = lookupResult.getValue();
          if (value == null) {
            return null;
          }
          return value.getBytes();
        }
      }
    } finally {
      mutex.unlock();
    }

    // Not in memTables; try live files in level order
    LookupResult lookupResult = versions.get(lookupKey);

    // schedule compaction if necessary
    mutex.lock();
    try {
      if (versions.needsCompaction()) {
        maybeScheduleCompaction();
      }
    } finally {
      mutex.unlock();
    }

    if (lookupResult != null) {
      Slice value = lookupResult.getValue();
      if (value != null) {
        return value.getBytes();
      }
    }
    return null;
  }
Ejemplo n.º 11
0
	/** Replies the accent's translation table.
	 * <p>
	 * This method read the translations from the
	 * resource file <code>ACCENT_TRANS_TBL</code>.
	 * 
	 *  @return the translation table or <code>null</code> if none was found.
	 */
	public static Map<Character,String> getAccentTranslationTable() {
		Map<Character,String> map = null;
		try {
			lock.lock();
			if (accentTransTbl!=null)
				map = accentTransTbl.get();
		}
		finally {
			lock.unlock();
		}
		
		if (map!=null) return map;
		
        // Get the resource file
        ResourceBundle resource = null;
        try {
            resource = ResourceBundle.getBundle(
            		TextUtil.class.getCanonicalName(),
            		java.util.Locale.getDefault());
        }
        catch (MissingResourceException exep) {
            return null;
        }
        
        // get the resource string
        String result;
        
        try {
            result = resource.getString("ACCENT_TRANS_TBL"); //$NON-NLS-1$
        }
        catch (Exception e) {
            return null;
        }
        
        map = new TreeMap<Character,String>();
        
        String[] pairs = result.split("(\\}\\{)|\\{|\\}"); //$NON-NLS-1$
        for (String pair : pairs) {
        	if (pair.length()>1) {
        		map.put(pair.charAt(0),pair.substring(1));
        	}
		}
        
		try {
			lock.lock();
			accentTransTbl = new SoftReference<Map<Character,String>>(map);
		}
		finally {
			lock.unlock();
		}

		return map;
	}
Ejemplo n.º 12
0
 /**
  * Remove the dot near the given position.
  *
  * @param pitch
  * @param yaw
  */
 private boolean removeMarker(float pitch, float yaw) {
   final float TRESHOLD = 10.0f;
   Snapshot o = new Snapshot(pitch, yaw);
   mTargetsLock.lock();
   for (Snapshot3D dot : mDots) {
     if (o.getDistance(dot) < TRESHOLD) {
       mDots.remove(dot);
       mTargetsLock.unlock();
       return true;
     }
   }
   mTargetsLock.unlock();
   return false;
 }
  public void clear() {
    putLock.lock();
    takeLock.lock();

    try {
      head.next = null;
      assert head.item == null;
      last = head;
      count.set(0);
    } finally {
      takeLock.unlock();
      putLock.unlock();
    }
  }
 /**
  * deprecated: 对保存seesion信息的map操作
  *
  * <p>2015-03-20
  *
  * @author sharkTang
  * @param webSocketMap : socket对象集合
  * @param session : javax.websocket.Session
  * @param actionString : action
  */
 public static void webSocketMapAction(
     Map<Integer, Session> webSessionMap, Session session, String actionString) {
   try {
     lock.lock();
     if (WebSocketConstants.ADD_STR.equals(actionString)) {
       webSessionMap.put(session.hashCode(), session);
     } else if (WebSocketConstants.REMOVE_STR.equals(actionString)) {
       webSessionMap.remove(session.hashCode());
     }
   } catch (Exception e) {
     lock.unlock();
   } finally {
     lock.unlock();
   }
 }
  public E poll() {
    final AtomicInteger count = this.count;
    if (count.get() == 0) return null;

    Node<E> x = null;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();

    try {
      if (count.get() > 0) {
        x = extract();
        if (count.getAndDecrement() > 1) notEmpty.signal();
      }
    } finally {
      takeLock.unlock();
    }

    if (x != null) {
      E result = x.item;

      // temporary clearence
      x.item = null;
      x.next = null;

      return result;
    }

    return null;
  }
  public E take() throws InterruptedException {
    Node<E> x;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
      try {
        while (count.get() == 0) notEmpty.await();
      } catch (InterruptedException ie) {
        notEmpty.signal(); // propagate to a non-interrupted thread
        throw ie;
      }

      x = extract();
      if (count.getAndDecrement() > 1) notEmpty.signal();
    } finally {
      takeLock.unlock();
    }

    E result = x.item;

    // temporary clearence
    x.item = null;
    x.next = null;

    return result;
  }
Ejemplo n.º 17
0
  private void updateOnAdjustment() {

    if (!locked) {

      mutex.lock();
      try {
        // see if something new was added or the window resized
        if (model.getMaximum() != vertScrollPrevMax || model.getExtent() != vertScrollPrevExtent) {
          // Yup ...

          // See if prev version was maxed
          if (vertScrollPrevValue + vertScrollPrevExtent >= vertScrollPrevMax) {
            // Yup ...

            setValue(Integer.MAX_VALUE);
          }
        } // if (model.getMaximum()

        vertScrollPrevMax = model.getMaximum();
        vertScrollPrevExtent = model.getExtent();
        vertScrollPrevValue = model.getValue();
      } finally {
        mutex.unlock();
      }
    }
  }
Ejemplo n.º 18
0
 private synchronized void load(
     final K key, final boolean synchronizeAccess, final boolean lockAccess) {
   ReentrantLock lock = null;
   try {
     synchronized (this) {
       if (lockAccess) {
         lock = lock(key);
       }
     }
     if (synchronizeAccess) {
       put(key, cacheLoader.get(key));
     } else {
       executorService.submit(
           new Callable<Object>() {
             public Object call() throws Exception {
               load(key, true, true);
               return null;
             }
           });
     }
   } finally {
     if (lock != null) {
       lock.unlock();
     }
   }
 }
Ejemplo n.º 19
0
  public final boolean isEmptyWriteSet() {

    if (readOnly) return true;

    lock.lock();

    try {

      final Iterator<ILocalBTreeView> itr = indices.values().iterator();

      while (itr.hasNext()) {

        final IsolatedFusedView ndx = (IsolatedFusedView) itr.next();

        if (!ndx.isEmptyWriteSet()) {

          // At least one isolated index was written on.

          return false;
        }
      }

      return true;

    } finally {

      lock.unlock();
    }
  }
Ejemplo n.º 20
0
  /** {@inheritDoc} */
  @Override
  public int next(int bits) {
    int result;
    try {
      lock.lock();
      // Set cell addresses using address of current cell.
      int cellC = currentCellIndex - 1;
      int cellB = cellC - 1;
      int cellA = cellB - 1;

      // Update cell states using rule table.
      cells[currentCellIndex] = RNG_RULE[cells[cellC] + cells[currentCellIndex]];
      cells[cellC] = RNG_RULE[cells[cellB] + cells[cellC]];
      cells[cellB] = RNG_RULE[cells[cellA] + cells[cellB]];

      // Update the state of cellA and shift current cell to the left by 4 bytes.
      if (cellA == 0) {
        cells[cellA] = RNG_RULE[cells[cellA]];
        currentCellIndex = AUTOMATON_LENGTH - 1;
      } else {
        cells[cellA] = RNG_RULE[cells[cellA - 1] + cells[cellA]];
        currentCellIndex -= 4;
      }
      result = convertCellsToInt(cells, cellA);
    } finally {
      lock.unlock();
    }
    return result >>> (32 - bits);
  }
  @Override
  public void save(NotificationInfo message) throws Exception {
    boolean created = NotificationSessionManager.createSystemProvider();
    SessionProvider sProvider = NotificationSessionManager.getSessionProvider();
    final ReentrantLock localLock = lock;
    try {
      localLock.lock();
      Node messageHomeNode =
          getOrCreateMessageParent(sProvider, workspace, message.getKey().getId());
      Node messageNode = messageHomeNode.addNode(message.getId(), NTF_MESSAGE);
      messageNode.setProperty(NTF_FROM, message.getFrom());
      messageNode.setProperty(NTF_ORDER, message.getOrder());
      messageNode.setProperty(NTF_PROVIDER_TYPE, message.getKey().getId());
      messageNode.setProperty(NTF_OWNER_PARAMETER, message.getArrayOwnerParameter());
      messageNode.setProperty(NTF_SEND_TO_DAILY, message.getSendToDaily());
      messageNode.setProperty(NTF_SEND_TO_WEEKLY, message.getSendToWeekly());
      messageHomeNode.getSession().save();

      // record statistics insert entity
      if (NotificationContextFactory.getInstance().getStatistics().isStatisticsEnabled()) {
        NotificationContextFactory.getInstance().getStatisticsCollector().insertEntity(NTF_MESSAGE);
      }

    } catch (Exception e) {
      LOG.error("Failed to save the NotificationMessage", e);
    } finally {
      NotificationSessionManager.closeSessionProvider(created);
      localLock.unlock();
    }
  }
Ejemplo n.º 22
0
  public void newCheckpoint(byte[] state, byte[] stateHash, int consensusId) {
    String ckpPath = DEFAULT_DIR + String.valueOf(id) + "." + System.currentTimeMillis() + ".tmp";
    try {
      checkpointLock.lock();
      RandomAccessFile ckp = new RandomAccessFile(ckpPath, (syncCkp ? "rwd" : "rw"));

      ByteBuffer bf = ByteBuffer.allocate(state.length + stateHash.length + 4 * INT_BYTE_SIZE);
      bf.putInt(state.length);
      bf.put(state);
      bf.putInt(stateHash.length);
      bf.put(stateHash);
      bf.putInt(EOF);
      bf.putInt(consensusId);

      byte[] ckpState = bf.array();

      ckp.write(ckpState);
      ckp.close();

      if (isToLog) deleteLogFile();
      deleteLastCkp();
      renameCkp(ckpPath);
      if (isToLog) createLogFile();

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      checkpointLock.unlock();
    }
  }
Ejemplo n.º 23
0
  private void backgroundCall() throws IOException {
    mutex.lock();
    try {
      if (backgroundCompaction == null) {
        return;
      }

      try {
        if (!shuttingDown.get()) {
          backgroundCompaction();
        }
      } finally {
        backgroundCompaction = null;
      }
    } finally {
      try {
        // Previous compaction may have produced too many files in a level,
        // so reschedule another compaction if needed.
        maybeScheduleCompaction();
      } finally {
        try {
          backgroundCondition.signalAll();
        } finally {
          mutex.unlock();
        }
      }
    }
  }
Ejemplo n.º 24
0
  public void close() {
    if (shuttingDown.getAndSet(true)) {
      return;
    }

    mutex.lock();
    try {
      while (backgroundCompaction != null) {
        backgroundCondition.awaitUninterruptibly();
      }
    } finally {
      mutex.unlock();
    }

    compactionExecutor.shutdown();
    try {
      compactionExecutor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
    try {
      versions.destroy();
    } catch (IOException ignored) {
    }
    try {
      log.close();
    } catch (IOException ignored) {
    }
    tableCache.close();
    dbLock.release();
  }
Ejemplo n.º 25
0
  @Override
  public void register(final ExtensionBuilder builder) {
    if (ArquillianUtil.isCurrentAdapter(ADAPTER)) {

      final ReentrantLock l = lock;
      l.lock();

      try {

        if (!registered.getAndSet(true)) {

          try {
            builder.observer(DeploymentExceptionObserver.class);
            builder.observer(RemoteInitialContextObserver.class);

            builder
                .service(DeployableContainer.class, TomEEWebappContainer.class)
                .service(
                    AuxiliaryArchiveAppender.class, TomEEWebappEJBEnricherArchiveAppender.class)
                .service(ResourceProvider.class, DeploymentExceptionProvider.class);
          } catch (IllegalArgumentException e) {
            Logger.getLogger(TomEEWebappExtension.class.getName())
                .log(Level.WARNING, "TomEEWebappExtension: " + e.getMessage());
          }
        }
      } finally {
        l.unlock();
      }
    }
  }
Ejemplo n.º 26
0
  private void writeLevel0Table(MemTable mem, VersionEdit edit, Version base) throws IOException {
    Preconditions.checkState(mutex.isHeldByCurrentThread());

    // skip empty mem table
    if (mem.isEmpty()) {
      return;
    }

    // write the memtable to a new sstable
    long fileNumber = versions.getNextFileNumber();
    pendingOutputs.add(fileNumber);
    mutex.unlock();
    FileMetaData meta;
    try {
      meta = buildTable(mem, fileNumber);
    } finally {
      mutex.lock();
    }
    pendingOutputs.remove(fileNumber);

    // Note that if file size is zero, the file has been deleted and
    // should not be added to the manifest.
    int level = 0;
    if (meta != null && meta.getFileSize() > 0) {
      Slice minUserKey = meta.getSmallest().getUserKey();
      Slice maxUserKey = meta.getLargest().getUserKey();
      if (base != null) {
        level = base.pickLevelForMemTableOutput(minUserKey, maxUserKey);
      }
      edit.addFile(level, meta);
    }
  }
Ejemplo n.º 27
0
 public void addKnownInput(
     String hostName,
     int port,
     InputAttemptIdentifier srcAttemptIdentifier,
     int srcPhysicalIndex) {
   String identifier = InputHost.createIdentifier(hostName, port);
   InputHost host = knownSrcHosts.get(identifier);
   if (host == null) {
     host = new InputHost(hostName, port, inputContext.getApplicationId(), srcPhysicalIndex);
     assert identifier.equals(host.getIdentifier());
     InputHost old = knownSrcHosts.putIfAbsent(identifier, host);
     if (old != null) {
       host = old;
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Adding input: " + srcAttemptIdentifier + ", to host: " + host);
   }
   host.addKnownInput(srcAttemptIdentifier);
   lock.lock();
   try {
     boolean added = pendingHosts.offer(host);
     if (!added) {
       String errorMessage = "Unable to add host: " + host.getIdentifier() + " to pending queue";
       LOG.error(errorMessage);
       throw new TezUncheckedException(errorMessage);
     }
     wakeLoop.signal();
   } finally {
     lock.unlock();
   }
 }
Ejemplo n.º 28
0
  public CacheItem put(final String url, final Object obj, DateTime expiresAt) {

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

    Timber.d(String.format("put(%s)", url));
    CacheItem d = new CacheItem(obj, expiresAt);

    if (null != mMemoryCache) {
      mMemoryCache.put(url, d);
    }

    if (null != mDiskCache) {
      checkNotOnMainThread();

      final String key = transformUrlForDiskCacheKey(url);
      final ReentrantLock lock = getLockForDiskCacheEdit(key);
      lock.lock();
      try {
        DiskLruCache.Editor editor = mDiskCache.edit(key);
        writeValueToDisk(editor.newOutputStream(0), obj);
        writeExpirationToDisk(editor.newOutputStream(1), expiresAt);
        editor.commit();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
        scheduleDiskCacheFlush();
      }
    }

    return d;
  }
Ejemplo n.º 29
0
  public void shutdown() throws InterruptedException {
    if (!isShutdown.getAndSet(true)) {
      // Shut down any pending fetchers
      LOG.info(
          "Shutting down pending fetchers on source"
              + srcNameTrimmed
              + ": "
              + runningFetchers.size());
      lock.lock();
      try {
        wakeLoop.signal(); // signal the fetch-scheduler
        for (Fetcher fetcher : runningFetchers) {
          fetcher.shutdown(); // This could be parallelized.
        }
      } finally {
        lock.unlock();
      }

      if (this.schedulerExecutor != null && !this.schedulerExecutor.isShutdown()) {
        this.schedulerExecutor.shutdownNow();
      }
      if (this.fetcherExecutor != null && !this.fetcherExecutor.isShutdown()) {
        this.fetcherExecutor.shutdownNow(); // Interrupts all running fetchers.
      }
    }
    // All threads are shutdown.  It is safe to shutdown SSL factory
    if (httpConnectionParams.isSSLShuffleEnabled()) {
      HttpConnection.cleanupSSLFactory();
    }
  }
Ejemplo n.º 30
0
 public void DeRegisterNativeObject() {
   nativeFunctionLock.lock();
   nativeFunctionsRegisted = false;
   openGLCreated = false;
   this.nativeObject = 0;
   nativeFunctionLock.unlock();
 }