com.facebook.common.references.CloseableReference Java Examples

The following examples show how to use com.facebook.common.references.CloseableReference. 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: ImagePipeline.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Returns a DataSource supplier that will on get submit the request for execution and return a
 * DataSource representing the pending results of the task.
 *
 * @param imageRequest the request to submit (what to execute).
 * @return a DataSource representing pending results and completion of the request
 */
public Supplier<DataSource<CloseableReference<PooledByteBuffer>>>
    getEncodedImageDataSourceSupplier(
        final ImageRequest imageRequest, final Object callerContext) {
  return new Supplier<DataSource<CloseableReference<PooledByteBuffer>>>() {
    @Override
    public DataSource<CloseableReference<PooledByteBuffer>> get() {
      return fetchEncodedImage(imageRequest, callerContext);
    }

    @Override
    public String toString() {
      return Objects.toStringHelper(this).add("uri", imageRequest.getSourceUri()).toString();
    }
  };
}
 
Example #2
Source File: ImagePipeline.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a DataSource supplier that will on get submit the request for execution and return a
 * DataSource representing the pending results of the task.
 * @param imageRequest the request to submit (what to execute).
 * @param bitmapCacheOnly whether to only look for the image in the bitmap cache
 * @return a DataSource representing pending results and completion of the request
 */
public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier(
    final ImageRequest imageRequest,
    final Object callerContext,
    final boolean bitmapCacheOnly) {
  return new Supplier<DataSource<CloseableReference<CloseableImage>>>() {
    @Override
    public DataSource<CloseableReference<CloseableImage>> get() {
      if (bitmapCacheOnly) {
        return fetchImageFromBitmapCache(imageRequest, callerContext);
      } else {
        return fetchDecodedImage(imageRequest, callerContext);
      }
    }
    @Override
    public String toString() {
      return Objects.toStringHelper(this)
          .add("uri", imageRequest.getSourceUri())
          .toString();
    }
  };
}
 
Example #3
Source File: FrescoController2Impl.java    From fresco with MIT License 6 votes vote down vote up
@Override
public void onNewResult(
    FrescoDrawable2 drawable,
    VitoImageRequest imageRequest,
    DataSource<CloseableReference<CloseableImage>> dataSource) {
  if (dataSource == null || !dataSource.hasResult()) {
    return;
  }

  CloseableReference<CloseableImage> image = dataSource.getResult();
  try {
    if (!CloseableReference.isValid(image)) {
      onFailure(drawable, imageRequest, dataSource);
    } else {
      setActualImage(drawable, imageRequest, image, false, dataSource);
    }
  } finally {
    CloseableReference.closeSafely(image);
  }
}
 
Example #4
Source File: CompositionPostProcessor.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
public CompositionPostProcessor(
  int width,
  int height,
  @Nullable JSONObject config,
  @Nonnull CloseableReference<CloseableImage> src,
  @Nonnull CacheKey srcCacheKey
) {
  super(config);

  InputConverter converter = new InputConverter(width, height);

  mWidth = width;
  mHeight = height;

  final PointF center = new PointF(0.5f, 0.5f);
  final Transform transform = new Transform(center, center, new Scale.WithMode(Scale.Mode.COVER), 0);

  mSrc = src.clone();
  mSrcCacheKey = srcCacheKey;
  mSrcTransform = converter.convertTransform(config, "srcTransform", transform);
  mDstTransform = converter.convertTransform(config, "dstTransform", transform);
  mResizeCanvasTo = converter.convertText(config, "resizeCanvasTo", null);
  mSwapImages = converter.convertBool(config, "swapImages", false);
}
 
Example #5
Source File: ImagePipelineTest.java    From fresco with MIT License 6 votes vote down vote up
@Test
public void testFetchFromBitmapCacheDueToImageRequest() {
  Producer<CloseableReference<CloseableImage>> bitmapCacheSequence = mock(Producer.class);
  when(mImageRequest.getLowestPermittedRequestLevel())
      .thenReturn(ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
  when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest))
      .thenReturn(bitmapCacheSequence);
  mImagePipeline.fetchDecodedImage(mImageRequest, mCallerContext);
  verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", false);
  verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false);
  ArgumentCaptor<ProducerContext> producerContextArgumentCaptor =
      ArgumentCaptor.forClass(ProducerContext.class);
  verify(bitmapCacheSequence)
      .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture());
  assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected());
  assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH);
  assertEquals(
      producerContextArgumentCaptor.getValue().getLowestPermittedRequestLevel(),
      ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
}
 
