View Javadoc
1   package net.secodo.jcircuitbreaker.breakhandler.impl;
2   
3   import java.lang.reflect.Constructor;
4   
5   import java.util.concurrent.Callable;
6   
7   import net.secodo.jcircuitbreaker.breaker.execution.ExecutionContext;
8   import net.secodo.jcircuitbreaker.breakhandler.BreakHandler;
9   import net.secodo.jcircuitbreaker.breakhandler.BreakHandlerFactory;
10  import net.secodo.jcircuitbreaker.breakhandler.exception.BreakHandlerException;
11  import net.secodo.jcircuitbreaker.task.Task;
12  
13  
14  /**
15   * An implementation of {@link BreakHandlerFactory} which creates new instance of given {@link BreakHandler} class for
16   * each invocation of {@link #makeHandler(Task, ExecutionContext)} . The class given as a constructor param needs
17   * to have default constructor which is used to create instance. The constructor must be accessible to 
18   * {@link SimpleHandlerFactory}.
19   *
20   * <p>NOTE: if given handlerClass makes subsequent calls to {@link #makeHandler(Task, ExecutionContext)} during one
21   * execution flow of circuit breaker (like for example {@link ReusableRetryHandler} does), new instance of given
22   * handler would be created for each call to {@link #makeHandler(Task, ExecutionContext)}, so there will be
23   * different instances of {@link BreakHandler} created per execution flow of circuit breaker. If you want only
24   * one <i>break handler</i> to be created for single execution of <i>Task</i>, consider implementing
25   * {@link net.secodo.jcircuitbreaker.breakhandler.OnePerExecutionHandlerFactory} which creates and returns only one
26   * instance per execution. See source code of {@link ReusableRetryHandler} for example of implementing this interface.
27   *
28   * @param <R> the return type of real-method for which a <i>break handler</i> is created
29   */
30  public class SimpleHandlerFactory<R> implements BreakHandlerFactory<R> {
31    private final Class<? extends BreakHandler<R>> handlerClass;
32  
33    public SimpleHandlerFactory(Class<? extends BreakHandler<R>> handlerClass) {
34      this.handlerClass = handlerClass;
35    }
36  
37    @Override
38    public BreakHandler<R> makeHandler(Task<R> task, ExecutionContext<R> executionContext) {
39      final BreakHandler<R> breakHandler;
40      try {
41        final Constructor<? extends BreakHandler<R>> handlerClassConstructor = handlerClass.getConstructor();
42        breakHandler = handlerClassConstructor.newInstance();
43  
44      } catch (Exception ex) {
45        throw new BreakHandlerException("Unable to create new instance of break handler of class: " + handlerClass, ex);
46      }
47  
48      return breakHandler;
49    }
50  }