View Javadoc
1   package net.secodo.jcircuitbreaker.breakstrategy.impl;
2   
3   import java.util.Collection;
4   
5   import net.secodo.jcircuitbreaker.breaker.execution.ExecutedTask;
6   import net.secodo.jcircuitbreaker.breaker.execution.ExecutionContext;
7   import net.secodo.jcircuitbreaker.breakstrategy.BreakStrategy;
8   import net.secodo.jcircuitbreaker.task.Task;
9   
10  
11  /**
12   * An implementation of {@link BreakStrategy} which causes the circuit breaker to break (not execute the Task) in
13   * case all tasks currently running inside the circuit breaker reaches the allowed maximum (defined by
14   * maxSupportedExecutions constructor param).
15   *
16   * <p>In constructor you define maximum number of allowed concurrent executions of <i>real_method</i> .
17   *
18   * <p>For example this strategy:
19   *
20   * <p>new LimitedConcurrentExecutionsStrategy(10);
21   *
22   * <p>breaks (not allows execution of target-method) in there are currently 10 other threads that started execution
23   * of <i>target-method</i> and the method did not yet return a value. In this case circuit breaker would executed a
24   * break handler to provide fallback behaviour. If the number of task at the moment was less than 10, <i>Task</i>
25   * (<i>real-method</i>) would be executed normal.
26   *
27   * <p>NOTE: in above example, if the average was above 1000ms than this strategy would return false to circuit breaker
28   * and circuit breaker would execute {@link net.secodo.jcircuitbreaker.breakhandler.BreakHandler} to handle this
29   * situation
30   *
31   * @param <R> the return type of <i>real-method</i> that is executed by circuit breaker
32   */
33  public class LimitedConcurrentExecutionsStrategy<R> implements BreakStrategy<R> {
34    /**
35     * Protected access to allow extending classes to dynamically change it,
36     * e.g. via MBean
37     */
38    protected long maxSupportedExecutions;
39  
40    public LimitedConcurrentExecutionsStrategy(long maxSupportedExecutions) {
41      this.maxSupportedExecutions = maxSupportedExecutions;
42    }
43  
44  
45    @Override
46    public boolean shouldBreak(Task<R> task, ExecutionContext<R> executionContext) {
47      final Collection<ExecutedTask<R>> executionsInProgress = executionContext.getExecutionsInProgress();
48  
49      return executionsInProgress.size() >= maxSupportedExecutions;
50    }
51  }