Example #6
Source File: AnimatedFrameCacheTest.java    From fresco with MIT License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  MemoryCacheParams params =
      new MemoryCacheParams(
          4 * ByteConstants.MB,
          256,
          Integer.MAX_VALUE,
          Integer.MAX_VALUE,
          Integer.MAX_VALUE,
          TimeUnit.MINUTES.toMillis(5));
  when(mMemoryCacheParamsSupplier.get()).thenReturn(params);
  CountingMemoryCache<CacheKey, CloseableImage> countingMemoryCache =
      BitmapCountingMemoryCacheFactory.get(
          mMemoryCacheParamsSupplier, mMemoryTrimmableRegistry, null);
  mCacheKey = new SimpleCacheKey("key");
  mAnimatedFrameCache = new AnimatedFrameCache(mCacheKey, countingMemoryCache);
  mFrame1 = CloseableReference.of(mock(CloseableImage.class));
  mFrame2 = CloseableReference.of(mock(CloseableImage.class));
}
 
Example #7
Source File: CountingMemoryCacheTest.java    From fresco with MIT License 6 votes vote down vote up
@Test
public void testReuseExclusive_CacheSameItemWithDifferentKey() {
  CloseableReference<Integer> cachedRef =
      mCache.cache(KEY, newReference(100), mEntryStateObserver);
  cachedRef.close();
  verify(mEntryStateObserver).onExclusivityChanged(KEY, true);
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(1, 100);
  cachedRef = mCache.reuse(KEY);
  assertNotNull(cachedRef);
  verify(mEntryStateObserver).onExclusivityChanged(KEY, false);
  assertTotalSize(0, 0);
  assertExclusivelyOwnedSize(0, 0);
  CloseableReference<Integer> newItem = mCache.cache(KEYS[2], cachedRef);
  cachedRef.close();
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(0, 0);
  newItem.close();
  verify(mEntryStateObserver).onExclusivityChanged(KEY, true);
  assertTotalSize(1, 100);
  assertExclusivelyOwnedSize(1, 100);
}
 
Example #8
Source File: LocalExifThumbnailProducer.java    From fresco with MIT License 6 votes vote down vote up
private EncodedImage buildEncodedImage(PooledByteBuffer imageBytes, ExifInterface exifInterface) {
  Pair<Integer, Integer> dimensions =
      BitmapUtil.decodeDimensions(new PooledByteBufferInputStream(imageBytes));
  int rotationAngle = getRotationAngle(exifInterface);
  int width = dimensions != null ? dimensions.first : EncodedImage.UNKNOWN_WIDTH;
  int height = dimensions != null ? dimensions.second : EncodedImage.UNKNOWN_HEIGHT;
  EncodedImage encodedImage;
  CloseableReference<PooledByteBuffer> closeableByteBuffer = CloseableReference.of(imageBytes);
  try {
    encodedImage = new EncodedImage(closeableByteBuffer);
  } finally {
    CloseableReference.closeSafely(closeableByteBuffer);
  }
  encodedImage.setImageFormat(DefaultImageFormats.JPEG);
  encodedImage.setRotationAngle(rotationAngle);
  encodedImage.setWidth(width);
  encodedImage.setHeight(height);
  return encodedImage;
}
 
Example #9
Source File: PostprocessorProducer.java    From fresco with MIT License 6 votes vote down vote up
@Override
public void produceResults(
    final Consumer<CloseableReference<CloseableImage>> consumer, ProducerContext context) {
  final ProducerListener2 listener = context.getProducerListener();
  final Postprocessor postprocessor = context.getImageRequest().getPostprocessor();
  final PostprocessorConsumer basePostprocessorConsumer =
      new PostprocessorConsumer(consumer, listener, postprocessor, context);
  final Consumer<CloseableReference<CloseableImage>> postprocessorConsumer;
  if (postprocessor instanceof RepeatedPostprocessor) {
    postprocessorConsumer =
        new RepeatedPostprocessorConsumer(
            basePostprocessorConsumer, (RepeatedPostprocessor) postprocessor, context);
  } else {
    postprocessorConsumer = new SingleUsePostprocessorConsumer(basePostprocessorConsumer);
  }
  mInputProducer.produceResults(postprocessorConsumer, context);
}
 
