简体   繁体   中英

NullPointer Exception using Thread.join on multiple threads

I have the following issue with one of my Java programs. I'm trying to launch several threads depending on what my main program find on the file system. The way it works is quite classic: - First loop: instantiate, store in a local array and start a new thread - Second loop: wait all of thread with '.join()' method

At execution i get a NullPointerException on the '.join()'. This exception is thrown by the 3rd thread launched (because it finishes before the 2 first one)

This is an example of my code:

PackageManager[] myRootManagers = new PackageManager[myCCDirs.size()];
int i = 0;
for (PkgDescriptor descriptor : myCCDirs) {
    ...
    // --- instantiate new ROOT manager
    myRootManagers[i] = new PackageManager(getConfig(), loggerPac, descriptor);
    // --- start it
    myRootManagers[i].start();
}

for (PackageManager packageManager : myRootManagers) {
    try {
        packageManager.join();
    }
    catch (InterruptedException e) {
        loggerPac.error("...");
    }
}

Does someone know why this exception occurs ?

Make sure all i in the first loop covers all valid indecies in the myRootManagers array.

Note that you should increment i in the end of the first for loop, since array indecies are 0-based.:

int i = 0;
for (PkgDescriptor descriptor : myCCDirs) {
    ...
    // --- instantiate new ROOT manager
    myRootManagers[i] = new PackageManager(getConfig(), loggerPac, descriptor);
    // --- start it
    myRootManagers[i].start();

    i++;   // <-----------------------------------
}

As a debugging step, I would add

System.out.println(Arrays.toString(myRootManagers));

after the first loop, to assert that there are no null references left.

This seems odd to me unless you hidden the important part:

for (PkgDescriptor descriptor : myCCDirs) {
    ...
    // --- instantiate new ROOT manager
    myRootManagers[i] = new PackageManager(getConfig(), loggerPac, descriptor);
    // --- start it
    myRootManagers[i].start();
}

You iterate over myCCDirs but initialize myRootManagers objects, maybe you didn't increment i ?

This could also happen if a myCCDirs is removed in another thread.

PackageManager[] myRootManagers = new PackageManager[myCCDirs.size()]; // size is 3
int i = 0;
for (PkgDescriptor descriptor : myCCDirs) { // size is now 2 so the last field is not set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM