podam icon indicating copy to clipboard operation
podam copied to clipboard

Make Podam thread-safe

Open mtedone opened this issue 11 years ago • 13 comments

Multiple instances of Podam must be able to run within the same JVM without affecting each other's results.

mtedone avatar May 16 '15 17:05 mtedone

Just make separate instances of PodamFactory and DataProviderStrategy per thread and it's safe.

daivanov avatar May 16 '15 18:05 daivanov

Invoking the PodamFactoryImpl constructor should create a new instance of the DataProviderStrategy. If it does it, it’s safe, otherwise it needs to do it. For example, RandomDataProviderStrategy should not be a singleton.

On 16 May 2015, at 19:15, Daniil Ivanov [email protected] wrote:

Just make separate instance of PodamFactory and DataProviderStrategy per thread and it's safe.

— Reply to this email directly or view it on GitHub https://github.com/mtedone/podam/issues/102#issuecomment-102662239.

mtedone avatar May 16 '15 18:05 mtedone

Changing RandomDataProviderStrategy to non-singleton won't fix thread safety in Podam. If someone shares factory between multiple threads this won't change anything comparing to having singleton strategy.

daivanov avatar May 16 '15 18:05 daivanov

Good point. So first we need to make the instance variables of RandomDataProviderStrategy thread-safe, e.g. by substituting HashMaps with ConcurrentHashMaps for instance and providing thread-safety when adding/removing/updating elements in those collections. Apart from the maps defined in AbstractRandomDataProviderStrategy, there’s nothing else that is stageful. So also RandomDataProviderStrategy should be thread-safe. Since this is the only implementation of DataProviderStrategy, once this has been fixed, Podam should be thread-safe.

Regards, M.

On 16 May 2015, at 19:34, Daniil Ivanov [email protected] wrote:

Changing RandomDataProviderStrategy to non-singleton won't fix thread safety in Podam. If someone shares factory between multiple threads this won't change anything comparing to having singleton strategy.

— Reply to this email directly or view it on GitHub https://github.com/mtedone/podam/issues/102#issuecomment-102664691.

mtedone avatar May 16 '15 18:05 mtedone

The test could be to fire off multiple PodamFactoryImpl instances with memoization set to true for the same type and all results should be different.

On 16 May 2015, at 19:34, Daniil Ivanov [email protected] wrote:

Changing RandomDataProviderStrategy to non-singleton won't fix thread safety in Podam. If someone shares factory between multiple threads this won't change anything comparing to having singleton strategy.

— Reply to this email directly or view it on GitHub https://github.com/mtedone/podam/issues/102#issuecomment-102664691.

mtedone avatar May 16 '15 18:05 mtedone

Daniil, are you working on this or shall I do it?

mtedone avatar May 18 '15 20:05 mtedone

No, I'm not, you can do it.

daivanov avatar May 19 '15 07:05 daivanov