Example #10
Source File: ProducerSequenceFactory.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Returns a sequence that can be used for a request for a decoded image.
 *
 * @param imageRequest the request that will be submitted
 * @return the sequence that should be used to process the request
 */
public Producer<CloseableReference<CloseableImage>> getDecodedImageProducerSequence(
    ImageRequest imageRequest) {
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.beginSection("ProducerSequenceFactory#getDecodedImageProducerSequence");
  }
  Producer<CloseableReference<CloseableImage>> pipelineSequence =
      getBasicDecodedImageSequence(imageRequest);

  if (imageRequest.getPostprocessor() != null) {
    pipelineSequence = getPostprocessorSequence(pipelineSequence);
  }

  if (mUseBitmapPrepareToDraw) {
    pipelineSequence = getBitmapPrepareSequence(pipelineSequence);
  }
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.endSection();
  }
  return pipelineSequence;
}
 
Example #11
Source File: CountingMemoryCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes exclusively owned values from the cache until there is at most count of them
 * and they occupy no more than size bytes.
 */
private synchronized Collection<CloseableReference<V>> trimEvictionQueueTo(
    int count,
    long size) {
  Preconditions.checkArgument(count >= 0);
  Preconditions.checkArgument(size >= 0);

  List<CloseableReference<V>> evictedValues = Lists.newArrayList();
  while (mEvictionQueue.size() > count || mEvictionQueueSize > size) {
    CacheEntry<K, V> cacheEntry = mEvictionQueue.iterator().next();
    evictedValues.add(cacheEntry.value);
    removeFromEvictionQueue(cacheEntry);
    removeFromCachedEntries(cacheEntry);
    mMemoryCacheIndex.removeEntry(cacheEntry.key, cacheEntry.value);
  }
  return evictedValues;
}
 
Example #12
Source File: LocalFetchProducer.java    From fresco with MIT License 6 votes vote down vote up
/** Creates a memory-backed encoded image from the stream. The stream is closed. */
protected EncodedImage getByteBufferBackedEncodedImage(InputStream inputStream, int length)
    throws IOException {
  CloseableReference<PooledByteBuffer> ref = null;
  try {
    if (length <= 0) {
      ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream));
    } else {
      ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream, length));
    }
    return new EncodedImage(ref);
  } finally {
    Closeables.closeQuietly(inputStream);
    CloseableReference.closeSafely(ref);
  }
}
 
Example #13
Source File: PostprocessorProducer.java    From fresco with MIT License 6 votes vote down vote up
private void updateSourceImageRef(
    @Nullable CloseableReference<CloseableImage> sourceImageRef, int status) {
  CloseableReference<CloseableImage> oldSourceImageRef;
  boolean shouldSubmit;
  synchronized (PostprocessorConsumer.this) {
    if (mIsClosed) {
      return;
    }
    oldSourceImageRef = mSourceImageRef;
    mSourceImageRef = CloseableReference.cloneOrNull(sourceImageRef);
    mStatus = status;
    mIsDirty = true;
    shouldSubmit = setRunningIfDirtyAndNotRunning();
  }
  CloseableReference.closeSafely(oldSourceImageRef);
  if (shouldSubmit) {
    submitPostprocessing();
  }
}
 
Example #14
Source File: PipelineDraweeController.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Initializes this controller with the new data source supplier, id and caller context. This
 * allows for reusing of the existing controller instead of instantiating a new one. This method
 * should be called when the controller is in detached state.
 *
 * @param dataSourceSupplier data source supplier
 * @param id unique id for this controller
 * @param callerContext tag and context for this controller
 */
public void initialize(
    Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier,
    String id,
    CacheKey cacheKey,
    Object callerContext,
    @Nullable ImmutableList<DrawableFactory> customDrawableFactories,
    @Nullable ImageOriginListener imageOriginListener) {
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.beginSection("PipelineDraweeController#initialize");
  }
  super.initialize(id, callerContext);
  init(dataSourceSupplier);
  mCacheKey = cacheKey;
  setCustomDrawableFactories(customDrawableFactories);
  clearImageOriginListeners();
  maybeUpdateDebugOverlay(null);
  addImageOriginListener(imageOriginListener);
  if (FrescoSystrace.isTracing()) {
    FrescoSystrace.endSection();
  }
}
 
