-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCircuitBreaker.java
More file actions
94 lines (71 loc) · 2.06 KB
/
CircuitBreaker.java
File metadata and controls
94 lines (71 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.roku.server.authsvc.restclients;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CircuitBreaker {
private String partner;
private State state;
public void setThreshold(int threshold) {
this.threshold = threshold;
}
private volatile int threshold;
public Lock lock;
private static int THRESHOLD_LEVEL = 3; // three 5xx in a minute will make the circuit open
public CircuitBreaker( ) {
state = State.CLOSE;
threshold = 0;
lock = new ReentrantLock();
}
public void setPartner(String partner) {
this.partner = partner;
}
public int getThreshold() {
return threshold;
}
public boolean isOpen() {
return state == State.OPEN;
}
public boolean isClosed() {
return state == State.CLOSE;
}
public boolean isHalfOpen() {
return state == State.HALF_OPEN;
}
public void closeCircuit() {
state = State.CLOSE;
threshold = 0 ;
}
public void openCircuit() {
state = State.OPEN;
}
public void setHalfOpen() {
state = State.HALF_OPEN;
}
public State getState() {
return state;
}
public static void main ( String[] args) {
Map<String, CircuitBreaker> circuitBreakerMap = new HashMap<>();
CircuitBreaker cb = new CircuitBreaker();
circuitBreakerMap.put("hulu",cb);
}
public enum State {
CLOSE,
OPEN,
HALF_OPEN;
}
public void updateErrorThreshold() {
if ( threshold > THRESHOLD_LEVEL) {
// threshold level already high , nothing to do
return ;
}
threshold++;
if ( threshold == THRESHOLD_LEVEL && state == State.CLOSE ) {
state = State.OPEN;
}
}
}