Unit testing for potential concurrency issues

I recently had a small contest with one of my colleagues (whom I really respect) regarding the theoretical ability to check if any code is thread safe or not.

Suppose we have some FooUnknown black box FooUnknown taken from a third-party library, so we don’t have access to its original source code. In addition, maybe he internally uses some of his own methods (if that is the question).

Can we write a unit test that tells us that using this class (for example, an instance shared between multiple threads) is 100% thread safe or not?

My conclusion is that it is impossible . For me, this is obvious and understandable: although you can write code that will lead to some concurrency problems that can be detected. But the lack of such results does not guarantee that there are no problems with concurrency at all.

I also think that this question is not too broad . To be sure, let's say that we have a class some.FooUnknown , and we want to use it as follows:

 @ApplicationScoped public class FooService { private some.FooUnkown foo = new some.FooUnknown(); public void someStuff() { // ... String result = foo.doSomeStuff(); // ... } } 

How to check it to make sure that it is thread safe, that we do not need to wrap it in ThreadLocal<FooUnknown> ?

+5
source share
3 answers

This is not possible because there are many ways to create thread unreliability. Just a global variable in native code might be enough.

+1
source

Ignoring all practical reasons, it also explains why it is theoretically difficult to achieve a complete set of concurrency security tests:

Assuming there are n tags that work in the same data structure. Then any stream i has a sequence S i of atomic operations on this data structure, where each sequence can have a different length. Now you need to make sure in an ideal environment that all possible iteration sequences in all threads through this operation are covered by your tests. Even for relatively small sequences of operations and only two threads, this number is growing quite quickly.

But now the hard part is to transfer this data to a real computer. Identifying such atomic operations is a difficult task in itself, given the freedom to implement jvms and the Java memory model. Then there is also thread scheduling controlled by os. Therefore, it is usually out of your control what actual sequence of operations takes place in the data structure.

+2
source

You are right - like a black box, you cannot tell if it is thread safe or not. Even if you test it for 2 weeks and throw everything in it onto a million virtual machines, it may be thread-safe now, but it will become unsafe in 2018 (for example, internally checking which date is intentionally blocked for 2018-01-01)

+1
source

Source: https://habr.com/ru/post/1273899/


All Articles