feat: support for multiple independent named contexts
Some checks failed
Release / release (push) Failing after 42s
Some checks failed
Release / release (push) Failing after 42s
Signed-off-by: Leo Galambos <lg@hq.egothor.org>
This commit is contained in:
@@ -34,169 +34,133 @@
|
|||||||
*/
|
*/
|
||||||
package conflux;
|
package conflux;
|
||||||
|
|
||||||
import java.lang.ref.WeakReference;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Set;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A globally accessible, type-safe context for sharing data between independent
|
* A central context manager for storing and retrieving key-value pairs in a
|
||||||
* parts of an application. Supports listeners that are notified whenever a
|
* thread-safe, type-safe manner.
|
||||||
* registered key's value changes.
|
|
||||||
*
|
|
||||||
* This implementation guarantees:
|
|
||||||
* <ul>
|
|
||||||
* <li>Strongly typed keys using {@link Key}</li>
|
|
||||||
* <li>One consistent type per key name</li>
|
|
||||||
* <li>Support for weak-referenced listeners to avoid memory leaks</li>
|
|
||||||
* <li>Thread-safe operations</li>
|
|
||||||
* </ul>
|
|
||||||
*
|
|
||||||
* Usage:
|
|
||||||
*
|
*
|
||||||
* <pre>
|
* This enum serves as both:
|
||||||
* Key<Integer> COUNT = Key.of("count", Integer.class);
|
* <ul>
|
||||||
* Ctx.INSTANCE.put(COUNT, 42);
|
* <li>A singleton context via {@code Ctx.INSTANCE} for global/shared usage</li>
|
||||||
* int v = Ctx.INSTANCE.get(COUNT);
|
* <li>A factory and registry for multiple named independent contexts</li>
|
||||||
* </pre>
|
* </ul>
|
||||||
|
*
|
||||||
|
* Each context provides listener support for reactive value changes.
|
||||||
*
|
*
|
||||||
|
* @see Key
|
||||||
|
* @see Listener
|
||||||
|
*
|
||||||
* @author Leo Galambos
|
* @author Leo Galambos
|
||||||
*/
|
*/
|
||||||
public enum Ctx {
|
public enum Ctx implements CtxInterface {
|
||||||
/**
|
/**
|
||||||
* Singleton instance of the context.
|
* The singleton instance representing the default/global context.
|
||||||
*/
|
*/
|
||||||
INSTANCE;
|
INSTANCE;
|
||||||
|
|
||||||
private final Map<Key<?>, Object> values = new ConcurrentHashMap<>();
|
/**
|
||||||
private final Map<String, Class<?>> keyTypes = new ConcurrentHashMap<>();
|
* A registry of named contexts, allowing for multiple isolated logical
|
||||||
private final Map<Key<?>, List<WeakReference<Listener<?>>>> listeners = new ConcurrentHashMap<>();
|
* contexts.
|
||||||
|
*/
|
||||||
|
private final Map<String, CtxInterface> contexts = new ConcurrentHashMap<>();
|
||||||
|
/**
|
||||||
|
* The default context instance used by this enum singleton. All interface
|
||||||
|
* method calls delegate to this context.
|
||||||
|
*/
|
||||||
|
private final CtxInterface defaultCtx = new CtxInstance();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stores or updates the value for a given key. If the key is used for the first
|
* Returns a named context. If the context does not exist, it is lazily created.
|
||||||
* time, its type is recorded. If the key has been used before with a different
|
*
|
||||||
* type, an exception will be thrown.
|
* This method allows isolation between different logical scopes (e.g.,
|
||||||
|
* sessions, users).
|
||||||
*
|
*
|
||||||
* After setting the value, any registered listeners for that key will be
|
* @param name the name of the context
|
||||||
* notified (if the value was modified).
|
* @return the associated context instance
|
||||||
*
|
|
||||||
* @param key the key
|
|
||||||
* @param value the value to store
|
|
||||||
* @param <T> the type of the value
|
|
||||||
* @throws IllegalStateException if the key is reused with a different type
|
|
||||||
*/
|
*/
|
||||||
|
public CtxInterface getContext(String name) {
|
||||||
|
return contexts.computeIfAbsent(name, k -> new CtxInstance());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the set of names for all currently registered contexts.
|
||||||
|
*
|
||||||
|
* @return an immutable set of context names
|
||||||
|
*/
|
||||||
|
public Set<String> contextNames() {
|
||||||
|
return Set.copyOf(contexts.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*
|
||||||
|
* Delegates to the default context instance.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
public <T> void put(Key<T> key, T value) {
|
public <T> void put(Key<T> key, T value) {
|
||||||
keyTypes.compute(key.name(), (k, existingType) -> {
|
defaultCtx.put(key, value);
|
||||||
if (existingType == null) {
|
|
||||||
return key.type();
|
|
||||||
} else {
|
|
||||||
if (!existingType.equals(key.type())) {
|
|
||||||
throw new IllegalStateException(
|
|
||||||
"Key '" + key.name() + "' already associated with type " + existingType.getName());
|
|
||||||
}
|
|
||||||
return existingType;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
T previous = (T) values.put(key, value);
|
|
||||||
|
|
||||||
if (Objects.deepEquals(value, previous)) {
|
|
||||||
// no change
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// notify listeners
|
|
||||||
var list = listeners.get(key);
|
|
||||||
if (list != null) {
|
|
||||||
for (var ref : list) {
|
|
||||||
var listener = ref.get();
|
|
||||||
if (listener != null) {
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
Listener<T> typedListener = (Listener<T>) listener;
|
|
||||||
typedListener.valueChanged(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// clean up dead weak references
|
|
||||||
list.removeIf(ref -> ref.get() == null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves the value for the given key, or {@code null} if not set.
|
* {@inheritDoc}
|
||||||
*
|
*
|
||||||
* @param key the key
|
* Delegates to the default context instance.
|
||||||
* @param <T> the type
|
|
||||||
* @return the stored value or null
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@Override
|
||||||
public <T> T get(Key<T> key) {
|
public <T> T get(Key<T> key) {
|
||||||
return (T) values.get(key);
|
return defaultCtx.get(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if a value exists for the given key.
|
* {@inheritDoc}
|
||||||
*
|
*
|
||||||
* @param key the key
|
* Delegates to the default context instance.
|
||||||
* @return true if a value is present
|
|
||||||
*/
|
*/
|
||||||
|
@Override
|
||||||
public boolean contains(Key<?> key) {
|
public boolean contains(Key<?> key) {
|
||||||
return values.containsKey(key);
|
return defaultCtx.contains(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes the value and any listeners for the given key.
|
* {@inheritDoc}
|
||||||
*
|
*
|
||||||
* @param key the key
|
* Delegates to the default context instance.
|
||||||
* @return the removed value, or null if absent
|
|
||||||
*/
|
*/
|
||||||
|
@Override
|
||||||
public Object remove(Key<?> key) {
|
public Object remove(Key<?> key) {
|
||||||
keyTypes.remove(key.name());
|
return defaultCtx.remove(key);
|
||||||
var removed = values.remove(key);
|
|
||||||
listeners.remove(key);
|
|
||||||
return removed;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clears all keys and listeners from the context.
|
* {@inheritDoc}
|
||||||
|
*
|
||||||
|
* Delegates to the default context instance.
|
||||||
*/
|
*/
|
||||||
|
@Override
|
||||||
public void clear() {
|
public void clear() {
|
||||||
values.clear();
|
defaultCtx.clear();
|
||||||
keyTypes.clear();
|
|
||||||
listeners.clear();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers a listener to be notified whenever the value for the key changes.
|
* {@inheritDoc}
|
||||||
* The listener is weakly referenced to avoid preventing its garbage collection.
|
*
|
||||||
*
|
* Delegates to the default context instance.
|
||||||
* @param key the key
|
|
||||||
* @param listener the listener
|
|
||||||
* @param <T> the type
|
|
||||||
*/
|
*/
|
||||||
|
@Override
|
||||||
public <T> void addListener(Key<T> key, Listener<T> listener) {
|
public <T> void addListener(Key<T> key, Listener<T> listener) {
|
||||||
listeners.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(new WeakReference<>(listener));
|
defaultCtx.addListener(key, listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unregisters a previously registered listener for the key.
|
* {@inheritDoc}
|
||||||
*
|
*
|
||||||
* @param key the key
|
* Delegates to the default context instance.
|
||||||
* @param listener the listener to remove
|
|
||||||
* @param <T> the type
|
|
||||||
*/
|
*/
|
||||||
|
@Override
|
||||||
public <T> void removeListener(Key<T> key, Listener<T> listener) {
|
public <T> void removeListener(Key<T> key, Listener<T> listener) {
|
||||||
var list = listeners.get(key);
|
defaultCtx.removeListener(key, listener);
|
||||||
if (list != null) {
|
|
||||||
list.removeIf(ref -> {
|
|
||||||
var l = ref.get();
|
|
||||||
return l == null || l.equals(listener);
|
|
||||||
});
|
|
||||||
if (list.isEmpty()) {
|
|
||||||
listeners.remove(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
197
src/main/java/conflux/CtxInstance.java
Normal file
197
src/main/java/conflux/CtxInstance.java
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (C) 2025, Leo Galambos
|
||||||
|
* All rights reserved.
|
||||||
|
*
|
||||||
|
* Redistribution and use in source and binary forms, with or without
|
||||||
|
* modification, are permitted provided that the following conditions are met:
|
||||||
|
*
|
||||||
|
* 1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
* this list of conditions and the following disclaimer.
|
||||||
|
*
|
||||||
|
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
* this list of conditions and the following disclaimer in the documentation
|
||||||
|
* and/or other materials provided with the distribution.
|
||||||
|
*
|
||||||
|
* 3. All advertising materials mentioning features or use of this software must
|
||||||
|
* display the following acknowledgement:
|
||||||
|
* This product includes software developed by the Egothor project.
|
||||||
|
*
|
||||||
|
* 4. Neither the name of the copyright holder nor the names of its contributors
|
||||||
|
* may be used to endorse or promote products derived from this software
|
||||||
|
* without specific prior written permission.
|
||||||
|
*
|
||||||
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||||
|
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||||
|
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||||
|
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||||
|
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||||
|
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||||
|
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||||
|
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||||
|
* POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
*/
|
||||||
|
package conflux;
|
||||||
|
|
||||||
|
import java.lang.ref.WeakReference;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A globally accessible, type-safe context for sharing data between independent
|
||||||
|
* parts of an application. Supports listeners that are notified whenever a
|
||||||
|
* registered key's value changes.
|
||||||
|
*
|
||||||
|
* This implementation guarantees:
|
||||||
|
* <ul>
|
||||||
|
* <li>Strongly typed keys using {@link Key}</li>
|
||||||
|
* <li>One consistent type per key name</li>
|
||||||
|
* <li>Support for weak-referenced listeners to avoid memory leaks</li>
|
||||||
|
* <li>Thread-safe operations</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @author Leo Galambos
|
||||||
|
*/
|
||||||
|
public final class CtxInstance implements CtxInterface {
|
||||||
|
|
||||||
|
private final Map<Key<?>, Object> values = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, Class<?>> keyTypes = new ConcurrentHashMap<>();
|
||||||
|
private final Map<Key<?>, List<WeakReference<Listener<?>>>> listeners = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores or updates the value for a given key. If the key is used for the first
|
||||||
|
* time, its type is recorded. If the key has been used before with a different
|
||||||
|
* type, an exception will be thrown.
|
||||||
|
*
|
||||||
|
* After setting the value, any registered listeners for that key will be
|
||||||
|
* notified (if the value was modified).
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param value the value to store
|
||||||
|
* @param <T> the type of the value
|
||||||
|
* @throws IllegalStateException if the key is reused with a different type
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public <T> void put(Key<T> key, T value) {
|
||||||
|
keyTypes.compute(key.name(), (k, existingType) -> {
|
||||||
|
if (existingType == null) {
|
||||||
|
return key.type();
|
||||||
|
} else {
|
||||||
|
if (!existingType.equals(key.type())) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Key '" + key.name() + "' already associated with type " + existingType.getName());
|
||||||
|
}
|
||||||
|
return existingType;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
T previous = (T) values.put(key, value);
|
||||||
|
|
||||||
|
if (Objects.deepEquals(value, previous)) {
|
||||||
|
// no change
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// notify listeners
|
||||||
|
var list = listeners.get(key);
|
||||||
|
if (list != null) {
|
||||||
|
for (var ref : list) {
|
||||||
|
var listener = ref.get();
|
||||||
|
if (listener != null) {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Listener<T> typedListener = (Listener<T>) listener;
|
||||||
|
typedListener.valueChanged(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// clean up dead weak references
|
||||||
|
list.removeIf(ref -> ref.get() == null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the value for the given key, or {@code null} if not set.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param <T> the type
|
||||||
|
* @return the stored value or null
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T> T get(Key<T> key) {
|
||||||
|
return (T) values.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a value exists for the given key.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @return true if a value is present
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean contains(Key<?> key) {
|
||||||
|
return values.containsKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes the value and any listeners for the given key.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @return the removed value, or null if absent
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Object remove(Key<?> key) {
|
||||||
|
keyTypes.remove(key.name());
|
||||||
|
var removed = values.remove(key);
|
||||||
|
listeners.remove(key);
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears all keys and listeners from the context.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void clear() {
|
||||||
|
values.clear();
|
||||||
|
keyTypes.clear();
|
||||||
|
listeners.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a listener to be notified whenever the value for the key changes.
|
||||||
|
* The listener is weakly referenced to avoid preventing its garbage collection.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param listener the listener
|
||||||
|
* @param <T> the type
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public <T> void addListener(Key<T> key, Listener<T> listener) {
|
||||||
|
listeners.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(new WeakReference<>(listener));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unregisters a previously registered listener for the key.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param listener the listener to remove
|
||||||
|
* @param <T> the type
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public <T> void removeListener(Key<T> key, Listener<T> listener) {
|
||||||
|
var list = listeners.get(key);
|
||||||
|
if (list != null) {
|
||||||
|
list.removeIf(ref -> {
|
||||||
|
var l = ref.get();
|
||||||
|
return l == null || l.equals(listener);
|
||||||
|
});
|
||||||
|
if (list.isEmpty()) {
|
||||||
|
listeners.remove(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
121
src/main/java/conflux/CtxInterface.java
Normal file
121
src/main/java/conflux/CtxInterface.java
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (C) 2025, Leo Galambos
|
||||||
|
* All rights reserved.
|
||||||
|
*
|
||||||
|
* Redistribution and use in source and binary forms, with or without
|
||||||
|
* modification, are permitted provided that the following conditions are met:
|
||||||
|
*
|
||||||
|
* 1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
* this list of conditions and the following disclaimer.
|
||||||
|
*
|
||||||
|
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
* this list of conditions and the following disclaimer in the documentation
|
||||||
|
* and/or other materials provided with the distribution.
|
||||||
|
*
|
||||||
|
* 3. All advertising materials mentioning features or use of this software must
|
||||||
|
* display the following acknowledgement:
|
||||||
|
* This product includes software developed by the Egothor project.
|
||||||
|
*
|
||||||
|
* 4. Neither the name of the copyright holder nor the names of its contributors
|
||||||
|
* may be used to endorse or promote products derived from this software
|
||||||
|
* without specific prior written permission.
|
||||||
|
*
|
||||||
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||||
|
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||||
|
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||||
|
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||||
|
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||||
|
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||||
|
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||||
|
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||||
|
* POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
*/
|
||||||
|
package conflux;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A type-safe, thread-safe context interface for storing and retrieving
|
||||||
|
* key-value pairs.
|
||||||
|
*
|
||||||
|
* Implementations of this interface support:
|
||||||
|
* <ul>
|
||||||
|
* <li>Recording type-safe associations between keys and values</li>
|
||||||
|
* <li>Automatic listener notification when a value changes</li>
|
||||||
|
* <li>Context isolation (e.g., per name or use case)</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* This interface is sealed to only permit known, safe implementations.
|
||||||
|
*
|
||||||
|
* @see Key
|
||||||
|
* @see Listener
|
||||||
|
*
|
||||||
|
* @author Leo Galambos
|
||||||
|
*/
|
||||||
|
public sealed interface CtxInterface permits Ctx, CtxInstance {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores or updates the value for a given key. If the key is used for the first
|
||||||
|
* time, its type is recorded. If the key has been used before with a different
|
||||||
|
* type, an exception will be thrown.
|
||||||
|
*
|
||||||
|
* After setting the value, any registered listeners for that key will be
|
||||||
|
* notified (if the value was modified).
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param value the value to store
|
||||||
|
* @param <T> the type of the value
|
||||||
|
* @throws IllegalStateException if the key is reused with a different type
|
||||||
|
*/
|
||||||
|
<T> void put(Key<T> key, T value);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the value for the given key, or {@code null} if not set.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param <T> the type
|
||||||
|
* @return the stored value or null
|
||||||
|
*/
|
||||||
|
<T> T get(Key<T> key);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a value exists for the given key.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @return true if a value is present
|
||||||
|
*/
|
||||||
|
boolean contains(Key<?> key);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes the value and any listeners for the given key.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @return the removed value, or null if absent
|
||||||
|
*/
|
||||||
|
Object remove(Key<?> key);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears all keys and listeners from the context.
|
||||||
|
*/
|
||||||
|
void clear();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a listener to be notified whenever the value for the key changes.
|
||||||
|
* The listener is weakly referenced to avoid preventing its garbage collection.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param listener the listener
|
||||||
|
* @param <T> the type
|
||||||
|
*/
|
||||||
|
<T> void addListener(Key<T> key, Listener<T> listener);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unregisters a previously registered listener for the key.
|
||||||
|
*
|
||||||
|
* @param key the key
|
||||||
|
* @param listener the listener to remove
|
||||||
|
* @param <T> the type
|
||||||
|
*/
|
||||||
|
<T> void removeListener(Key<T> key, Listener<T> listener);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,28 +1,33 @@
|
|||||||
/**
|
/**
|
||||||
* Provides a lightweight, type-safe, application-wide context mechanism for
|
* Provides a lightweight, type-safe, application-wide context mechanism for
|
||||||
* sharing strongly typed data among otherwise decoupled classes.
|
* sharing strongly typed data among otherwise decoupled classes.
|
||||||
* <p>
|
*
|
||||||
* The {@link conflux.Ctx} class acts as a central, generic context storage
|
* The {@link conflux.Ctx} enum serves as a central, generic context storage,
|
||||||
* supporting key-based put/get operations. Each {@link conflux.Key} defines a
|
* supporting key-based put/get operations. Each {@link conflux.Key} instance
|
||||||
* unique, strongly typed entry in the context, ensuring type consistency and
|
* defines a unique, strongly typed entry in the context, ensuring type
|
||||||
* preventing misuse. {@link conflux.Listener} interfaces allow clients to
|
* consistency and preventing misuse.
|
||||||
* observe value changes for specific keys. Listeners are held with weak
|
*
|
||||||
* references to avoid memory leaks.
|
* The {@link conflux.Listener} interface allows clients to observe value
|
||||||
* <p>
|
* changes for specific keys. Listeners are weakly referenced to prevent memory
|
||||||
* Typical usage involves defining {@link conflux.Key} instances with explicit
|
* leaks.
|
||||||
* types, storing values through {@code Ctx.INSTANCE.put()}, and retrieving them
|
*
|
||||||
* with {@code Ctx.INSTANCE.get()}. Listeners can be attached via
|
* Typical usage:
|
||||||
* {@code Ctx.INSTANCE.addListener()} to react to context changes in a decoupled
|
* <ul>
|
||||||
* and thread-safe manner. Values and listeners can be removed individually or
|
* <li>Define {@link conflux.Key} instances with explicit types</li>
|
||||||
* the entire context can be cleared.
|
* <li>Store values via {@code Ctx.INSTANCE.put(key, value)}</li>
|
||||||
* <p>
|
* <li>Retrieve values via {@code Ctx.INSTANCE.get(key)}</li>
|
||||||
* <b>Best Practices:</b>
|
* <li>Register listeners with {@code Ctx.INSTANCE.addListener()}</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* Values and listeners can be removed individually, or the entire context can
|
||||||
|
* be cleared.
|
||||||
|
*
|
||||||
|
* Best practices:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>Define keys as constants to maintain consistency and avoid
|
* <li>Define keys as constants to maintain consistency and avoid
|
||||||
* collisions.</li>
|
* collisions</li>
|
||||||
* <li>Remove listeners when no longer needed (although weak references help
|
* <li>Remove listeners when no longer needed</li>
|
||||||
* prevent leaks).</li>
|
* <li>Use unique key names to avoid accidental type conflicts</li>
|
||||||
* <li>Use unique key names to ensure no accidental type conflicts.</li>
|
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* @see conflux.Ctx
|
* @see conflux.Ctx
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ package conflux;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
@@ -159,4 +160,50 @@ public class CtxTest {
|
|||||||
assertTrue(flag[0] || !flag[0]);
|
assertTrue(flag[0] || !flag[0]);
|
||||||
System.out.println("...ok");
|
System.out.println("...ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testMultipleContextsIsolation() {
|
||||||
|
System.out.println("testMultipleContextsIsolation");
|
||||||
|
var ctxA = Ctx.INSTANCE.getContext("A");
|
||||||
|
var ctxB = Ctx.INSTANCE.getContext("B");
|
||||||
|
|
||||||
|
ctxA.put(intKey, 10);
|
||||||
|
ctxB.put(intKey, 20);
|
||||||
|
|
||||||
|
assertEquals(10, ctxA.get(intKey));
|
||||||
|
assertEquals(20, ctxB.get(intKey));
|
||||||
|
assertNull(Ctx.INSTANCE.get(intKey)); // Default context is separate
|
||||||
|
|
||||||
|
ctxA.clear();
|
||||||
|
assertFalse(ctxA.contains(intKey));
|
||||||
|
assertEquals(20, ctxB.get(intKey));
|
||||||
|
|
||||||
|
System.out.println("...ok");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testListenerNotificationInSeparateContexts() {
|
||||||
|
System.out.println("testListenerNotificationInSeparateContexts");
|
||||||
|
var ctxA = Ctx.INSTANCE.getContext("A");
|
||||||
|
var ctxB = Ctx.INSTANCE.getContext("B");
|
||||||
|
|
||||||
|
var resultA = new StringBuilder();
|
||||||
|
var resultB = new StringBuilder();
|
||||||
|
|
||||||
|
Listener<Integer> listenerA = v -> resultA.append(v);
|
||||||
|
Listener<Integer> listenerB = v -> resultB.append(v);
|
||||||
|
|
||||||
|
ctxA.addListener(intKey, listenerA);
|
||||||
|
ctxB.addListener(intKey, listenerB);
|
||||||
|
|
||||||
|
ctxA.put(intKey, 1);
|
||||||
|
ctxB.put(intKey, 2);
|
||||||
|
ctxA.put(intKey, 3);
|
||||||
|
ctxB.put(intKey, 4);
|
||||||
|
|
||||||
|
assertEquals("13", resultA.toString());
|
||||||
|
assertEquals("24", resultB.toString());
|
||||||
|
|
||||||
|
System.out.println("...ok");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user