Search code examples
javadebuggingintellij-idea

Watchpoint not triggered when inserting to ArrayList


I have a java program, it has a global variable ArrayList<Integer> al I put a watchpoint on it to track changes to this variable. I found that watchpoint only gets triggered when there is assignment to the this varible, like this al = new ArrayList<>, but when I insert into this list, the watchpoint is not getting triggered. I guess this is a normal behaviour. So is there any setting we can do, so that we get trigger everytime we insert or remove from the list.

The actual code for reference

public MyClass {

private static ArrayList<Integer> al = new ArrayList(); Put a watchpoint here

public static void main(String args[]){
    al = new ArrayList<>(); // watchpoint gets triggered here
    Integer a = 1;
    al.add(a); // watchpoint not getting triggered here
  }
}

EDIT

My actual scenario is this list can be modified from other threads, so I thought putting a watchpoint over it will be a good idea to know which thread modified it and also look into its stack trace


Solution

  • So is there any setting we can do, so that we get trigger everytime we insert or remove from the list.

    Well, if you add or remove elements from an ArrayList, the watchpoint will not be triggered, because ArrayList object itself is not changing.

    I have an idea that you can monitor changes to the elements inside the ArrayList, you would need to implement your own custom class ArrayList. This way you can set callback functions that get triggered whenever an element is added or removed from the list.

    import java.util.ArrayList;
    import java.util.function.Consumer;
    
    public class CustomObservableArrayList<T> extends ArrayList<T> {
    
        private Consumer<T> addCallback;
        private Consumer<T> removeCallback;
    
        public CustomObservableArrayList(Consumer<T> addCallback, Consumer<T> removeCallback) {
            super();
            this.addCallback = addCallback;
            this.removeCallback = removeCallback;
        }
    
        @Override
        public boolean add(T element) {
            boolean result = super.add(element);
            if (result && addCallback != null) {
                addCallback.accept(element);
            }
            return result;
        }
    
        @Override
        public boolean remove(Object element) {
            boolean result = super.remove(element);
            if (result && removeCallback != null) {
                removeCallback.accept((T) element);
            }
            return result;
        }
    }