Example #15
Source File: BitmapMemoryCacheProducerTest.java    From fresco with MIT License 6 votes vote down vote up
@Test
public void testDontCacheIntermediateImageAsAlreadyHaveFullQuality() {
  setupBitmapMemoryCacheGetNotFound();
  setupInputProducerStreamingSuccess();
  CloseableImage closeableImage = mock(CloseableImage.class);
  when(closeableImage.getQualityInfo()).thenReturn(ImmutableQualityInfo.FULL_QUALITY);
  CloseableReference<CloseableImage> closeableImageRef = CloseableReference.of(closeableImage);
  setupBitmapMemoryCacheGetSuccessOnSecondRead(closeableImageRef);
  mBitmapMemoryCacheProducer.produceResults(mConsumer, mProducerContext);
  verify(mMemoryCache, never()).cache(mBitmapMemoryCacheKey, mIntermediateImageReference);
  verify(mMemoryCache).cache(mBitmapMemoryCacheKey, mFinalImageReference);
  verify(mConsumer).onNewResult(closeableImageRef, Consumer.NO_FLAGS);
  verify(mConsumer).onNewResult(mFinalImageReferenceClone, Consumer.IS_LAST);
  Assert.assertTrue(!mFinalImageReferenceClone.isValid());
  Assert.assertEquals(
      0, closeableImageRef.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
  verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
  Map<String, String> extraMap =
      ImmutableMap.of(BitmapMemoryCacheProducer.EXTRA_CACHED_VALUE_FOUND, "false");
  verify(mProducerListener)
      .onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, extraMap);
  verify(mProducerListener, never())
      .onUltimateProducerReached(eq(mProducerContext), anyString(), anyBoolean());
}
 
Example #16
Source File: RepeatedPostprocessorProducerTest.java    From fresco with MIT License 6 votes vote down vote up
private void verifyNewResultProcessed(int index, Bitmap destBitmap) {
  mInOrder
      .verify(mProducerListener)
      .onProducerStart(mProducerContext, PostprocessorProducer.NAME);
  mInOrder.verify(mPostprocessor).process(mSourceBitmap, mPlatformBitmapFactory);
  mInOrder
      .verify(mProducerListener)
      .requiresExtraMap(mProducerContext, PostprocessorProducer.NAME);
  mInOrder
      .verify(mProducerListener)
      .onProducerFinishWithSuccess(
          eq(mProducerContext), eq(PostprocessorProducer.NAME), eq(mExtraMap));
  mInOrder.verify(mConsumer).onNewResult(any(CloseableReference.class), eq(Consumer.NO_FLAGS));
  mInOrder.verifyNoMoreInteractions();

  assertEquals(index + 1, mResults.size());
  CloseableReference<CloseableImage> res0 = mResults.get(index);
  assertTrue(CloseableReference.isValid(res0));
  assertSame(destBitmap, ((CloseableStaticBitmap) res0.get()).getUnderlyingBitmap());
  res0.close();
  verify(mBitmapResourceReleaser).release(destBitmap);
}
 
Example #17
Source File: FrescoControllerImpl.java    From fresco with MIT License 6 votes vote down vote up
@Override
public void onNewResult(
    FrescoState frescoState, DataSource<CloseableReference<CloseableImage>> dataSource) {
  if (dataSource != null && !dataSource.isClosed()) {
    final boolean shouldClose =
        mFrescoContext.getExperiments().closeDatasourceOnNewResult() && dataSource.isFinished();
    final CloseableReference<CloseableImage> result = dataSource.getResult();
    try {
      frescoState.setImageFetched(true);
      if (frescoState.isAttached()) {
        displayResultOrError(frescoState, result, false, dataSource);
      }
    } finally {
      CloseableReference.closeSafely(result);
      if (shouldClose) {
        dataSource.close();
      }
    }
  }
}
 
Example #18
Source File: ImagePipeline.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Submits a request for execution and returns a DataSource representing the pending encoded
 * image(s).
 *
 * <p>The returned DataSource must be closed once the client has finished with it.
 * @param imageRequest the request to submit
 * @return a DataSource representing the pending encoded image(s)
 */
public DataSource<CloseableReference<PooledByteBuffer>> fetchEncodedImage(
    ImageRequest imageRequest,
    Object callerContext) {
  Producer<CloseableReference<PooledByteBuffer>> producerSequence =
      mProducerSequenceFactory.getEncodedImageProducerSequence(
          imageRequest);
    return submitFetchRequest(producerSequence, imageRequest, callerContext);
}
 
