jfairy icon indicating copy to clipboard operation
jfairy copied to clipboard

Document thread safety

Open nurkiewicz opened this issue 7 years ago • 2 comments

Please document if the library is thread-safe. I'm generating millions of test samples and want to know if I can safely reuse the same instance across threads. Also during prototyping, I use Fairy object as a Spring singleton bean - is it safe as well?

Another question - if I create hundreds of Fairy instances in quick succession, will they produce different samples? Or maybe (due to the same random seed maybe?) I'll get duplicates?

nurkiewicz avatar Dec 08 '17 08:12 nurkiewicz

I think that the library is thread-safe. It uses java.util.Random which is thread-safe. However, documentation of Random class says that when it is used by multiple threads, the performance would be better for one Random instance per thread.

When you create hundreds of Fairy instances in quick succession and you do not provide seed with withRandomSeed, they still should properly return random results. The reason is that, java.util.Random by default initialized seed with: seedUniquifier() ^ System.nanoTime().

I think that when you need to use this library by multiple threads and the performance matters, you should create Fairy instance per thread. Each instance should be created by different Bootstrap.Builder (or by calling create). If you try to use the same builder to build multiple Fairy instances, they will share java.util.Random which will yield poor multi-thread performance.

kdebski85 avatar Mar 05 '20 10:03 kdebski85

Upon further investigation, I found out that some parts of the library are not thread safe. For example, TextProducer has limit variable that can be changed and it is accessed twice in result method. TextProducerInternal also shuffles words collection that can be accessed by multiple threads.

I think that we should state in the README that each thread should use its own Fairy object.

kdebski85 avatar Mar 06 '20 10:03 kdebski85