Forum Discussion

augeva's avatar
augeva
New Contributor
13 years ago

[Resolved] Mock logic can't handle multiple threads

Hi all,

I have been happily using a mock service that dispatches different responses using script for over a year but this time I seem to have hit an obstacle I can't get around.

The problem occurs when my application fires 2 requests in parallel.
In this case the results are inconsistent.

My script does something like this:

if (condition1) {
return "Response1"
}
if (condition2){
return "Response2"
}

}


My application might fire 2 requests in parallel the first one satisfying condition1, and the second say condition2
At this point I expect Response1 and Response2 both to be returned but the actual result is that I randomly receive either Response1 or Response2 or both of them.

I believe the issue might be the fact that multiple threads are run at the same time in the script and this causes problems, is there any way I can make the groovy script thread safe? I tried using

synchronized(this){
%MYSCRIPT%
}

But it didn't work :-(

Any help would be strongly appreciated.

Best Regards,

Augusto
  • Hi!

    synchronized(this){
    %MYSCRIPT%
    }


    MockServices are thread-safe. But you need to synchronize on shared objects, e.g.

    synchronized( testRunner.testCase.testSuite.project ){
    %MYSCRIPT%
    }


    You could also create atomicvariables (like AtomicBoolean) in the MockService's startUp script:
    context.myVariable = new AtomicBoolean()

    ...and then use it later on like this:
    context.myVariable.get()


    Regards

    Henrik
    SmartBear Software
  • augeva's avatar
    augeva
    New Contributor
    Thanks for the suggestions guys.

    synchronized(this){
    %MYSCRIPT%
    }

    didn't work for us as I mentioned in the original message but we found a workaround that fixed the issue.
    If you are interested in investigating the issue further I can privately share my code with you.

    Our workaround involves changing the dispatch logic to call separate mock responses, isolating 2 differently named "context.myVariable" in 2 separate mock responses injecting one variable per response.

    Thanks again for the support,

    Augusto
  • Hi again!

    You do not want to do:

    synchronized(this){
    %MYSCRIPT%
    }


    as this refers to the script instance, which will differ for each thread.

    For example, running a load test at a MockService with this dispatch script:
    log.info ("hello, this is "+this)

    ...will result in:
    Wed May 23 10:57:43 CEST 2012:INFO:hello, this is Script3@1e9668d
    Wed May 23 10:57:43 CEST 2012:INFO:hello, this is Script1@a3e85e


    What you instead do want to do is to synchronize on something that the threads have in common, e.g. the MockService object:
    synchronized(mockRequest.context.mockService){
    %MYSCRIPT%
    }


    Regards

    Henrik
    SmartBear Software