Example #19
Source File: ImagePipelineMultiUriHelper.java    From fresco with MIT License 5 votes vote down vote up
private static Supplier<DataSource<CloseableReference<CloseableImage>>>
    getImageRequestDataSourceSupplier(
        final ImagePipeline imagePipeline,
        final ImageRequest imageRequest,
        final Object callerContext,
        final RequestListener requestListener,
        final @Nullable String uiComponentId) {
  return getImageRequestDataSourceSupplier(
      imagePipeline,
      imageRequest,
      callerContext,
      ImageRequest.RequestLevel.FULL_FETCH,
      requestListener,
      uiComponentId);
}
 
Example #20
Source File: FrescoBitmapUtils.java    From LiuAGeAndroid with MIT License 5 votes vote down vote up
/**
 * 释放引用
 *
 * @param reference    需要被释放的引用
 * @param isReleaseAll 当前释放请求是否在释放全部引用时调用
 */
public void releaseCloseReference(CloseableReference reference, boolean isReleaseAll) {
    if (mFrescoListener != null && !isReleaseAll) {
        //独自通知功能只在单独释放某个引用时才调用
        mFrescoListener.onReferenceRelease(reference);
    }
    CloseableReference.closeSafely(reference);
    reference = null;
}
 
Example #21
Source File: NetworkFetchProducerTest.java    From fresco with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
public void testNoIntermediateResults() throws Exception {
  long currentTime = 86400l;
  mNetworkFetchProducer.setSystemUptime(currentTime);
  NetworkFetcher.Callback callback = performFetch();

  when(mNetworkFetcher.shouldPropagate(any(FetchState.class))).thenReturn(false);
  final BlockingInputStream inputStream = new BlockingInputStream();
  final Future requestHandlerFuture = performResponse(inputStream, -1, callback);

  // Consumer should not be notified before any data is read
  inputStream.waitUntilReadingThreadBlocked();
  verify(mPooledByteBufferFactory).newOutputStream();
  verify(mConsumer, never()).onNewResult(any(CloseableReference.class), anyInt());
  verifyPooledByteBufferUsed(0);

  // Allow NetworkFetchProducer to read 1024 bytes and check that consumer is not notified
  inputStream.increaseBytesToRead(1024);
  inputStream.waitUntilReadingThreadBlocked();
  inputStream.increaseBytesToRead(1024);
  inputStream.waitUntilReadingThreadBlocked();
  verify(mConsumer, never()).onNewResult(any(CloseableReference.class), anyInt());
  verifyPooledByteBufferUsed(0);

  inputStream.signalEof();
  requestHandlerFuture.get();
  // Check no intermediate results were propagated
  verify(mProducerListener, times(0))
      .onProducerEvent(
          mProducerContext,
          NetworkFetchProducer.PRODUCER_NAME,
          NetworkFetchProducer.INTERMEDIATE_RESULT_PRODUCER_EVENT);
  // Test final result
  verify(mConsumer, times(1)).onNewResult(anyObject(), eq(Consumer.IS_LAST));
  verifyPooledByteBufferUsed(1);
  // When everything is over, pooled byte buffer output stream should be closed
  verify(mPooledByteBufferOutputStream).close();
}
 
Example #22
Source File: DecodeProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
public DecodeProducer(
    final ByteArrayPool byteArrayPool,
    final Executor executor,
    final ImageDecoder imageDecoder,
    final ProgressiveJpegConfig progressiveJpegConfig,
    final Producer<CloseableReference<PooledByteBuffer>> nextProducer) {
  mByteArrayPool = Preconditions.checkNotNull(byteArrayPool);
  mExecutor = Preconditions.checkNotNull(executor);
  mImageDecoder = Preconditions.checkNotNull(imageDecoder);
  mProgressiveJpegConfig = Preconditions.checkNotNull(progressiveJpegConfig);
  mNextProducer = Preconditions.checkNotNull(nextProducer);
}
 
Example #23
Source File: InstrumentedMemoryCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public CloseableReference<V> get(K key, @Nullable S lookupStrategy) {
  CloseableReference<V> result = mDelegate.get(key, lookupStrategy);
  if (result == null) {
    mTracker.onCacheMiss();
  } else {
    mTracker.onCacheHit();
  }
  return result;
}
 
