org.jenetics.util.Context Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of org.jenetics Show documentation
Show all versions of org.jenetics Show documentation
Jenetics - Java Genetic Algorithm Library
/*
* Java Genetic Algorithm Library (jenetics-3.1.0).
* Copyright (c) 2007-2015 Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package org.jenetics.util;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
/**
* @author Franz Wilhelmstötter
* @version 2.0
* @since 3.0
*/
final class Context {
private final T _default;
private final AtomicReference> _entry;
private final ThreadLocal> _threadLocalEntry = new ThreadLocal<>();
Context(final T defaultValue) {
_default = defaultValue;
_entry = new AtomicReference<>(new Entry<>(defaultValue));
}
void set(final T value) {
final Entry e = _threadLocalEntry.get();
if (e != null) e.value = value; else _entry.set(new Entry(value));
}
T get() {
final Entry e = _threadLocalEntry.get();
return (e != null ? e : _entry.get()).value;
}
void reset() {
set(_default);
}
R with(final S value, final Function f) {
final Entry e = _threadLocalEntry.get();
if (e != null) {
_threadLocalEntry.set(e.inner(value));
} else {
_threadLocalEntry.set(new Entry(value, Thread.currentThread()));
}
try {
return f.apply(value);
} finally {
_threadLocalEntry.set(_threadLocalEntry.get().parent);
}
}
/**
* @author Franz Wilhelmstötter
* @version 2.0
* @since 2.0
*/
private static final class Entry {
final Thread thread;
final Entry parent;
T value;
Entry(final T value, final Entry parent, final Thread thread) {
this.value = value;
this.parent = parent;
this.thread = thread;
}
Entry(final T value, final Thread thread) {
this(value, null, thread);
}
Entry(final T value) {
this(value, null, null);
}
Entry inner(final T value) {
assert(thread == Thread.currentThread());
return new Entry<>(value, this, thread);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy