Skip to content

Regarding the code snippet in ConcurrentBag#remove(), specifically threadLocalList.get().remove(bagEntry), when using the list obtained from threadLocalList.get() which employs weak references, removing an element of type T is an ineffective operation. #2354

@huyu-tom

Description

@huyu-tom

ConcurrentBag#remove()

  public boolean remove(final T bagEntry)
   {
      if (!bagEntry.compareAndSet(STATE_IN_USE, STATE_REMOVED) && !bagEntry.compareAndSet(STATE_RESERVED, STATE_REMOVED) && !closed) {
         LOGGER.warn("Attempt to remove an object from the bag that was not borrowed or reserved: {}", bagEntry);
         return false;
      }

      final var removed = sharedList.remove(bagEntry);
      if (!removed && !closed) {
         LOGGER.warn("Attempt to remove an object from the bag that does not exist: {}", bagEntry);
      }

      threadLocalList.get().remove(bagEntry);

      return removed;
   }

It is recommended to change to the following two solutions:

1

  public boolean remove(final T bagEntry)
   {
      if (!bagEntry.compareAndSet(STATE_IN_USE, STATE_REMOVED) && !bagEntry.compareAndSet(STATE_RESERVED, STATE_REMOVED) && !closed) {
         LOGGER.warn("Attempt to remove an object from the bag that was not borrowed or reserved: {}", bagEntry);
         return false;
      }

      final var removed = sharedList.remove(bagEntry);
      if (!removed && !closed) {
         LOGGER.warn("Attempt to remove an object from the bag that does not exist: {}", bagEntry);
      }
 

     if(!useWeakThreadLocals){
       threadLocalList.get().remove(bagEntry);
     } 
      
      return removed;
   }

2

  class IWeakReference<T> extends WeakReference<T> {

  public IWeakReference(T referent) {
    super(referent);
  }

  public IWeakReference(T referent, ReferenceQueue<? super T> q) {
    super(referent, q);
  }

  @Override
  public boolean equals(Object obj) {
    return get().equals(obj);
  }
}

  public boolean remove(final T bagEntry)
   {
      if (!bagEntry.compareAndSet(STATE_IN_USE, STATE_REMOVED) && !bagEntry.compareAndSet(STATE_RESERVED, STATE_REMOVED) && !closed) {
         LOGGER.warn("Attempt to remove an object from the bag that was not borrowed or reserved: {}", bagEntry);
         return false;
      }

      final var removed = sharedList.remove(bagEntry);
      if (!removed && !closed) {
         LOGGER.warn("Attempt to remove an object from the bag that does not exist: {}", bagEntry);
      }
 
       threadLocalList.get().remove( useWeakThreadLocals ? new IWeakReference(bagEntry) : bagEntry );
      
      return removed;
   }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions