![JAR search and dependency download from the Maven repository](/logo.png)
com.g2forge.alexandria.java.resource.StackThreadResource Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ax-java Show documentation
Show all versions of ax-java Show documentation
Standard Java library and the basis of the ${alexandria.name} project.
package com.g2forge.alexandria.java.resource;
import java.util.Stack;
import java.util.function.Function;
import java.util.function.Supplier;
import com.g2forge.alexandria.java.close.ICloseable;
import com.g2forge.alexandria.java.function.LiteralSupplier;
public class StackThreadResource implements ICloseableResource {
protected final ThreadLocal> local;
public StackThreadResource() {
this.local = ThreadLocal.withInitial(Stack::new);
}
public StackThreadResource(Supplier extends T> initial) {
this.local = ThreadLocal.withInitial(() -> {
final Stack stack = new Stack<>();
stack.add(initial.get());
return stack;
});
}
public StackThreadResource(T initial) {
this(new LiteralSupplier<>(initial));
}
public int depth() {
return local.get().size();
}
@Override
public T get() {
return local.get().peek();
}
public ICloseable modify(Function super T, ? extends T> function) {
final Stack stack = local.get();
final T value = function.apply(stack.peek());
stack.push(value);
return () -> {
if (stack.pop() != value) throw new IllegalStateException();
};
}
@Override
public ICloseable open(T value) {
final Stack stack = local.get();
stack.push(value);
return () -> {
if (stack.pop() != value) throw new IllegalStateException();
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy