View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.concurrent;
18  
19  import static org.junit.jupiter.api.Assertions.assertArrayEquals;
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertFalse;
22  import static org.junit.jupiter.api.Assertions.assertNotEquals;
23  import static org.junit.jupiter.api.Assertions.assertThrows;
24  import static org.junit.jupiter.api.Assertions.assertTrue;
25  
26  import java.beans.PropertyChangeEvent;
27  import java.beans.PropertyChangeListener;
28  import java.lang.reflect.Constructor;
29  import java.lang.reflect.Field;
30  import java.util.ArrayList;
31  import java.util.List;
32  import java.util.concurrent.CountDownLatch;
33  import java.util.concurrent.TimeUnit;
34  import java.util.concurrent.atomic.AtomicReference;
35  
36  import org.apache.commons.lang3.AbstractLangTest;
37  import org.apache.commons.lang3.ArrayUtils;
38  import org.junit.jupiter.api.Test;
39  import org.junit.jupiter.params.ParameterizedTest;
40  import org.junit.jupiter.params.provider.ValueSource;
41  
42  /**
43   * Test class for {@code EventCountCircuitBreaker}.
44   */
45  class EventCountCircuitBreakerTest extends AbstractLangTest {
46  
47      /**
48       * A test change listener for checking whether correct change events are generated.
49       */
50      private static final class ChangeListener implements PropertyChangeListener {
51  
52          /** The expected event source. */
53          private final Object expectedSource;
54  
55          /** A list with the updated values extracted from received change events. */
56          private final List<Boolean> changedValues;
57  
58          /**
59           * Creates a new instance of {@code ChangeListener} and sets the expected event
60           * source.
61           *
62           * @param source The expected event source
63           */
64          ChangeListener(final Object source) {
65              expectedSource = source;
66              changedValues = new ArrayList<>();
67          }
68  
69          @Override
70          public void propertyChange(final PropertyChangeEvent evt) {
71              assertEquals(expectedSource, evt.getSource(), "Wrong event source");
72              assertEquals("open", evt.getPropertyName(), "Wrong property name");
73              final Boolean newValue = (Boolean) evt.getNewValue();
74              final Boolean oldValue = (Boolean) evt.getOldValue();
75              assertNotEquals(newValue, oldValue, "Old and new value are equal");
76              changedValues.add(newValue);
77          }
78  
79          /**
80           * Verifies that change events for the expected values have been received.
81           *
82           * @param values The expected values
83           */
84          public void verify(final Boolean... values) {
85              assertArrayEquals(values, changedValues.toArray(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY));
86          }
87      }
88  
89      /**
90       * A test implementation of {@code EventCountCircuitBreaker} which supports mocking the timer.
91       * This is useful for the creation of deterministic tests for switching the circuit
92       * breaker's state.
93       */
94      private static final class EventCountCircuitBreakerTestImpl extends EventCountCircuitBreaker {
95  
96          /** The current time in nanoseconds. */
97          private long currentTime;
98  
99          EventCountCircuitBreakerTestImpl(final int openingThreshold, final long openingInterval,
100                                                 final TimeUnit openingUnit, final int closingThreshold, final long closingInterval,
101                                                 final TimeUnit closingUnit) {
102             super(openingThreshold, openingInterval, openingUnit, closingThreshold,
103                     closingInterval, closingUnit);
104         }
105 
106         /**
107          * Sets the current time to be used by this test object for the next operation.
108          *
109          * @param time The time to set
110          * @return A reference to this object
111          */
112         public EventCountCircuitBreakerTestImpl at(final long time) {
113             currentTime = time;
114             return this;
115         }
116 
117         /**
118          * {@inheritDoc} This implementation returns the value passed to the {@code at()}
119          * method.
120          */
121         @Override
122         long nanoTime() {
123             return currentTime;
124         }
125 
126         /**
127          * Sets the event count near the long boundary without executing billions of increments.
128          *
129          * @param count The event count
130          * @throws ReflectiveOperationException if the interval data cannot be initialized
131          */
132         @SuppressWarnings("unchecked")
133         private void setEventCount(final long count) throws ReflectiveOperationException {
134             final Field field = EventCountCircuitBreaker.class.getDeclaredField("checkIntervalData");
135             field.setAccessible(true);
136             final AtomicReference<Object> intervalData = (AtomicReference<Object>) field.get(this);
137             final Constructor<?> constructor = intervalData.get().getClass().getDeclaredConstructor(long.class, long.class);
138             constructor.setAccessible(true);
139             intervalData.set(constructor.newInstance(count, currentTime));
140         }
141     }
142 
143     /** Constant for the opening threshold. */
144     private static final int OPENING_THRESHOLD = 10;
145 
146     /** Constant for the closing threshold. */
147     private static final int CLOSING_THRESHOLD = 5;
148 
149     /** Constant for the factor for converting nanoseconds. */
150     private static final long NANO_FACTOR = 1000L * 1000L * 1000L;
151 
152     /**
153      * Tests whether a new check interval is started if the circuit breaker has a
154      * transition to open state.
155      */
156     @Test
157     void testAutomaticOpenStartsNewCheckInterval() {
158         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2,
159                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
160         long time = 10 * NANO_FACTOR;
161         for (int i = 0; i <= OPENING_THRESHOLD; i++) {
162             breaker.at(time++).incrementAndCheckState();
163         }
164         assertTrue(breaker.isOpen(), "Not open");
165         time += NANO_FACTOR - 1000;
166         assertFalse(breaker.at(time).incrementAndCheckState(), "Already closed");
167         time += 1001;
168         assertTrue(breaker.at(time).checkState(), "Not closed in time interval");
169     }
170 
171     /**
172      * Tests whether events are generated when the state is changed.
173      */
174     @Test
175     void testChangeEvents() {
176         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
177                 TimeUnit.SECONDS);
178         final ChangeListener listener = new ChangeListener(breaker);
179         breaker.addChangeListener(listener);
180         breaker.open();
181         breaker.close();
182         listener.verify(Boolean.TRUE, Boolean.FALSE);
183     }
184 
185     /**
186      * Tests that automatic state transitions generate change events as well.
187      */
188     @Test
189     void testChangeEventsGeneratedByAutomaticTransitions() {
190         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2,
191                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
192         final ChangeListener listener = new ChangeListener(breaker);
193         breaker.addChangeListener(listener);
194         long time = 0;
195         for (int i = 0; i <= OPENING_THRESHOLD; i++, time += 1000) {
196             breaker.at(time).incrementAndCheckState();
197         }
198         breaker.at(NANO_FACTOR + 1).checkState();
199         breaker.at(3 * NANO_FACTOR).checkState();
200         listener.verify(Boolean.TRUE, Boolean.FALSE);
201     }
202 
203     /**
204      * Tests whether the circuit breaker can be closed explicitly.
205      */
206     @Test
207     void testClose() {
208         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2,
209                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
210         long time = 0;
211         for (int i = 0; i <= OPENING_THRESHOLD; i++, time += 1000) {
212             breaker.at(time).incrementAndCheckState();
213         }
214         assertTrue(breaker.isOpen(), "Not open");
215         breaker.close();
216         assertTrue(breaker.isClosed(), "Not closed");
217         assertTrue(breaker.at(time + 1000).incrementAndCheckState(), "Open again");
218     }
219 
220     /**
221      * Tests that the circuit breaker closes automatically if the number of events
222      * received goes under the closing threshold.
223      */
224     @Test
225     void testClosingWhenThresholdReached() {
226         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD,
227                 10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
228         breaker.open();
229         breaker.at(1000).incrementAndCheckState();
230         assertFalse(breaker.at(2000).checkState(), "Already closed");
231         assertFalse(breaker.at(NANO_FACTOR).checkState(), "Closed at interval end");
232         assertTrue(breaker.at(NANO_FACTOR + 1).checkState(), "Not closed after interval end");
233         assertTrue(breaker.isClosed(), "Not closed at end");
234     }
235 
236     /**
237      * Tests that the closing interval is the same as the opening interval if it is not
238      * specified.
239      */
240     @Test
241     void testDefaultClosingInterval() {
242         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
243                 TimeUnit.SECONDS, CLOSING_THRESHOLD);
244         assertEquals(NANO_FACTOR, breaker.getClosingInterval(), "Wrong closing interval");
245     }
246 
247     /**
248      * Tests that the closing threshold is the same as the opening threshold if not
249      * specified otherwise.
250      */
251     @Test
252     void testDefaultClosingThreshold() {
253         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
254                 TimeUnit.SECONDS);
255         assertEquals(NANO_FACTOR, breaker.getClosingInterval(), "Wrong closing interval");
256         assertEquals(OPENING_THRESHOLD, breaker.getClosingThreshold(), "Wrong closing threshold");
257     }
258 
259     /**
260      * Tests that a circuit breaker is closed after its creation.
261      */
262     @Test
263     void testInitiallyClosed() {
264         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
265                 TimeUnit.SECONDS);
266         assertFalse(breaker.isOpen(), "Open");
267         assertTrue(breaker.isClosed(), "Not closed");
268     }
269 
270     /**
271      * Tests that time units are correctly taken into account by constructors.
272      */
273     @Test
274     void testIntervalCalculation() {
275         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
276                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 2, TimeUnit.MILLISECONDS);
277         assertEquals(NANO_FACTOR, breaker.getOpeningInterval(), "Wrong opening interval");
278         assertEquals(2 * NANO_FACTOR / 1000, breaker.getClosingInterval(), "Wrong closing interval");
279     }
280 
281     /**
282      * Tests that a negative increment is rejected: the event count must only move toward
283      * the opening threshold.
284      */
285     @Test
286     void testNegativeIncrementRejected() {
287         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1, TimeUnit.SECONDS);
288         assertThrows(IllegalArgumentException.class, () -> breaker.incrementAndCheckState(-1), "Negative increments must be rejected");
289     }
290 
291     /**
292      * Tests that an open circuit breaker does not close itself when the number of events
293      * received is over the threshold.
294      */
295     @Test
296     void testNotClosingOverThreshold() {
297         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD,
298                 10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
299         long startTime = 0;
300         breaker.open();
301         for (int i = 0; i <= CLOSING_THRESHOLD; i++) {
302             assertFalse(breaker.at(startTime).incrementAndCheckState(), "Not open");
303             startTime += 1000;
304         }
305         assertFalse(breaker.at(startTime + NANO_FACTOR).incrementAndCheckState(), "Closed in new interval");
306         assertTrue(breaker.isOpen(), "Not open at end");
307     }
308 
309     /**
310      * Tests that an open circuit breaker does not close itself when the event count of the
311      * check interval exceeds the range of an int.
312      */
313     @Test
314     void testNotClosingWhenEventCountOverflows() {
315         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD,
316                 10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
317         breaker.at(0).open();
318         assertFalse(breaker.at(1000).incrementAndCheckState(CLOSING_THRESHOLD), "Not open");
319         assertFalse(breaker.at(2000).incrementAndCheckState(Integer.MAX_VALUE), "Not open");
320         assertFalse(breaker.at(NANO_FACTOR + 3000).incrementAndCheckState(), "Closed in new interval");
321         assertTrue(breaker.isOpen(), "Not open at end");
322     }
323 
324     /**
325      * Tests that saturation prevents closing after heavy load and still allows recovery after a quiet interval.
326      *
327      * @param count The event count before incrementing
328      * @throws ReflectiveOperationException if the interval data cannot be initialized
329      */
330     @ParameterizedTest
331     @ValueSource(longs = {Long.MAX_VALUE - Integer.MAX_VALUE, Long.MAX_VALUE - Integer.MAX_VALUE + 1, Long.MAX_VALUE - 1, Long.MAX_VALUE})
332     void testNotClosingWhenEventCountSaturates(final long count) throws ReflectiveOperationException {
333         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD,
334                 10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
335         breaker.at(0).open();
336         breaker.setEventCount(count);
337         assertFalse(breaker.at(1000).incrementAndCheckState(Integer.MAX_VALUE), "Not open");
338         assertFalse(breaker.at(2000).checkState(), "Closed after a zero increment");
339         assertFalse(breaker.at(3000).incrementAndCheckState(), "Not open after another event");
340         assertFalse(breaker.at(4000).incrementAndCheckState(Integer.MAX_VALUE), "Not open after another batch");
341         assertFalse(breaker.at(NANO_FACTOR + 1).checkState(), "Closed after a saturated interval");
342         assertTrue(breaker.at(2 * NANO_FACTOR + 2).checkState(), "Not closed after a quiet interval");
343     }
344 
345     /**
346      * Tests that the circuit breaker stays closed if there are a number of received
347      * events, but not in a single check interval.
348      */
349     @Test
350     void testNotOpeningCheckIntervalExceeded() {
351         long startTime = 0L;
352         final long timeIncrement = 3 * NANO_FACTOR / (2 * OPENING_THRESHOLD);
353         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
354                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
355         for (int i = 0; i < 5 * OPENING_THRESHOLD; i++) {
356             assertTrue(breaker.at(startTime).incrementAndCheckState(), "In open state");
357             startTime += timeIncrement;
358         }
359         assertTrue(breaker.isClosed(), "Not closed");
360     }
361 
362     /**
363      * Tests that the circuit breaker stays closed if the number of received events stays
364      * below the threshold.
365      */
366     @Test
367     void testNotOpeningUnderThreshold() {
368         long startTime = 1000;
369         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
370                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
371         for (int i = 0; i < OPENING_THRESHOLD - 1; i++) {
372             assertTrue(breaker.at(startTime).incrementAndCheckState(), "In open state");
373             startTime++;
374         }
375         assertTrue(breaker.isClosed(), "Not closed");
376     }
377 
378     /**
379      * Tests whether the current time is correctly determined.
380      */
381     @Test
382     void testNow() {
383         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
384                 TimeUnit.SECONDS);
385         final long nowNanos = breaker.nanoTime();
386         final long deltaNanos = Math.abs(System.nanoTime() - nowNanos);
387         assertTrue(deltaNanos < 100_000, String.format("Delta %,d ns to current time too large", deltaNanos));
388     }
389 
390     /**
391      * Tests that the circuit breaker opens when the event count of the check interval
392      * exceeds the range of an int.
393      */
394     @Test
395     void testOpeningWhenEventCountOverflows() {
396         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
397             TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
398         assertTrue(breaker.at(1000).incrementAndCheckState(OPENING_THRESHOLD / 2), "Not closed");
399         assertFalse(breaker.at(2000).incrementAndCheckState(Integer.MAX_VALUE), "Not open");
400         assertTrue(breaker.isOpen(), "Not open at end");
401     }
402 
403     /**
404      * Tests that the circuit breaker opens if all conditions are met.
405      */
406     @Test
407     void testOpeningWhenThresholdReached() {
408         long startTime = 0;
409         final long timeIncrement = NANO_FACTOR / OPENING_THRESHOLD - 1;
410         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
411                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
412         boolean open = false;
413         for (int i = 0; i < OPENING_THRESHOLD + 1; i++) {
414             open = !breaker.at(startTime).incrementAndCheckState();
415             startTime += timeIncrement;
416         }
417         assertTrue(open, "Not open");
418         assertFalse(breaker.isClosed(), "Closed");
419     }
420 
421     /**
422      * Tests that the circuit breaker opens if all conditions are met when using
423      * {@link EventCountCircuitBreaker#incrementAndCheckState(Integer increment)}.
424      */
425     @Test
426     void testOpeningWhenThresholdReachedThroughBatch() {
427         final long timeIncrement = NANO_FACTOR / OPENING_THRESHOLD - 1;
428         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
429             TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
430         final long startTime = timeIncrement * (OPENING_THRESHOLD + 1);
431         final boolean open = !breaker.at(startTime).incrementAndCheckState(OPENING_THRESHOLD + 1);
432         assertTrue(open, "Not open");
433         assertFalse(breaker.isClosed(), "Closed");
434     }
435 
436     /**
437      * Tests that the maximum int opening threshold is exceeded without wrapping the event count.
438      */
439     @Test
440     void testOpeningWithMaximumThreshold() {
441         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(Integer.MAX_VALUE, 1,
442                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
443         assertTrue(breaker.at(1000).incrementAndCheckState(Integer.MAX_VALUE), "Opened at the threshold");
444         assertFalse(breaker.at(2000).incrementAndCheckState(), "Not open above the threshold");
445         assertTrue(breaker.isOpen(), "Not open at end");
446     }
447 
448     /**
449      * Tests whether an explicit open operation fully initializes the internal check data
450      * object. Otherwise, the circuit breaker may close itself directly afterwards.
451      */
452     @Test
453     void testOpenStartsNewCheckInterval() {
454         final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2,
455                 TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
456         breaker.at(NANO_FACTOR - 1000).open();
457         assertTrue(breaker.isOpen(), "Not open");
458         assertFalse(breaker.at(NANO_FACTOR + 100).checkState(), "Already closed");
459     }
460 
461     /**
462      * Tests whether a change listener can be removed.
463      */
464     @Test
465     void testRemoveChangeListener() {
466         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
467                 TimeUnit.SECONDS);
468         final ChangeListener listener = new ChangeListener(breaker);
469         breaker.addChangeListener(listener);
470         breaker.open();
471         breaker.removeChangeListener(listener);
472         breaker.close();
473         listener.verify(Boolean.TRUE);
474     }
475 
476     /**
477      * Tests that a state transition triggered by multiple threads is handled correctly.
478      * Only the first transition should cause an event to be sent.
479      */
480     @Test
481     void testStateTransitionGuarded() throws InterruptedException {
482         final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
483                 TimeUnit.SECONDS);
484         final ChangeListener listener = new ChangeListener(breaker);
485         breaker.addChangeListener(listener);
486 
487         final int threadCount = 128;
488         final CountDownLatch latch = new CountDownLatch(1);
489         final Thread[] threads = new Thread[threadCount];
490         for (int i = 0; i < threadCount; i++) {
491             threads[i] = new Thread() {
492                 @Override
493                 public void run() {
494                     try {
495                         latch.await();
496                     } catch (final InterruptedException iex) {
497                         // ignore
498                     }
499                     breaker.open();
500                 }
501             };
502             threads[i].start();
503         }
504         latch.countDown();
505         for (final Thread thread : threads) {
506             thread.join();
507         }
508         listener.verify(Boolean.TRUE);
509     }
510 }