Testing thread safety fails with Spock
<h1>The subject</h1>

<p>I have some code that is decidedly not thread safe:</p>

<pre><code>public class ExampleLoader
{
    private List&lt;String&gt; strings;

    protected List&lt;String&gt; loadStrings()
    {
        return Arrays.asList("Hello", "World", "Sup");
    }

    public List&lt;String&gt; getStrings()
    {
        if (strings == null)
        {
            strings = loadStrings();
        }

        return strings;
    }
}
</code></pre>

<p>Multiple threads accessing <code>getStrings()</code> simultaneously are expected to see <code>strings</code> as <code>null</code>, and thus <code>loadStrings()</code> (which is an expensive operation) is triggered multiple times.</p>

<h1>The problem</h1>

<p>I wanted to make the code thread safe, and as a good citizen of the world I wrote a failing Spock spec first:</p>

<pre><code>def "getStrings is thread safe"() {
    given:
    def loader = Spy(ExampleLoader)
    def threads = (0..&lt;10).collect { new Thread({ loader.getStrings() })}

    when:
    threads.each { it.start() }
    threads.each { it.join() }

    then:
    1 * loader.loadStrings()
}
</code></pre>

<p>The above code creates and starts 10 threads that each calls <code>getStrings()</code>. It then asserts that <code>loadStrings()</code> was called only once when all threads are done.</p>

<p>I expected this to fail. However, it consistently passes. What?</p>

<p>After a debugging session involving <code>System.out.println</code> and other boring things, I found that the threads are indeed asynchronous: their <code>run()</code> methods printed in a seemingly random order. However, the first thread to access <code>getStrings()</code> would <em>always</em> be the <em>only</em> thread to call <code>loadStrings()</code>.</p>

<h1>The weird part</h1>

<p>Frustrated after quite some time spent debugging, I wrote the same test again with JUnit 4 and Mockito:</p>

<pre><code>@Test
public void getStringsIsThreadSafe() throws Exception
{
    // given
    ExampleLoader loader = Mockito.spy(ExampleLoader.class);
    List&lt;Thread&gt; threads = IntStream.range(0, 10)
            .mapToObj(index -&gt; new Thread(loader::getStrings))
            .collect(Collectors.toList());

    // when
    threads.forEach(Thread::start);
    threads.forEach(thread -&gt; {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    // then
    Mockito.verify(loader, Mockito.times(1))
            .loadStrings();
}
</code></pre>

<p>This test consistently fails due to multiple calls to <code>loadStrings()</code>, as was expected.</p>

<h1>The question</h1>

<p>Why does the Spock test consistently pass, and how would I go about testing this with Spock?</p>