<p>I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield.  I'd like to ask how people have gone about testing code that relies on threads for successful execution, or just how people have gone about testing those kinds of issues that only show up when two threads interact in a given manner?</p>

<p>This seems like a really key problem for programmers today, it would be useful to pool our knowledge on this one imho.</p>

[{'answer_id': 12223, 'author': 'Dale Ragan', 'author_id': 1117, 'author_profile': 'https://Stackoverflow.com/users/1117', 'pm_score': 2, 'selected': False, 'text': '<p>I have had the unfortunate task of testing threaded code and they are definitely the hardest tests I have ever written.</p>\n\n<p>When writing my tests, I used a combination of delegates and events.  Basically it is all about using <code>PropertyNotifyChanged</code> events with a <code>WaitCallback</code> or some kind of <code>ConditionalWaiter</code> that polls.</p>\n\n<p>I am not sure if this was the best approach, but it has worked out for me.</p>\n'}, {'answer_id': 12237, 'author': 'David Joyner', 'author_id': 1146, 'author_profile': 'https://Stackoverflow.com/users/1146', 'pm_score': 6, 'selected': False, 'text': '<p>Tough one indeed!  In my (C++) unit tests, I\'ve broken this down into several categories along the lines of the concurrency pattern used:</p>\n<ol>\n<li><p>Unit tests for classes that operate in a single thread and aren\'t thread aware -- easy, test as usual.</p>\n</li>\n<li><p>Unit tests for <a href="https://web.archive.org/web/20171215050902/http://www.cse.wustl.edu/%7Eschmidt/PDF/monitor.pdf" rel="noreferrer">Monitor objects</a> (those that execute synchronized methods in the callers\' thread of control) that expose a synchronized public API -- instantiate multiple mock threads that exercise the API.  Construct scenarios that exercise internal conditions of the passive object.  Include one longer running test that basically beats the heck out of it from multiple threads for a long period of time.  This is unscientific I know but it does build confidence.</p>\n</li>\n<li><p>Unit tests for <a href="https://web.archive.org/web/20151019023537/http://www.cse.wustl.edu/%7Eschmidt/PDF/Act-Obj.pdf" rel="noreferrer">Active objects</a> (those that encapsulate their own thread or threads of control) -- similar to #2 above with variations depending on the class design.  Public API may be blocking or non-blocking, callers may obtain futures, data may arrive at queues or need to be dequeued.  There are many combinations possible here; white box away.  Still requires multiple mock threads to make calls to the object under test.</p>\n</li>\n</ol>\n<p>As an aside:</p>\n<p>In internal developer training that I do, I teach the <a href="http://www.ddj.com/hpc-high-performance-computing/200001985" rel="noreferrer">Pillars of Concurrency</a> and these two patterns as the primary framework for thinking about and decomposing concurrency problems.  There\'s obviously more advanced concepts out there but I\'ve found that this set of basics helps keep engineers out of the soup.  It also leads to code that is more unit testable, as described above.</p>\n'}, {'answer_id': 12241, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 8, 'selected': False, 'text': "<p>Look, there's no easy way to do this.  I'm working on a project that is inherently multithreaded.  Events come in from the operating system and I have to process them concurrently.</p>\n<p>The simplest way to deal with testing complex, multithreaded application code is this:  If it's too complex to test, you're doing it wrong.  If you have a single instance that has multiple threads acting upon it, and you can't test situations where these threads step all over each other, then your design needs to be redone.  It's both as simple and as complex as this.</p>\n<p>There are many ways to program for multithreading that avoids threads running through instances at the same time.  The simplest is to make all your objects immutable.  Of course, that's not usually possible.  So you have to identify those places in your design where threads interact with the same instance and reduce the number of those places.  By doing this, you isolate a few classes where multithreading actually occurs, reducing the overall complexity of testing your system.</p>\n<p>But you have to realize that even by doing this, you still can't test every situation where two threads step on each other.  To do that, you'd have to run two threads concurrently in the same test, then control exactly what lines they are executing at any given moment.  The best you can do is simulate this situation.  But this might require you to code specifically for testing, and that's at best a half step towards a true solution.</p>\n<p>Probably the best way to test code for threading issues is through static analysis of the code.  If your threaded code doesn't follow a finite set of thread safe patterns, then you might have a problem.  I believe Code Analysis in VS does contain some knowledge of threading, but probably not much.</p>\n<p>Look, as things stand currently (and probably will stand for a good time to come), the best way to test multithreaded apps is to reduce the complexity of threaded code as much as possible.  Minimize areas where threads interact, test as best as possible, and use code analysis to identify danger areas.</p>\n"}, {'answer_id': 12739, 'author': 'graham.reeds', 'author_id': 342, 'author_profile': 'https://Stackoverflow.com/users/342', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://goodliffe.blogspot.com/" rel="noreferrer">Pete Goodliffe</a> has a series on the <a href="http://goodliffe.blogspot.com/search/label/threads" rel="noreferrer">unit testing of threaded</a> code.</p>\n\n<p>It\'s hard. I take the easier way out and try to keep the threading code abstracted from the actual test. Pete does mention that the way I do it is wrong but I\'ve either got the separation right or I\'ve just been lucky. </p>\n'}, {'answer_id': 17835, 'author': 'ollifant', 'author_id': 2078, 'author_profile': 'https://Stackoverflow.com/users/2078', 'pm_score': 5, 'selected': False, 'text': '<p>I also had serious problems testing multi- threaded code. Then I found a really cool solution in "xUnit Test Patterns" by Gerard Meszaros. The pattern he describes is called <strong>Humble object</strong>. </p>\n\n<p>Basically it describes how you can extract the logic into a separate, easy-to-test component that is decoupled from its environment. After you tested this logic, you can test the complicated behaviour (multi- threading, asynchronous execution, etc...)</p>\n'}, {'answer_id': 49203, 'author': 'Don Kirkby', 'author_id': 4794, 'author_profile': 'https://Stackoverflow.com/users/4794', 'pm_score': 3, 'selected': False, 'text': '<p>I like to write two or more test methods to execute on parallel threads, and each of them make calls into the object under test. I\'ve been using Sleep() calls to coordinate the order of the calls from the different threads, but that\'s not really reliable. It\'s also a lot slower because you have to sleep long enough that the timing usually works.</p>\n\n<p>I found the <a href="http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html" rel="nofollow noreferrer">Multithreaded TC Java library</a> from the same group that wrote FindBugs. It lets you specify the order of events without using Sleep(), and it\'s reliable. I haven\'t tried it yet.</p>\n\n<p>The biggest limitation to this approach is that it only lets you test the scenarios you suspect will cause trouble. As others have said, you really need to isolate your multithreaded code into a small number of simple classes to have any hope of thoroughly testing them.</p>\n\n<p>Once you\'ve carefully tested the scenarios you expect to cause trouble, an unscientific test that throws a bunch of simultaneous requests at the class for a while is a good way to look for unexpected trouble.</p>\n\n<p><strong>Update:</strong> I\'ve played a bit with the Multithreaded TC Java library, and it works well. I\'ve also ported some of its features to a .NET version I call <a href="https://github.com/donkirkby/donkirkby/tree/master/TickingTest" rel="nofollow noreferrer">TickingTest</a>.</p>\n'}, {'answer_id': 85101, 'author': 'Scott Bale', 'author_id': 2495576, 'author_profile': 'https://Stackoverflow.com/users/2495576', 'pm_score': 3, 'selected': False, 'text': '<p>For Java, check out chapter 12 of <a href="https://rads.stackoverflow.com/amzn/click/com/0321349601" rel="noreferrer" rel="nofollow noreferrer">JCIP</a>.  There are some concrete examples of writing deterministic, multi-threaded unit tests to at least test the correctness and invariants of concurrent code.</p>\n\n<p>"Proving" thread-safety with unit tests is much dicier.  My belief is that this is better served by automated integration testing on a variety of platforms/configurations.</p>\n'}, {'answer_id': 125487, 'author': 'Kevin Wong', 'author_id': 4792, 'author_profile': 'https://Stackoverflow.com/users/4792', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve done a lot of this, and yes it sucks.</p>\n\n<p>Some tips:</p>\n\n<ul>\n<li><a href="http://groboutils.sourceforge.net/" rel="nofollow noreferrer">GroboUtils</a> for running multiple test threads</li>\n<li><a href="http://www.alphaworks.ibm.com/tech/contest?open&amp;S_TACT=105AGX59&amp;S_CMP=GR&amp;ca=dgr-lnxw03awcontest" rel="nofollow noreferrer">alphaWorks ConTest</a> to instrument classes to cause interleavings to vary between iterations</li>\n<li>Create a <code>throwable</code> field and check it in <code>tearDown</code> (see Listing 1). If you catch a bad exception in another thread, just assign it to throwable.</li>\n<li>I created the utils class in Listing 2 and have found it invaluable, especially waitForVerify and waitForCondition, which will greatly increase the performance of your tests.</li>\n<li>Make good use of <code>AtomicBoolean</code> in your tests.  It is thread safe, and you\'ll often need a final reference type to store values from callback classes and suchlike.  See example in Listing 3.</li>\n<li>Make sure to always give your test a timeout (e.g., <code>@Test(timeout=60*1000)</code>), as concurrency tests can sometimes hang forever when they\'re broken.</li>\n</ul>\n\n<p>Listing 1:</p>\n\n<pre class="lang-java prettyprint-override"><code>@After\npublic void tearDown() {\n    if ( throwable != null )\n        throw throwable;\n}\n</code></pre>\n\n<p>Listing 2:</p>\n\n<pre class="lang-java prettyprint-override"><code>import static org.junit.Assert.fail;\nimport java.io.File;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Proxy;\nimport java.util.Random;\nimport org.apache.commons.collections.Closure;\nimport org.apache.commons.collections.Predicate;\nimport org.apache.commons.lang.time.StopWatch;\nimport org.easymock.EasyMock;\nimport org.easymock.classextension.internal.ClassExtensionHelper;\nimport static org.easymock.classextension.EasyMock.*;\n\nimport ca.digitalrapids.io.DRFileUtils;\n\n/**\n * Various utilities for testing\n */\npublic abstract class DRTestUtils\n{\n    static private Random random = new Random();\n\n/** Calls {@link #waitForCondition(Integer, Integer, Predicate, String)} with\n * default max wait and check period values.\n */\nstatic public void waitForCondition(Predicate predicate, String errorMessage) \n    throws Throwable\n{\n    waitForCondition(null, null, predicate, errorMessage);\n}\n\n/** Blocks until a condition is true, throwing an {@link AssertionError} if\n * it does not become true during a given max time.\n * @param maxWait_ms max time to wait for true condition. Optional; defaults\n * to 30 * 1000 ms (30 seconds).\n * @param checkPeriod_ms period at which to try the condition. Optional; defaults\n * to 100 ms.\n * @param predicate the condition\n * @param errorMessage message use in the {@link AssertionError}\n * @throws Throwable on {@link AssertionError} or any other exception/error\n */\nstatic public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms, \n    Predicate predicate, String errorMessage) throws Throwable \n{\n    waitForCondition(maxWait_ms, checkPeriod_ms, predicate, new Closure() {\n        public void execute(Object errorMessage)\n        {\n            fail((String)errorMessage);\n        }\n    }, errorMessage);\n}\n\n/** Blocks until a condition is true, running a closure if\n * it does not become true during a given max time.\n * @param maxWait_ms max time to wait for true condition. Optional; defaults\n * to 30 * 1000 ms (30 seconds).\n * @param checkPeriod_ms period at which to try the condition. Optional; defaults\n * to 100 ms.\n * @param predicate the condition\n * @param closure closure to run\n * @param argument argument for closure\n * @throws Throwable on {@link AssertionError} or any other exception/error\n */\nstatic public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms, \n    Predicate predicate, Closure closure, Object argument) throws Throwable \n{\n    if ( maxWait_ms == null )\n        maxWait_ms = 30 * 1000;\n    if ( checkPeriod_ms == null )\n        checkPeriod_ms = 100;\n    StopWatch stopWatch = new StopWatch();\n    stopWatch.start();\n    while ( !predicate.evaluate(null) ) {\n        Thread.sleep(checkPeriod_ms);\n        if ( stopWatch.getTime() &gt; maxWait_ms ) {\n            closure.execute(argument);\n        }\n    }\n}\n\n/** Calls {@link #waitForVerify(Integer, Object)} with &lt;code&gt;null&lt;/code&gt;\n * for {@code maxWait_ms}\n */\nstatic public void waitForVerify(Object easyMockProxy)\n    throws Throwable\n{\n    waitForVerify(null, easyMockProxy);\n}\n\n/** Repeatedly calls {@link EasyMock#verify(Object[])} until it succeeds, or a\n * max wait time has elapsed.\n * @param maxWait_ms Max wait time. &lt;code&gt;null&lt;/code&gt; defaults to 30s.\n * @param easyMockProxy Proxy to call verify on\n * @throws Throwable\n */\nstatic public void waitForVerify(Integer maxWait_ms, Object easyMockProxy)\n    throws Throwable\n{\n    if ( maxWait_ms == null )\n        maxWait_ms = 30 * 1000;\n    StopWatch stopWatch = new StopWatch();\n    stopWatch.start();\n    for(;;) {\n        try\n        {\n            verify(easyMockProxy);\n            break;\n        }\n        catch (AssertionError e)\n        {\n            if ( stopWatch.getTime() &gt; maxWait_ms )\n                throw e;\n            Thread.sleep(100);\n        }\n    }\n}\n\n/** Returns a path to a directory in the temp dir with the name of the given\n * class. This is useful for temporary test files.\n * @param aClass test class for which to create dir\n * @return the path\n */\nstatic public String getTestDirPathForTestClass(Object object) \n{\n\n    String filename = object instanceof Class ? \n        ((Class)object).getName() :\n        object.getClass().getName();\n    return DRFileUtils.getTempDir() + File.separator + \n        filename;\n}\n\nstatic public byte[] createRandomByteArray(int bytesLength)\n{\n    byte[] sourceBytes = new byte[bytesLength];\n    random.nextBytes(sourceBytes);\n    return sourceBytes;\n}\n\n/** Returns &lt;code&gt;true&lt;/code&gt; if the given object is an EasyMock mock object \n */\nstatic public boolean isEasyMockMock(Object object) {\n    try {\n        InvocationHandler invocationHandler = Proxy\n                .getInvocationHandler(object);\n        return invocationHandler.getClass().getName().contains("easymock");\n    } catch (IllegalArgumentException e) {\n        return false;\n    }\n}\n}\n</code></pre>\n\n<p>Listing 3:</p>\n\n<pre class="lang-java prettyprint-override"><code>@Test\npublic void testSomething() {\n    final AtomicBoolean called = new AtomicBoolean(false);\n    subject.setCallback(new SomeCallback() {\n        public void callback(Object arg) {\n            // check arg here\n            called.set(true);\n        }\n    });\n    subject.run();\n    assertTrue(called.get());\n}\n</code></pre>\n'}, {'answer_id': 125529, 'author': 'Robert Gould', 'author_id': 15124, 'author_profile': 'https://Stackoverflow.com/users/15124', 'pm_score': 4, 'selected': False, 'text': '<p>Another way to (kinda) test threaded code, and very complex systems in general is through <a href="http://en.wikipedia.org/wiki/Fuzz_testing" rel="noreferrer">Fuzz Testing</a>.\nIt\'s not great, and it won\'t find everything, but its likely to be useful and its simple to do.</p>\n\n<p>Quote:</p>\n\n<blockquote>\n  <p>Fuzz testing or fuzzing is a software testing technique that provides random data("fuzz") to the inputs of a program. If the program fails (for example, by crashing, or by failing built-in code assertions), the defects can be noted. The great advantage of fuzz testing is that the test design is extremely simple, and free of preconceptions about system behavior. </p>\n  \n  <p>...</p>\n  \n  <p>Fuzz testing is often used in large software development projects that employ black box testing. These projects usually have a budget to develop test tools, and fuzz testing is one of the techniques which offers a high benefit to cost ratio. </p>\n  \n  <p>...</p>\n  \n  <p>However, fuzz testing is not a substitute for exhaustive testing or formal methods: it can only provide a random sample of the system\'s behavior, and in many cases passing a fuzz test may only demonstrate that a piece of software handles exceptions without crashing, rather than behaving correctly. Thus, fuzz testing can only be regarded as a bug-finding tool rather than an assurance of quality.</p>\n</blockquote>\n'}, {'answer_id': 455054, 'author': 'Theo Lenndorff', 'author_id': 53881, 'author_profile': 'https://Stackoverflow.com/users/53881', 'pm_score': 7, 'selected': False, 'text': '<p>It\'s been a while when this question was posted, but it\'s still not answered ...</p>\n<p><a href="https://stackoverflow.com/questions/12159/how-should-i-unit-test-threaded-code/17835#17835">kleolb02</a>\'s answer is a good one. I\'ll try going into more details.</p>\n<p>There is a way, which I practice for C# code. For unit tests you should be able to program <em>reproducible</em> tests, which is the biggest challenge in multithreaded code. So my answer aims toward forcing asynchronous code into a test harness, which works <em>synchronously</em>.</p>\n<p>It\'s an idea from Gerard Meszaros\'s book &quot;<a href="http://xunitpatterns.com/" rel="noreferrer">xUnit Test Patterns</a>&quot; and is called &quot;Humble Object&quot; (p. 695): You have to separate core logic code and anything which smells like asynchronous code from each other. This would result to a class for the core logic, which works <em>synchronously</em>.</p>\n<p>This puts you into the position to test the core logic code in a <em>synchronous</em> way. You have absolute control over the timing of the calls you are doing on the core logic and thus can make <em>reproducible</em> tests. And this is your gain from separating core logic and asynchronous logic.</p>\n<p>This core logic needs be wrapped around by another class, which is responsible for receiving calls to the core logic asynchronously and <em>delegates</em> these calls to the core logic. Production code will only access the core logic via that class. Because this class should only delegate calls, it\'s a very &quot;dumb&quot; class without much logic. So you can keep your unit tests for this asychronous working class at a minimum.</p>\n<p>Anything above that (testing interaction between classes) are component tests. Also in this case, you should be able to have absolute control over timing, if you stick to the &quot;Humble Object&quot; pattern.</p>\n'}, {'answer_id': 671738, 'author': 'Paul Nathan', 'author_id': 26227, 'author_profile': 'https://Stackoverflow.com/users/26227', 'pm_score': 2, 'selected': False, 'text': '<p>I spent most of last week at a university library studying debugging of concurrent code. The central problem is concurrent code is non-deterministic. Typically, academic debugging has fallen into one of three camps here:</p>\n\n<ol>\n<li>Event-trace/replay. This requires an event monitor and then reviewing the events that were sent. In a UT framework, this would involve manually sending the events as part of a test, and then doing post-mortem reviews.</li>\n<li>Scriptable. This is where you interact with the running code with a set of triggers. "On x > foo, baz()". This could be interpreted into a UT framework where you have a run-time system triggering a given test on a certain condition.</li>\n<li>Interactive. This obviously won\'t work in an automatic testing situation. ;)</li>\n</ol>\n\n<p>Now, as above commentators have noticed, you can design your concurrent system into a more deterministic state. However, if you don\'t do that properly, you\'re just back to designing a sequential system again. </p>\n\n<p>My suggestion would be to focus on having a very strict design protocol about what gets threaded and what doesn\'t get threaded. If you constrain your interface so that there is minimal dependancies between elements, it is much easier.</p>\n\n<p>Good luck, and keep working on the problem.</p>\n'}, {'answer_id': 2345540, 'author': 'scim', 'author_id': 102153, 'author_profile': 'https://Stackoverflow.com/users/102153', 'pm_score': 3, 'selected': False, 'text': '<p>I handle unit tests of threaded components the same way I handle any unit test, that is, with inversion of control and isolation frameworks. I develop in the .Net-arena and, out of the box, the threading (among other things) is very hard (I\'d say nearly impossible) to fully isolate.</p>\n<p>Therefore, I\'ve written wrappers that looks something like this (simplified):</p>\n<pre class="lang-cs prettyprint-override"><code>public interface IThread\n{\n    void Start();\n    ...\n}\n\npublic class ThreadWrapper : IThread\n{\n    private readonly Thread _thread;\n     \n    public ThreadWrapper(ThreadStart threadStart)\n    {\n        _thread = new Thread(threadStart);\n    }\n\n    public Start()\n    {\n        _thread.Start();\n    }\n}\n    \npublic interface IThreadingManager\n{\n    IThread CreateThread(ThreadStart threadStart);\n}\n\npublic class ThreadingManager : IThreadingManager\n{\n    public IThread CreateThread(ThreadStart threadStart)\n    {\n         return new ThreadWrapper(threadStart)\n    }\n}\n</code></pre>\n<p>From there, I can easily inject the IThreadingManager into my components and use my isolation framework of choice to make the thread behave as I expect during the test.</p>\n<p>That has so far worked great for me, and I use the same approach for the thread pool, things in System.Environment, Sleep etc. etc.</p>\n'}, {'answer_id': 3203474, 'author': 'xagyg', 'author_id': 384464, 'author_profile': 'https://Stackoverflow.com/users/384464', 'pm_score': 4, 'selected': False, 'text': '<p>There are a few tools around that are quite good. Here is a summary of some of the Java ones.</p>\n\n<p>Some good static analysis tools include <a href="http://findbugs.sourceforge.net/" rel="noreferrer">FindBugs</a> (gives some useful hints), <a href="http://jlint.sourceforge.net/" rel="noreferrer">JLint</a>, <a href="http://babelfish.arc.nasa.gov/trac/jpf" rel="noreferrer">Java Pathfinder</a> (JPF &amp; JPF2), and <a href="http://bogor.projects.cis.ksu.edu/" rel="noreferrer">Bogor</a>.</p>\n\n<p><a href="http://code.google.com/p/multithreadedtc/" rel="noreferrer">MultithreadedTC</a> is quite a good dynamic analysis tool (integrated into JUnit) where you have to set up your own test cases.</p>\n\n<p><a href="https://www.research.ibm.com/haifa/projects/verification/contest/" rel="noreferrer">ConTest</a> from IBM Research is interesting. It instruments your code by inserting all kinds of thread modifying behaviours (e.g. sleep &amp; yield) to try to uncover bugs randomly.</p>\n\n<p><a href="http://spinroot.com/spin/whatispin.html" rel="noreferrer">SPIN</a> is a really cool tool for modelling your Java (and other) components, but you need to have some useful framework. It is hard to use as is, but extremely powerful if you know how to use it. Quite a few tools use SPIN underneath the hood.</p>\n\n<p>MultithreadedTC is probably the most mainstream, but some of the static analysis tools listed above are definitely worth looking at.</p>\n'}, {'answer_id': 4227668, 'author': 'Johan', 'author_id': 398441, 'author_profile': 'https://Stackoverflow.com/users/398441', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://github.com/awaitility/awaitility" rel="nofollow noreferrer">Awaitility</a> can also be useful to help you write deterministic unit tests. It allows you to wait until some state somewhere in your system is updated. For example:</p>\n<pre><code>await().untilCall( to(myService).myMethod(), greaterThan(3) );\n</code></pre>\n<p>or</p>\n<pre><code>await().atMost(5,SECONDS).until(fieldIn(myObject).ofType(int.class), equalTo(1));\n</code></pre>\n<p>It also has Scala and Groovy support.</p>\n<pre><code>await until { something() &gt; 4 } // Scala example\n</code></pre>\n'}, {'answer_id': 4615627, 'author': 'Toby', 'author_id': 233266, 'author_profile': 'https://Stackoverflow.com/users/233266', 'pm_score': 3, 'selected': False, 'text': '<p>Have a look at my related answer at</p>\n\n<p><a href="https://stackoverflow.com/questions/4418373/designing-a-test-class-for-a-custom-barrier/4427499#4427499">Designing a Test class for a custom Barrier</a></p>\n\n<p>It\'s biased towards Java but has a reasonable summary of the options. </p>\n\n<p>In summary though (IMO) its not the use of some fancy framework that will ensure correctness but how you go about designing you multithreaded code. Splitting the concerns (concurrency and functionality) goes a huge way towards raising confidence. <a href="http://www.amazon.co.uk/Growing-Object-Oriented-Software-Guided-Signature/dp/0321503627/ref=sr_1_1?ie=UTF8&amp;qid=1294321919&amp;sr=1-1" rel="nofollow noreferrer">Growing Object Orientated Software Guided By Tests</a> explains some options better than I can.</p>\n\n<p>Static analysis and formal methods (see, <a href="http://www.amazon.co.uk/gp/product/0470093552/" rel="nofollow noreferrer">Concurrency: State Models and Java Programs</a>) is an option but I\'ve found them to be of limited use in commercial development.</p>\n\n<p>Don\'t forget that any load/soak style tests are rarely guaranteed to highlight problems.</p>\n\n<p>Good luck!</p>\n'}, {'answer_id': 17465097, 'author': 'Dill', 'author_id': 126741, 'author_profile': 'https://Stackoverflow.com/users/126741', 'pm_score': -1, 'selected': False, 'text': "<p>(if possible) don't use threads, use actors / active objects. Easy to test.</p>\n"}, {'answer_id': 17973470, 'author': "Effi Bar-She'an", 'author_id': 2638505, 'author_profile': 'https://Stackoverflow.com/users/2638505', 'pm_score': 2, 'selected': False, 'text': '<p>The following article suggests 2 solutions. Wrapping a semaphore (CountDownLatch) and adds functionality like  externalize data from internal thread. Another way of achieving this purpose is to use Thread Pool (see Points of Interest).</p>\n\n<p><a href="http://www.codeproject.com/Articles/628843/Sprinkler-Advanced-synchronization-object#_rating" rel="nofollow">Sprinkler - Advanced synchronization object</a></p>\n'}, {'answer_id': 21090530, 'author': 'user590444', 'author_id': 590444, 'author_profile': 'https://Stackoverflow.com/users/590444', 'pm_score': -1, 'selected': False, 'text': '<p>You may use EasyMock.makeThreadSafe to make testing instance threadsafe</p>\n'}, {'answer_id': 23850131, 'author': 'feldoh', 'author_id': 513992, 'author_profile': 'https://Stackoverflow.com/users/513992', 'pm_score': 2, 'selected': False, 'text': '<p>I just recently discovered (for Java) a tool called Threadsafe. It is a static analysis tool much like findbugs but specifically to spot multi-threading issues. It is not a replacement for testing but I can recommend it as part of writing reliable multi-threaded Java.</p>\n\n<p>It even catches some very subtle potential issues around things like class subsumption, accessing unsafe objects through concurrent classes and spotting missing volatile modifiers when using the double checked locking paradigm.</p>\n\n<p>If you write multithreaded Java <a href="http://www.contemplateltd.com/threadsafe" rel="nofollow">give it a shot.</a></p>\n'}, {'answer_id': 25910372, 'author': 'bennidi', 'author_id': 1047493, 'author_profile': 'https://Stackoverflow.com/users/1047493', 'pm_score': 4, 'selected': False, 'text': '<p>Testing MT code for correctness is, as already stated, quite a hard problem. In the end it boils down to ensuring that there are no incorrectly synchronised data races in your code. The problem with this is that there are infinitely many possibilities of thread execution (interleavings) over which you do not have much control (be sure to read <a href="http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html" rel="noreferrer">this</a> article, though). In simple scenarios it might be possible to actually prove correctness by reasoning but this is usually not the case. Especially if you want to avoid/minimize synchronization and not go for the most obvious/easiest synchronization option.</p>\n\n<p>An approach that I follow is to write highly concurrent test code in order to make potentially undetected data races likely to occur. And then I run those tests for some time :) I once stumbled upon a talk where some computer scientist where showing off a tool that kind of does this (randomly devising test from specs and then running them wildly, concurrently, checking for the defined invariants to be broken).</p>\n\n<p>By the way, I think this aspect of testing MT code has not been mentioned here: identify invariants of the code that you can check for randomly. Unfortunately, finding those invariants is quite a hard problem, too. Also they might not hold all the time during execution, so you have to find/enforce executions points where you can expect them to be true. Bringing the code execution to such a state is also a hard problem (and might itself incur concurrency issues. Whew, it\'s damn hard!</p>\n\n<p>Some interesting links to read:</p>\n\n<ul>\n<li><a href="http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html" rel="noreferrer">Deterministic interleaving</a>: A framework that allows to force certain thread interleavings and then check for invariants</li>\n<li><a href="http://jmock.org/threading-blitzer.html" rel="noreferrer">jMock Blitzer </a> : Stress test synchronization</li>\n<li><a href="https://github.com/junit-team/junit/wiki/Multithreaded-code-and-concurrency" rel="noreferrer">assertConcurrent</a> : JUnit version of stress testing synronization</li>\n<li><a href="http://tempusfugitlibrary.org/recipes/2012/05/20/testing-concurrent-code/" rel="noreferrer">Testing concurrent code</a> : Short overview of the two primary methods of brute force (stress test) or deterministic (going for the invariants)</li>\n</ul>\n'}, {'answer_id': 32532047, 'author': 'Warren Dew', 'author_id': 2580516, 'author_profile': 'https://Stackoverflow.com/users/2580516', 'pm_score': 6, 'selected': False, 'text': "<p>I have faced this issue several times in recent years when writing thread handling code for several projects.  I'm providing a late answer because most of the other answers, while providing alternatives, do not actually answer the question about testing.  My answer is addressed to the cases where there is no alternative to multithreaded code; I do cover code design issues for completeness, but also discuss unit testing.</p>\n\n<p><strong>Writing testable multithreaded code</strong></p>\n\n<p>The first thing to do is to separate your production thread handling code from all the code that does actual data processing.  That way, the data processing can be tested as singly threaded code, and the only thing the multithreaded code does is to coordinate threads.</p>\n\n<p>The second thing to remember is that bugs in multithreaded code are probabilistic; the bugs that manifest themselves least frequently are the bugs that will sneak through into production, will be difficult to reproduce even in production, and will thus cause the biggest problems.  For this reason, the standard coding approach of writing the code quickly and then debugging it until it works is a bad idea for multithreaded code; it will result in code where the easy bugs are fixed and the dangerous bugs are still there.</p>\n\n<p>Instead, when writing multithreaded code, you must write the code with the attitude that you are going to avoid writing the bugs in the first place.  If you have properly removed the data processing code, the thread handling code should be small enough - preferably a few lines, at worst a few dozen lines - that you have a chance of writing it without writing a bug, and certainly without writing many bugs, if you understand threading, take your time, and are careful.</p>\n\n<p><strong>Writing unit tests for multithreaded code</strong></p>\n\n<p>Once the multithreaded code is written as carefully as possible, it is still worthwhile writing tests for that code.  The primary purpose of the tests is not so much to test for highly timing dependent race condition bugs - it's impossible to test for such race conditions repeatably - but rather to test that your locking strategy for preventing such bugs allows for multiple threads to interact as intended.</p>\n\n<p>To properly test correct locking behavior, a test must start multiple threads.  To make the test repeatable, we want the interactions between the threads to happen in a predictable order.  We don't want to externally synchronize the threads in the test, because that will mask bugs that could happen in production where the threads are not externally synchronized.  That leaves the use of timing delays for thread synchronization, which is the technique that I have used successfully whenever I've had to write tests of multithreaded code.</p>\n\n<p>If the delays are too short, then the test becomes fragile, because minor timing differences - say between different machines on which the tests may be run - may cause the timing to be off and the test to fail.  What I've typically done is start with delays that cause test failures, increase the delays so that the test passes reliably on my development machine, and then double the delays beyond that so the test has a good chance of passing on other machines.  This does mean that the test will take a macroscopic amount of time, though in my experience, careful test design can limit that time to no more than a dozen seconds.  Since you shouldn't have very many places requiring thread coordination code in your application, that should be acceptable for your test suite.</p>\n\n<p>Finally, keep track of the number of bugs caught by your test.  If your test has 80% code coverage, it can be expected to catch about 80% of your bugs.  If your test is well designed but finds no bugs, there's a reasonable chance that you don't have additional bugs that will only show up in production.  If the test catches one or two bugs, you might still get lucky.  Beyond that, and you may want to consider a careful review of or even a complete rewrite of your thread handling code, since it is likely that code still contains hidden bugs that will be very difficult to find until the code is in production, and very difficult to fix then.</p>\n"}, {'answer_id': 46414300, 'author': 'Red Rooster', 'author_id': 4289996, 'author_profile': 'https://Stackoverflow.com/users/4289996', 'pm_score': 0, 'selected': False, 'text': "<p>For J2E code, I've used SilkPerformer, LoadRunner and JMeter for concurrency testing of threads.  They all do the same thing.  Basically, they give you a relatively simple interface for administrating their version of the proxy server, required, in order to analyze the TCP/IP data stream, and simulate multiple users making simultaneous requests to your app server.  The proxy server can give you the ability to do things like analyze the requests made, by presenting the whole page and URL sent to the server, as well as the response from the server, after processing the request.</p>\n\n<p>You can find some bugs in insecure http mode, where you can at least analyze the form data that is being sent, and systematically alter that for each user.  But the true tests are when you run in https (Secured Socket Layers).  Then, you also have to contend with systematically altering the session and cookie data, which can be a little more convoluted.</p>\n\n<p>The best bug I ever found, while testing concurrency, was when I discovered that the developer had relied upon Java garbage collection to close the connection request that was established at login, to the LDAP server, when logging in.  This resulted in users being exposed to other users' sessions and very confusing results, when trying to analyze what happened when the server was brought to it's knees, barely able to complete one transaction, every few seconds.</p>\n\n<p>In the end, you or someone will probably have to buckle down and analyze the code for blunders like the one I just mentioned.  And an open discussion across departments, like the one that occurred, when we unfolded the problem described above, are most useful.  But these tools are the best solution to testing multi-threaded code.  JMeter is open source.  SilkPerformer and LoadRunner are proprietary.  If you really want to know whether your app is thread safe, that's how the big boys do it.  I've done this for very large companies professionally, so I'm not guessing.  I'm speaking from personal experience.</p>\n\n<p>A word of caution:  it does take some time to understand these tools.  It will not be a matter of simply installing the software and firing up the GUI, unless you've already had some exposure to multi-threaded programming.  I've tried to identify the 3 critical categories of areas to understand (forms, session and cookie data), with the hope that at least starting with understanding these topics will help you focus on quick results, as opposed to having to read through the entire documentation.</p>\n"}, {'answer_id': 49736681, 'author': 'Avraham Shalev', 'author_id': 4516910, 'author_profile': 'https://Stackoverflow.com/users/4516910', 'pm_score': -1, 'selected': False, 'text': '<p>If you are testing simple <em>new Thread(runnable).run()</em>\nYou can mock Thread to run the runnable sequentially</p>\n\n<p>For instance, if the code of the tested object invokes a new thread like this</p>\n\n<pre><code>Class TestedClass {\n    public void doAsychOp() {\n       new Thread(new myRunnable()).start();\n    }\n}\n</code></pre>\n\n<p>Then mocking new Threads and run the runnable argument sequentially can help</p>\n\n<pre><code>@Mock\nprivate Thread threadMock;\n\n@Test\npublic void myTest() throws Exception {\n    PowerMockito.mockStatic(Thread.class);\n    //when new thread is created execute runnable immediately \n    PowerMockito.whenNew(Thread.class).withAnyArguments().then(new Answer&lt;Thread&gt;() {\n        @Override\n        public Thread answer(InvocationOnMock invocation) throws Throwable {\n            // immediately run the runnable\n            Runnable runnable = invocation.getArgumentAt(0, Runnable.class);\n            if(runnable != null) {\n                runnable.run();\n            }\n            return threadMock;//return a mock so Thread.start() will do nothing         \n        }\n    }); \n    TestedClass testcls = new TestedClass()\n    testcls.doAsychOp(); //will invoke myRunnable.run in current thread\n    //.... check expected \n}\n</code></pre>\n'}, {'answer_id': 50943298, 'author': 'Mohan Radhakrishnan', 'author_id': 1234909, 'author_profile': 'https://Stackoverflow.com/users/1234909', 'pm_score': 0, 'selected': False, 'text': '<p>Concurrency is a complex interplay between the memory model, hardware, caches and our code. In the case of Java at least such tests have been partly addressed mainly by <a href="https://wiki.openjdk.java.net/display/CodeTools/jcstress" rel="nofollow noreferrer">jcstress</a>. The creators of that library are known to be authors of many JVM, GC and Java concurrency features.</p>\n\n<p>But even this library needs good knowledge of the Java Memory Model specification so that we know exactly what we are testing. But I think the focus of this effort is mircobenchmarks. Not huge business applications.</p>\n'}, {'answer_id': 55276976, 'author': 'KolA', 'author_id': 1553641, 'author_profile': 'https://Stackoverflow.com/users/1553641', 'pm_score': 1, 'selected': False, 'text': '<p>Assuming under "multi-threaded" code was meant something that is </p>\n\n<ul>\n<li>stateful and mutable</li>\n<li>AND accessed/modified by multiple threads\nconcurrently</li>\n</ul>\n\n<p>In other words we are talking about testing <strong>custom stateful thread-safe class/method/unit</strong> - which should be a very rare beast nowadays.</p>\n\n<p>Because this beast is rare, first of all we need to make sure that there are all valid excuses to write it.</p>\n\n<p><strong>Step 1.</strong> Consider modifying state in same synchronization context.</p>\n\n<p>Today it is easy to write compose-able concurrent and asynchronous code where IO or other slow operations offloaded to background but shared state is updated and queried in one synchronization context. e.g. async/await tasks and Rx in .NET etc. - they are all testable by design, "real" Tasks and schedulers can be substituted to make testing deterministic (however this is out of scope of the question). </p>\n\n<p>It may sound very constrained but this approach works surprisingly well. It is possible to write whole apps in this style without need to make any state thread-safe (I do).</p>\n\n<p><strong>Step 2.</strong> If manipulating of shared state on single synchronization context is absolutely not possible. </p>\n\n<p>Make sure the wheel is not being reinvented / there\'s definitely no standard alternative that can be adapted for the job. It should be likely that code is very cohesive and contained within one unit e.g. with a good chance it is a special case of some standard thread-safe data structure like hash map or collection or whatever.</p>\n\n<p><em>Note: if code is large / spans across multiple classes AND needs multi-thread state manipulation then there\'s a very high chance that design is not good, reconsider Step 1</em> </p>\n\n<p><strong>Step 3.</strong> If this step is reached then we need to test <strong>our own custom stateful thread-safe class/method/unit</strong>.</p>\n\n<p>I\'ll be dead honest : I never had to write proper tests for such code. Most of the time I get away at Step 1, sometimes at Step 2. Last time I had to write custom thread-safe code was so many years ago that it was before I adopted unit testing / probably I wouldn\'t have to write it with the current knowledge anyway.</p>\n\n<p>If I really had to test such code (<strong>finally, actual answer</strong>) then I would try couple of things below</p>\n\n<ol>\n<li><p>Non-deterministic stress testing. e.g. run 100 threads simultaneously and check that end result is consistent.\nThis is more typical for higher level / integration testing of multiple users scenarios but also can be used at the unit level.</p></li>\n<li><p>Expose some test \'hooks\' where test can inject some code to help make deterministic scenarios where one thread must perform operation before the other.\nAs ugly as it is, I can\'t think of anything better.</p></li>\n<li><p>Delay-driven testing to make threads run and perform operations in particular order. Strictly speaking such tests are non-deterministic too (there\'s a chance of system freeze / stop-the-world GC collection which can distort otherwise orchestrated delays), also it is ugly but allows to avoid hooks.</p></li>\n</ol>\n'}, {'answer_id': 61472502, 'author': 'gterzian', 'author_id': 2063091, 'author_profile': 'https://Stackoverflow.com/users/2063091', 'pm_score': 0, 'selected': False, 'text': '<p>There is an article on the topic, using Rust as the language in the example code:</p>\n\n<p><a href="https://medium.com/@polyglot_factotum/rust-concurrency-five-easy-pieces-871f1c62906a" rel="nofollow noreferrer">https://medium.com/@polyglot_factotum/rust-concurrency-five-easy-pieces-871f1c62906a</a></p>\n\n<p>In summary, the trick is to write your concurrent logic so that it is robust to the non-determinism involved with multiple threads of execution, using tools like channels and condvars. </p>\n\n<p>Then, if that is how you\'ve structured your "components", the easiest way to test them is by using channels to send messages to them, and then block on other channels to assert that the component sends certain expected messages. </p>\n\n<p>The linked-to article is fully written using unit-tests.</p>\n'}, {'answer_id': 65727155, 'author': 'Tim', 'author_id': 5703407, 'author_profile': 'https://Stackoverflow.com/users/5703407', 'pm_score': 0, 'selected': False, 'text': "<p>It's not perfect, but I wrote this helper for my tests in C#:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Proto.Promises.Tests.Threading\n{\n    public class ThreadHelper\n    {\n        public static readonly int multiThreadCount = Environment.ProcessorCount * 100;\n        private static readonly int[] offsets = new int[] { 0, 10, 100, 1000 };\n\n        private readonly Stack&lt;Task&gt; _executingTasks = new Stack&lt;Task&gt;(multiThreadCount);\n        private readonly Barrier _barrier = new Barrier(1);\n        private int _currentParticipants = 0;\n        private readonly TimeSpan _timeout;\n\n        public ThreadHelper() : this(TimeSpan.FromSeconds(10)) { } // 10 second timeout should be enough for most cases.\n\n        public ThreadHelper(TimeSpan timeout)\n        {\n            _timeout = timeout;\n        }\n\n        /// &lt;summary&gt;\n        /// Execute the action multiple times in parallel threads.\n        /// &lt;/summary&gt;\n        public void ExecuteMultiActionParallel(Action action)\n        {\n            for (int i = 0; i &lt; multiThreadCount; ++i)\n            {\n                AddParallelAction(action);\n            }\n            ExecutePendingParallelActions();\n        }\n\n        /// &lt;summary&gt;\n        /// Execute the action once in a separate thread.\n        /// &lt;/summary&gt;\n        public void ExecuteSingleAction(Action action)\n        {\n            AddParallelAction(action);\n            ExecutePendingParallelActions();\n        }\n\n        /// &lt;summary&gt;\n        /// Add an action to be run in parallel.\n        /// &lt;/summary&gt;\n        public void AddParallelAction(Action action)\n        {\n            var taskSource = new TaskCompletionSource&lt;bool&gt;();\n            lock (_executingTasks)\n            {\n                ++_currentParticipants;\n                _barrier.AddParticipant();\n                _executingTasks.Push(taskSource.Task);\n            }\n            new Thread(() =&gt;\n            {\n                try\n                {\n                    _barrier.SignalAndWait(); // Try to make actions run in lock-step to increase likelihood of breaking race conditions.\n                    action.Invoke();\n                    taskSource.SetResult(true);\n                }\n                catch (Exception e)\n                {\n                    taskSource.SetException(e);\n                }\n            }).Start();\n        }\n\n        /// &lt;summary&gt;\n        /// Runs the pending actions in parallel, attempting to run them in lock-step.\n        /// &lt;/summary&gt;\n        public void ExecutePendingParallelActions()\n        {\n            Task[] tasks;\n            lock (_executingTasks)\n            {\n                _barrier.SignalAndWait();\n                _barrier.RemoveParticipants(_currentParticipants);\n                _currentParticipants = 0;\n                tasks = _executingTasks.ToArray();\n                _executingTasks.Clear();\n            }\n            try\n            {\n                if (!Task.WaitAll(tasks, _timeout))\n                {\n                    throw new TimeoutException($&quot;Action(s) timed out after {_timeout}, there may be a deadlock.&quot;);\n                }\n            }\n            catch (AggregateException e)\n            {\n                // Only throw one exception instead of aggregate to try to avoid overloading the test error output.\n                throw e.Flatten().InnerException;\n            }\n        }\n\n        /// &lt;summary&gt;\n        /// Run each action in parallel multiple times with differing offsets for each run.\n        /// &lt;para/&gt;The number of runs is 4^actions.Length, so be careful if you don't want the test to run too long.\n        /// &lt;/summary&gt;\n        /// &lt;param name=&quot;expandToProcessorCount&quot;&gt;If true, copies each action on additional threads up to the processor count. This can help test more without increasing the time it takes to complete.\n        /// &lt;para/&gt;Example: 2 actions with 6 processors, runs each action 3 times in parallel.&lt;/param&gt;\n        /// &lt;param name=&quot;setup&quot;&gt;The action to run before each parallel run.&lt;/param&gt;\n        /// &lt;param name=&quot;teardown&quot;&gt;The action to run after each parallel run.&lt;/param&gt;\n        /// &lt;param name=&quot;actions&quot;&gt;The actions to run in parallel.&lt;/param&gt;\n        public void ExecuteParallelActionsWithOffsets(bool expandToProcessorCount, Action setup, Action teardown, params Action[] actions)\n        {\n            setup += () =&gt; { };\n            teardown += () =&gt; { };\n            int actionCount = actions.Length;\n            int expandCount = expandToProcessorCount ? Math.Max(Environment.ProcessorCount / actionCount, 1) : 1;\n            foreach (var combo in GenerateCombinations(offsets, actionCount))\n            {\n                setup.Invoke();\n                for (int k = 0; k &lt; expandCount; ++k)\n                {\n                    for (int i = 0; i &lt; actionCount; ++i)\n                    {\n                        int offset = combo[i];\n                        Action action = actions[i];\n                        AddParallelAction(() =&gt;\n                        {\n                            for (int j = offset; j &gt; 0; --j) { } // Just spin in a loop for the offset.\n                            action.Invoke();\n                        });\n                    }\n                }\n                ExecutePendingParallelActions();\n                teardown.Invoke();\n            }\n        }\n\n        // Input: [1, 2, 3], 3\n        // Ouput: [\n        //          [1, 1, 1],\n        //          [2, 1, 1],\n        //          [3, 1, 1],\n        //          [1, 2, 1],\n        //          [2, 2, 1],\n        //          [3, 2, 1],\n        //          [1, 3, 1],\n        //          [2, 3, 1],\n        //          [3, 3, 1],\n        //          [1, 1, 2],\n        //          [2, 1, 2],\n        //          [3, 1, 2],\n        //          [1, 2, 2],\n        //          [2, 2, 2],\n        //          [3, 2, 2],\n        //          [1, 3, 2],\n        //          [2, 3, 2],\n        //          [3, 3, 2],\n        //          [1, 1, 3],\n        //          [2, 1, 3],\n        //          [3, 1, 3],\n        //          [1, 2, 3],\n        //          [2, 2, 3],\n        //          [3, 2, 3],\n        //          [1, 3, 3],\n        //          [2, 3, 3],\n        //          [3, 3, 3]\n        //        ]\n        private static IEnumerable&lt;int[]&gt; GenerateCombinations(int[] options, int count)\n        {\n            int[] indexTracker = new int[count];\n            int[] combo = new int[count];\n            for (int i = 0; i &lt; count; ++i)\n            {\n                combo[i] = options[0];\n            }\n            // Same algorithm as picking a combination lock.\n            int rollovers = 0;\n            while (rollovers &lt; count)\n            {\n                yield return combo; // No need to duplicate the array since we're just reading it.\n                for (int i = 0; i &lt; count; ++i)\n                {\n                    int index = ++indexTracker[i];\n                    if (index == options.Length)\n                    {\n                        indexTracker[i] = 0;\n                        combo[i] = options[0];\n                        if (i == rollovers)\n                        {\n                            ++rollovers;\n                        }\n                    }\n                    else\n                    {\n                        combo[i] = options[index];\n                        break;\n                    }\n                }\n            }\n        }\n    }\n}\n</code></pre>\n<p>Example usage:</p>\n<pre><code>[Test]\npublic void DeferredMayBeBeResolvedAndPromiseAwaitedConcurrently_void0()\n{\n    Promise.Deferred deferred = default(Promise.Deferred);\n    Promise promise = default(Promise);\n\n    int invokedCount = 0;\n\n    var threadHelper = new ThreadHelper();\n    threadHelper.ExecuteParallelActionsWithOffsets(false,\n        // Setup\n        () =&gt;\n        {\n            invokedCount = 0;\n            deferred = Promise.NewDeferred();\n            promise = deferred.Promise;\n        },\n        // Teardown\n        () =&gt; Assert.AreEqual(1, invokedCount),\n        // Parallel Actions\n        () =&gt; deferred.Resolve(),\n        () =&gt; promise.Then(() =&gt; { Interlocked.Increment(ref invokedCount); }).Forget()\n    );\n}\n</code></pre>\n"}, {'answer_id': 73224125, 'author': 'mercury0114', 'author_id': 4929809, 'author_profile': 'https://Stackoverflow.com/users/4929809', 'pm_score': 0, 'selected': False, 'text': '<p>One simple test pattern that can work for <strong>some (not all!)</strong> cases is to repeat the same test many times. For example, suppose you have a method:</p>\n<pre><code>def process(input):\n    # Spawns several threads to do the job\n    # ...\n    return output\n</code></pre>\n<p>Create a bunch of tests:</p>\n<pre><code>process(input1) -&gt; expect to return output1\nprocess(input2) -&gt; expect to return output2\n...\n</code></pre>\n<p>Now run each of those tests many times.</p>\n<p>If the implementation of <code>process</code> contains a subtle bug (e.g. deadlock, race condition, etc.) that has 0.1% chance to emerge, running the test 1000 times gives 64% probability for the bug to emerge at least once. Running the test 10000 times gives &gt;99% probability.</p>\n'}, {'answer_id': 74574386, 'author': 'Mike Nakis', 'author_id': 773113, 'author_profile': 'https://Stackoverflow.com/users/773113', 'pm_score': 0, 'selected': False, 'text': "<p>Running multiple threads is not difficult; it is piece of cake. Unfortunately, threads usually need to communicate with each other; that's what's difficult.</p>\n<p>The mechanism that was originally invented to allow communication between modules was function calls; when module A wants to communicate with module B, it just invokes a function in module B. Unfortunately, this does not work with threads, because when you call a function, that function still runs in the current thread.</p>\n<p>To overcome this problem, people decided to fall back to an even more primitive mechanism of communication: just declare a certain variable, and let both threads have access to that variable. In other words, allow the threads to share data. Sharing data is literally the first thing that naturally comes to mind, and it appears like a good choice because it seems very simple. I mean, how hard can it be, right? What could possibly go wrong?</p>\n<p>Race conditions. That's what can, and will, go wrong.</p>\n<p>When people realized their software was suffering from random, non-reproducible catastrophic failures due to race conditions, they started inventing elaborate mechanisms such as locks and compare-and-swap, aiming to protect against such things happening. These mechanisms fall under the broad category of &quot;synchronization&quot;. Unfortunately, synchronization has two problems:</p>\n<ol>\n<li>It is very difficult to get it right, so it is very prone to bugs.</li>\n<li>It is completely untestable, because you cannot test for a race condition.</li>\n</ol>\n<p>The astute reader might notice that &quot;Very prone to bugs&quot; and &quot;Completely untestable&quot; is a <em><strong>deadly combination</strong></em>.</p>\n<p>Now, the mechanisms I mentioned above were being invented and adopted by large parts of the industry before the concept of automated software testing became prevalent; So, nobody could see how deadly the problem was; they just regarded it as a difficult topic which requires guru programmers, and everyone was okay with that.</p>\n<p>Nowadays, whatever we do, we put testing first. So, if some mechanism is untestable, then the use of that mechanism is just out of the question, period. Thus, synchronization has fallen out of grace; very few people still practice it, and they are becoming fewer and fewer every day.</p>\n<p>Without synchronization threads cannot share data; however, the original requirement was not to share data; it was to allow threads to communicate with each other. Besides sharing data, there exist other, more elegant mechanisms for inter-thread communication.</p>\n<p>One such mechanism is message-passing, otherwise known as events.</p>\n<p>With message passing, there is only one place in the entire software system which utilizes synchronization, and that is the concurrent blocking queue collection class that we use for storing messages. (The idea is that we should be able to get at least that little part right.)</p>\n<p>The great thing about message passing is that it does not suffer from race conditions and is fully testable.</p>\n"}]
['https://Stackoverflow.com/questions/12159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/912/']