File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
approvaltests-util-tests/src/test/java/org/lambda/utils
approvaltests-util/src/main/java/org/lambda/utils Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ package org .lambda .utils ;
2+
3+ import org .junit .jupiter .api .Test ;
4+
5+ import static org .junit .jupiter .api .Assertions .assertEquals ;
6+
7+ public class OnceTest {
8+ public static int count = 0 ;
9+
10+ @ Test
11+ public void testOnce () {
12+ increment ();
13+ increment ();
14+ increment ();
15+ increment ();
16+ increment ();
17+ assertEquals (1 , count );
18+ }
19+
20+ private void increment () {
21+ Once .run (() -> OnceTest .count ++);
22+ }
23+
24+ @ Test
25+ public void testFunctionCallOnce () {
26+ int count = 0 ;
27+ count = increment (count );
28+ count = increment (count );
29+ count = increment (count );
30+ count = increment (count );
31+ count = increment (count );
32+ assertEquals (1 , count );
33+ }
34+
35+ private int increment (int count ) {
36+ return Once .run (() -> count + 1 );
37+ }
38+
39+ }
Original file line number Diff line number Diff line change 1+ package org .lambda .utils ;
2+
3+ import org .lambda .actions .Action0 ;
4+ import org .lambda .functions .Function0 ;
5+
6+ import java .util .*;
7+
8+ public class Once {
9+ private static final Set <Action0 > actions = Collections .synchronizedSet (new HashSet <>());
10+ private static final Map <Class , Object > functions = Collections .synchronizedMap (new HashMap <>());
11+ public static void run (Action0 runnable ) {
12+ if (!actions .contains (runnable )) {
13+ actions .add (runnable );
14+ runnable .call ();
15+ }
16+ }
17+ public static <T > T run (Function0 <T > runnable ) {
18+ return (T ) functions .computeIfAbsent (runnable .getClass (), k -> runnable .call ());
19+ }
20+ }
You can’t perform that action at this time.
0 commit comments