
com.thejohnfreeman.attribute.LateBoundAttribute Maven / Gradle / Ivy
Show all versions of lazy Show documentation
package com.thejohnfreeman.attribute;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.thejohnfreeman.lazy.LateBound;
import com.thejohnfreeman.lazy.Lazy;
/**
* An attribute that may be "read" (in the sense that its lazy wrapper is
* stored) before it is written.
*
* @author thejohnfreeman
*/
public class LateBoundAttribute
implements Attribute
{
private final Map> _attrs = new ConcurrentHashMap<>();
private Lazy getOrCreate(final N node) {
return _attrs.computeIfAbsent(node, k -> LateBound.of());
}
/**
* {@inheritDoc}
*
*
* May be called before the node's value has been
* {@link #put(Object, Lazy)}.
*/
@Override
public Lazy get(final N node) {
return getOrCreate(node);
}
@Override
public void put(final N node, final Lazy value)
throws IllegalStateException
{
final Lazy existing = _attrs.get(node);
if (existing != null) {
if (existing instanceof LateBound) {
((LateBound)existing).bind(value);
} else {
throw new IllegalStateException(String.format(
"attribute already assigned:%n key: %s%n value: %s",
node, value));
}
}
_attrs.put(node, value);
}
}