Made Podam thread-safe. AbstractRandomProviderStrategy should really have putIfAbsent but on the cloud box on Jenkins this throws some errors, whereas on my box it runs fine. I guess it has to do with JDK versions (they've only got 7 as the latest). Introduced BDD testing to test multiple threads requesting the same POJO and returning different values although memoization is set to true.

mtedone avatar May 19 '15 23:05 mtedone

AbstractRandomDataProviderStrategy.getMemoizedObject() and AbstractRandomDataProviderStrategy.cacheMemoizedObject() are not thread safe.

daivanov avatar May 20 '15 02:05 daivanov

The test could be to fire off multiple PodamFactoryImpl instances with memoization set to true for the same type and all results should be different.

If memoization works correctly all results must be the same. If they are different, it means memoization is broken.

daivanov avatar May 20 '15 02:05 daivanov

That's not correct. The memoization table is an instance variable

private final Map<Class, Map<Type[], Object>> memoizationTable = new ConcurrentHashMap<Class, Map<Type[], Object>>();

Therefore since each creation of PodamFactoryImpl also creates a new instance of RandomDataProviderStrategy different threads of execution should lead to different values.

AbstractRandomDataProviderStrategy.getMemoizedObject() and AbstractRandomDataProviderStrategy.cacheMemoizedObject() are thread safe as they use only thread-safe structures and local variables.

mtedone avatar May 20 '15 05:05 mtedone

With singleton factory it was like that:

thread -> PodamFactoryImpl \
                            -> Strategy
thread -> PodamFactoryImpl /

You changed it to be like this

thread -> PodamFactoryImpl -> Strategy
thread -> PodamFactoryImpl -> Strategy

Here threads are not sharing any data.

But if several threads do share the data, problem remains:

thread \
        -> PodamFactoryImpl-> Strategy
thread /

daivanov avatar May 20 '15 12:05 daivanov

I'm afraid that's not correct, as the following output from a branch created from commit c2ede20 demonstrates:

Processing system properties {} Using controls EmbedderControls[batch=false,skip=false,generateViewAfterStories=true,ignoreFailureInStories=false,ignoreFailureInView=true,verboseFailures=false,verboseFiltering=false,storyTimeoutInSecs=60,failOnStoryTimeout=false,threads=1]

(BeforeStories)

Running story uk.co.jemos.podam.bdd.stories/podam-factory-thread-safety.story

(uk.co.jemos.podam.bdd.stories/podam-factory-thread-safety.story) Scenario: Running one factory should return a filled in POJO Given I have a Podam Factory When I invoke Podam Then The returned POJO should not be null And The returned POJO should have some fields filled in with data

Scenario: Running multiple factories should lead to different results
 Given I have an executor service with 2 threads and a callable which returns a String When I invoke the executor service for each thread 2015-05-20 22:20:25 PodamFactoryThreadSafeSteps [INFO] SimplePojoToTestSetters ( stringField = pDLDuPnGoh intField = -1059743143 ) 2015-05-20 22:20:25 PodamFactoryThreadSafeSteps [INFO] SimplePojoToTestSetters ( stringField = pDLDuPnGoh intField = -1059743143 ) And I retrieve the results Then I should receive 2 distinct results (FAILED) (java.lang.AssertionError: There should be two different objects in the Set!)

(AfterStories)

Generating reports view to '/Users/tedonema/dev/podam/target/jbehave' using formats '[stats, console, txt, html, xml]' and view properties '{navigator=ftl/jbehave-navigator.ftl, views=ftl/jbehave-views.ftl, reports=ftl/jbehave-reports-with-totals.ftl, nonDecorated=ftl/jbehave-report-non-decorated.ftl, decorated=ftl/jbehave-report-decorated.ftl, maps=ftl/jbehave-maps.ftl}'

org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories: org.jbehave.core.embedder.PerformableTree$SomethingHappened@79d59476: java.lang.AssertionError: There should be two different objects in the Set! at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handleFailures(Embedder.java:530) at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:229) at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:207) at org.jbehave.core.junit.JUnitStories.run(JUnitStories.java:20) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41) at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.junit.runners.ParentRunner.run(ParentRunner.java:220) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

You can see above that even if there are two factories, the objects returned are the same, and that violates the "independent state" that each factory should have. It's maybe easier to think of that as:

Factory -> Unique POJO

And that's the contract that Podam should offer to its users.

If you look at the steps for this story, you'll see the following:

PodamFactoryInvocatorCallable callable1 = new PodamFactoryInvocatorCallable(new PodamFactoryImpl()); FutureTask future1 = new FutureTask(callable1); PodamFactoryInvocatorCallable callable2 = new PodamFactoryInvocatorCallable(new PodamFactoryImpl()); FutureTask future2 = new FutureTask(callable2);

This scenario is:

thread -> new PodamFactoryImpl
-> One strategy thread -> new PodamFactoryImpl /

This was normal before the change, since the strategy was a singleton therefore, regardless whether two PodamFactoryImpl instances were created, the underlying object was the same (defined as static variable in RandomDataProviderStrategy).

My fix addresses this problem by guaranteeing that each instance of PodamFactoryImpl has got its own blueprint of data, as it should be.

If several threads share one factory, then they're agreeing to use the same data blueprint, therefore the same object should be expected. Podam now, though, guarantees that there won't be race conditions when reading/writing instance variables on the strategy. However, as much as a rare case that would be, clients sharing a factory (and therefore a strategy) should synchronise on how to change the strategy state. That's responsibility of the clients, not Podam.

This issue is closed, please don't reopen it again.

mtedone avatar May 20 '15 21:05 mtedone