/*
 * Copyright (c) 2007 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */
package org.mockito.internal.stubbing;

import java.io.Serializable;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.DescribedInvocation;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.invocation.MatchableInvocation;
import org.mockito.quality.Strictness;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Stubbing;

@SuppressWarnings("unchecked")
public class StubbedInvocationMatcher extends InvocationMatcher implements Serializable, Stubbing {

    private static final long serialVersionUID = 4919105134123672727L;
    private final Queue<Answer> answers = new ConcurrentLinkedQueue<Answer>();
    private final Strictness strictness;
    private DescribedInvocation usedAt;

    public StubbedInvocationMatcher(
            Answer answer, MatchableInvocation invocation, Strictness strictness) {
        super(invocation.getInvocation(), invocation.getMatchers());
        this.strictness = strictness;
        this.answers.add(answer);
    }

    public Object answer(InvocationOnMock invocation) throws Throwable {
        // see ThreadsShareGenerouslyStubbedMockTest
        Answer a;
        synchronized (answers) {
            a = answers.size() == 1 ? answers.peek() : answers.poll();
        }
        return a.answer(invocation);
    }

    public void addAnswer(Answer answer) {
        answers.add(answer);
    }

    public void markStubUsed(DescribedInvocation usedAt) {
        this.usedAt = usedAt;
    }

    public boolean wasUsed() {
        return usedAt != null;
    }

    @Override
    public String toString() {
        return super.toString() + " stubbed with: " + answers;
    }

    @Override
    public Strictness getStrictness() {
        return strictness;
    }
}

@@ -899,24 +899,77 @@
 strictness;%0A
+    private final Object usedAtLock = new Object%5B0%5D;%0A
     private 
@@ -1702,24 +1702,64 @@
 n usedAt) %7B%0A
+        synchronized (usedAtLock) %7B%0A    
         this
@@ -1776,16 +1776,26 @@
 usedAt;%0A
+        %7D%0A
     %7D%0A%0A 
@@ -1820,24 +1820,64 @@
 wasUsed() %7B%0A
+        synchronized (usedAtLock) %7B%0A    
         retu
@@ -1895,16 +1895,26 @@
 = null;%0A
+        %7D%0A
     %7D%0A%0A 

Fix thread race condition (#2248)