Import views plugins
[deliverable/tracecompass.git] / tmf / org.lttng.scope.tmf2.views.core / src / org / lttng / scope / tmf2 / views / core / NestingBoolean.java
1 /*
2 * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 */
9
10 package org.lttng.scope.tmf2.views.core;
11
12 import java.util.concurrent.atomic.AtomicInteger;
13
14 import javafx.beans.property.BooleanProperty;
15 import javafx.beans.property.ReadOnlyBooleanProperty;
16 import javafx.beans.property.SimpleBooleanProperty;
17 import javafx.beans.value.ChangeListener;
18
19 /**
20 * Utility class that serves as a wrapper around a single boolean flag that can
21 * be enabled/disabled. It counts the number of times {@link #disable()} is
22 * called, and only really re-enables the inner value when {@link #enable()} is
23 * called that many times.
24 *
25 * It is meant to be useful in multi-thread scenarios, where concurrent
26 * "critical sections" may want to disable something like a listener, and not
27 * have it really be re-enabled until all critical sections are finished. Thus
28 * it is thread-safe.
29 *
30 * The inner value is exposed through the {@link #enabledProperty()} method, which
31 * returns a {@link ReadOnlyBooleanProperty}. You can attach
32 * {@link ChangeListener}s to that property to get notified of inner value
33 * changes.
34 *
35 * It is "enabled" at creation time.
36 *
37 * @author Alexandre Montplaisir
38 */
39 public class NestingBoolean {
40
41 private final AtomicInteger fDisabledCount = new AtomicInteger(0);
42 private final BooleanProperty fBoolean = new SimpleBooleanProperty(true);
43
44 /**
45 * Decrease the "disabled" count by 1. If it reaches (or already was at) 0
46 * then the value is truly enabled.
47 */
48 public synchronized void enable() {
49 /* Decrement the count but only if it is currently above 0 */
50 int ret = fDisabledCount.updateAndGet(value -> value > 0 ? value - 1 : 0);
51 if (ret == 0) {
52 fBoolean.set(true);
53 }
54 }
55
56 /**
57 * Increase the "disabled" count by 1. The inner value will necessarily be
58 * disabled after this call.
59 */
60 public synchronized void disable() {
61 fDisabledCount.incrementAndGet();
62 fBoolean.set(false);
63 }
64
65 /**
66 * Property representing the inner boolean value.
67 *
68 * @return The inner value
69 */
70 public ReadOnlyBooleanProperty enabledProperty() {
71 return fBoolean;
72 }
73 }
This page took 0.033814 seconds and 5 git commands to generate.