0

I have Java code that calls a native function which fills results by invoking a callback method multiple times before it returns. The native code doesn't spawn any threads on its own. All java-native is handled by javacpp. The outline looks like this:

class Scanner {
    private final LinkedList<Long> matchedIds = new LinkedList<>();

    private final Handler handler = new Handler() {
        public void call(int id) {
            matchedIds.add(id);
        }
    };

    public void scan() {
      callToNativeLib(handler);
      matchedIds.forEach(System.out::println)  // throws sometimes
    }
}


new Scanner().scan();

The problem is it sometimes (very rarely) throws:

java.lang.NullPointerException: Cannot read field "next" because "this.next" is null
    at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:897)
    at java.base/java.lang.Iterable.forEach(Iterable.java:74)

Why could it be? Almost like the list is made broken by callbacks coming from native code.

EDIT: Got a ConcurrentModificationException. My assumptions must be wrong.

milan
  • 2,355
  • 2
  • 23
  • 38
  • Why is ```matchedIds``` not part of the anonymous handler class? It seems to me like a bad idea to call a native library with side effects (although this may be unrelated to the issue at hand). – geanakuch Jun 15 '23 at 12:58
  • It's not my code. I would make it all within scope of `scan()` but I don't think it makes any difference. – milan Jun 15 '23 at 13:36
  • I suspect my handler gets GC-ed. – milan Jun 16 '23 at 12:06

0 Answers0