Is NRule Thread Safe?

343 views
Skip to first unread message

Zack Jones

unread,
May 6, 2015, 11:40:35 PM5/6/15
to nrules...@googlegroups.com
I notice a lot of static classes in the source.  Is NRule thread safe?  I am thinking in terms of high-volume, web-based activity...


Sergiy Nikolayev

unread,
May 7, 2015, 12:23:25 AM5/7/15
to nrules...@googlegroups.com
Hi Zack,

The static classes you saw contain extension methods, which are stateless, so that has no impact on thread safety. NRules does not have any static or single instance state anywhere in the codebase.

With that being said, NRules needs to be used in a particular way in a multi-threaded environment. If it is used correctly - it is thread safe.
Roughly, the sequence of operations is as follows:
1. Load rules into an instance of RuleRepository. This operation is NOT thread safe, and is expected to be done only once, when bootstraping the application (or a web application)
2. Compile rules contained in the RuleRepository into an ISessionFactory. Again, NOT thread safe and only done once during the application bootstraping
3. Create a new rules session (ISession) from ISessionFactory - this IS thread safe. So, you can share the same ISessionFactory among multiple concurrent threads
4. Work with the ISession to assert facts and fire rules. This is NOT thread safe. There are two usage scenarios:
4.a. Short lived session. You create a new session within a single-threaded context (i.e. a service request handler, etc.), assert facts, fire rules and throw the session away. Every single-threaded context gets its own session, so multi-threading is not a concern
4.b. Long lived session. You share a long lived session among multiple threads - in this case, you MUST synchronize access to ISession, since ISession is not thread safe.

See:

Let me know if this answers your question.

Sergiy

Zack Jones

unread,
May 7, 2015, 1:13:20 AM5/7/15
to nrules...@googlegroups.com
Thank you Sergiy! 

I will have to experiment a bit to see exactly what you're describing, but thank you for the very thorough reply.

sBham

unread,
Dec 27, 2015, 2:26:04 PM12/27/15
to NRules Users
I might see a good use for an example/sample of a per web request lifecycle.
I think that so far an adequate web framework to surface Sergiy notes/guides might be nancyfx since the app bootstrapping and per request context is pretty clear to understand get hold of.

I wish I had time to write a simple example, maybe in the near future is no one does already.

Cheers!
-sBham
 
Reply all
Reply to author
Forward
0 new messages