(junit/mockito) thread.join() is completed before thread work is done?

36 views Asked by At

did some quick searching and wasn't able to come up with much. Here is some small example code

Map<String, Integer> valuesFromThread = new HashMap<>();
List<String> threads = new ArrayList<>();
List<String> labels = new ArrayList<>();

labels.add('hello1');
labels.add('hello2');
labels.add('hello3');

for (String l : labels)
{
    Thread t = new Thread(() ->
    {
        valuesFromThread.put(l, 123);
    });
    t.start();
    threads.add(t);
}

// wait for work to complete
for (Thread t : threads.values())
{
    t.join();
}

if (labels.size() != presignedS3Urls.size())
{
    // throw error (never happens in practice)
}

Since in practice we wait for each thread to finish, guaranteeing that there is an entry in valuesFromThread for each thread, therefore each label.

However when I use this method in a unit test, it seems like the work from the thread is never actually executed, or at least not before we do the check at the bottom.

Note, this code is nested within a method I need to test, so I am not actually needing create a mock scenario equivalent to the above which tests something similar, I need this logic to be able to be testable via the outer method without changing any of it.

Is there any way to resolve this?

I have not found any resources on this issue, so have not been able to try anything yet.

0

There are 0 answers