Example #24
Source File: ProducerSequenceFactoryTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testLocalVideoFileFullFetch() {
  PowerMockito.when(mImageRequest.getSourceUriType()).thenReturn(SOURCE_TYPE_LOCAL_VIDEO_FILE);
  Producer<CloseableReference<CloseableImage>> producer =
      mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest);
  assertSame(producer, mProducerSequenceFactory.mLocalVideoFileFetchSequence);
}
 
Example #25
Source File: CountingMemoryCacheTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testEviction_ByEvictionQueueSize() {
  CloseableReference<Integer> originalRef1 = newReference(200);
  CloseableReference<Integer> valueRef1 = mCache.cache(KEYS[1], originalRef1);
  originalRef1.close();
  valueRef1.close();
  CloseableReference<Integer> originalRef2 = newReference(300);
  CloseableReference<Integer> valueRef2 = mCache.cache(KEYS[2], originalRef2);
  originalRef2.close();
  valueRef2.close();
  CloseableReference<Integer> originalRef3 = newReference(700);
  CloseableReference<Integer> valueRef3 = mCache.cache(KEYS[3], originalRef3);
  originalRef3.close();
  assertTotalSize(3, 1200);
  assertExclusivelyOwnedSize(2, 500);
  assertExclusivelyOwned(KEYS[1], 200);
  assertExclusivelyOwned(KEYS[2], 300);
  assertSharedWithCount(KEYS[3], 700, 1);
  verify(mReleaser, never()).release(anyInt());

  // closing the client reference for item3 will cause item1 to be evicted
  valueRef3.close();
  assertTotalSize(2, 1000);
  assertExclusivelyOwnedSize(2, 1000);
  assertNotCached(KEYS[1], 200);
  assertExclusivelyOwned(KEYS[2], 300);
  assertExclusivelyOwned(KEYS[3], 700);
  verify(mReleaser).release(200);
}
 
Example #26
Source File: MultiplexProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
private synchronized boolean isIntermediateResultExpected() {
  for (Pair<Consumer<CloseableReference<T>>, ProducerContext> pair : mConsumerContextPairs) {
    if (pair.second.isIntermediateResultExpected()) {
      return true;
    }
  }
  return false;
}
 
Example #27
Source File: BaseFrescoDrawable.java    From fresco with MIT License 5 votes vote down vote up
public @Nullable Drawable setImage(
    @Nullable Drawable imageDrawable,
    @Nullable CloseableReference<CloseableImage> imageReference) {
  CloseableReference.closeSafely(mImageReference);
  mImageReference = CloseableReference.cloneOrNull(imageReference);
  return setDrawable(IMAGE_DRAWABLE_INDEX, imageDrawable);
}
 
Example #28
Source File: AnimatedDrawableCachingBackendImpl.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
private synchronized void maybeCacheRenderedBitmap(
    int frameNumber,
    CloseableReference<Bitmap> bitmapReference) {
  if (!mBitmapsToKeepCached.get(frameNumber)) {
    return;
  }

  int existingIndex = mCachedBitmaps.indexOfKey(frameNumber);
  if (existingIndex >= 0) {
    CloseableReference<Bitmap> oldReference = mCachedBitmaps.valueAt(existingIndex);
    oldReference.close();
    mCachedBitmaps.removeAt(existingIndex);
  }
  mCachedBitmaps.put(frameNumber, bitmapReference.clone());
}
 
Example #29
Source File: BitmapMemoryCacheProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected boolean shouldCacheResult(
    CloseableReference<CloseableImage> result,
    BitmapMemoryCacheKey cacheKey,
    boolean isLast) {
  if (result.get().isStateful()) {
    return false;
  }
  return isLast || shouldCacheIntermediateResult(result, cacheKey);
}
 
Example #30
Source File: ProducerSequenceFactory.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Creates a new fetch sequence that just needs the source producer.
 *
 * @param inputProducer the source producer
 * @return the new sequence
 */
private Producer<CloseableReference<CloseableImage>> newBitmapCacheGetToLocalTransformSequence(
    Producer<EncodedImage> inputProducer) {
  ThumbnailProducer<EncodedImage>[] defaultThumbnailProducers = new ThumbnailProducer[1];
  defaultThumbnailProducers[0] = mProducerFactory.newLocalExifThumbnailProducer();
  return newBitmapCacheGetToLocalTransformSequence(inputProducer, defaultThumbnailProducers);
}