Check if any object is used somewhere before deleting it in java

I have a situation where I need to provide an error message when someone tries to delete an object bfrom bListand it is used in some other class say class A.
Unless breferenced in another class, I should not cause an error message.

Pseudocode for the above scenario

public class A {

    B b;

    void setB(B b) {
        this.b = b;
    }
}

public class NotifyTest {

    List<B> bList = new ArrayList<>();

    String notifyTest() {

        A a = new A();
        B b = new B();
        a.setB(b);
        bList.add(b);

        if (b referencedSomewhere)   
        {
            return "error";
        }
        else
        {
             bList.remove(b);
             return  "success";
        }
    }
}

Moving my entire model to verify that the object is being bused somewhere is a performance hit, so I don't want to go for this approach.
Please let me know if there is any solution for this script provided by Java, or suggest a better way to handle this.

Edit1: , b , bList

+4
3

, - . , . , , .

class RefCounter<T>
{
   private HashMap<T, Integer>  counts = new HashMap<>();

   public T  using(T object)
   {
      Integer  num = counts.get(object);
      if (num == null)
         counts.put(object, 1);
      else
         counts.put(object, num+1);
      return object;
   }

   public T  release(T object)
   {
      Integer  num = counts.get(object);
      if (num == null)
         throw new IllegalArgumentException("Object not in RefCounter");
      else if (num == 1)
         counts.remove(object);
      else
         counts.put(object, num-1);
      return object;
   }


   public boolean  usedElsewhere(T object)
   {
      Integer  num = counts.get(object);
      return (num != null && num > 1);
   }

}

, RefCounter.

refCounter.using(x);
someList.add(x);

someList.remove(index);
refCounter.release(x);

,

if (refCounter.usedElsewhere(x) {
   return "error";
} else {
   someList.remove(index);
   refCounter.release(x);
}

, , using() release() , , .

+1

( ), java , , , java .

Most of the high level contains garbage collection (GC) such as java, C #, Python (iirc), etc. You only need to monitor the memory if you are using lower-level languages ​​like C ir C ++ (somewhere between low and high level actually)

0
source

Source: https://habr.com/ru/post/1655026/


All Articles