App-vNext / Polly

Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner. From version 6.0.1, Polly targets .NET Standard 1.1 and 2.0+.
https://www.thepollyproject.org
BSD 3-Clause "New" or "Revised" License
13.48k stars 1.23k forks source link

Share policy instace #57

Closed monotore closed 8 years ago

monotore commented 9 years ago

Can I share a Policy instance between threads, or should I create a new instance each time I run a policy?

joelhulen commented 9 years ago

Could you please provide a sample of what you're trying to accomplish?

monotore commented 9 years ago

I have a class where the Policy is a field. The field is used by multiple methods of the class. An instance of the class is used by multiple threads at the same time. Is this OK?

   public class Class
    {
        private readonly Policy _policy = Policy
            .Handle<TimeoutException>()
            .RetryForever();

        public void MethodA()
        {
            _policy.Execute(DoSomething);
        }

        public void MethodB()
        {
            _policy.Execute(DoSomething);
        }
    }
reisenberger commented 9 years ago

@monotore @joelhulen My reading of the Polly codebase is that Policy instances are thread-safe.

@joelhulen, your team might want to verify this for yourselves independently (see if you agree...), but my reasoning:

Retry policies: Use an underlying instance of IRetryPolicyState to maintain retry state (eg number of retries made). However, each call to someRetryPolicyInstance.Execute(...) uses the Func<IRetryPolicyState> policyStateFactory to make a new, private instance of the relevant IRetryPolicyState implementation, so retry state data for different calls through someRetryPolicyInstance.Execute(...) is entirely independent (and hence thread-safe).

Circuit-breaker policies: Multiple calls to someCircuitBreakerPolicyInstance.Execute(...) share (and must share) the same underlying ICircuitBreakerState, so that any exceptions thrown during each call to Execute(...) accumulate towards the (consecutive) total at which the circuit will break. However, all manipulation and reading of the ICircuitBreakerState's state data is protected by locks making it thread-safe.

Hope this is useful.

reisenberger commented 8 years ago

New documentation of some example policy patterns has been added at https://github.com/App-vNext/Polly/wiki/Some-policy-patterns. This covers: