Search code examples
javaconcurrencyatomic

Why does invoking a method to a null Atomic class does not produce exception?


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class _7_Synchronizing_Data_Access {
    private AtomicInteger count;

    private void incrementAndReport() {
        System.out.print(count.incrementAndGet() + "here"); //does not print
    }

    public static void main(String[] args) {
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(20);
            _7_Synchronizing_Data_Access manager = new _7_Synchronizing_Data_Access();
            for (int i = 0; i < 10; i++)
                service.submit(() -> manager.incrementAndReport());
        } finally {
            if (service != null)
                service.shutdown();
        }
    }
}

Running this program outputs nothing. Not even a NullPointerException. As you can see I did not instantiate count. I expect it throw an error. Why is that?


Solution

  • The NullPointerException exceptions are thrown and caught, but in order to see them, you need to check the Future instances returned by the service.submit calls:

    Changing your loop as follows:

    for (int i = 0; i < 10; i++) {
        Future f = service.submit(() -> manager.incrementAndReport());
        try {
            System.out.println (f.get ());
        }
        catch (ExecutionException exex) {
            System.out.println (exex);
        }
        catch (InterruptedException intEx) {
            System.out.println (intEx);
        }
    }
    

    will output:

    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    java.util.concurrent.ExecutionException: java.lang.NullPointerException
    

    You'll also see that the exceptions are thrown if you surround the System.out.println(count.incrementAndGet() + "here"); statement with try-catch:

    private void incrementAndReport() {
        try {
            System.out.println(count.incrementAndGet() + "here"); //does not print
        }
        catch (Exception exc) {
            System.out.println (exc);
        }
    }