Try to close alive ChronicleMaps on JVM shutdown

This commit is contained in:
leventov
2016-10-02 18:42:39 +03:00
parent 4b1f11dd3a
commit a2c8ac4866
4 changed files with 101 additions and 8 deletions
@@ -164,12 +164,25 @@ public abstract class VanillaChronicleHash<K,
private transient ArrayList<WeakReference<ChainingInterface>> allContexts;
public VanillaChronicleHash(ChronicleMapBuilder<K, ?> builder) {
createdOrInMemory = true;
/**
* {@link net.openhft.chronicle.map.ChronicleMapCloseOnExitHook} needs to use
* {@code VanillaChronicleHash}es as WeakHashMap keys, but with identity comparison, not Map's
* equals() and hashCode().
*/
public class Identity {
public VanillaChronicleHash hash() {
return VanillaChronicleHash.this;
}
}
public transient Identity identity;
public VanillaChronicleHash(ChronicleMapBuilder<K, ?> builder) {
// Version
dataFileVersion = BuildVersion.version();
createdOrInMemory = true;
@SuppressWarnings({"deprecation", "unchecked"})
ChronicleHashBuilderPrivateAPI<K, ?> privateAPI =
(ChronicleHashBuilderPrivateAPI<K, ?>) builder.privateAPI();
@@ -231,13 +244,13 @@ public abstract class VanillaChronicleHash<K,
}
protected void readMarshallableFields(@NotNull WireIn wireIn) {
dataFileVersion = wireIn.read(() -> "dataFileVersion").text();
// Previously this assignment was done in default field initializer, but with Wire
// serialization VanillaChronicleMap instance is created with unsafe.allocateInstance(),
// that doesn't guarantee (?) to initialize fields with default values (false for boolean)
createdOrInMemory = false;
dataFileVersion = wireIn.read(() -> "dataFileVersion").text();
keyClass = wireIn.read(() -> "keyClass").typeLiteral();
keySizeMarshaller = wireIn.read(() -> "keySizeMarshaller").typedMarshallable();
keyReader = wireIn.read(() -> "keyReader").typedMarshallable();
@@ -385,6 +398,7 @@ public abstract class VanillaChronicleHash<K,
tierHashLookupSlotSize + " observed");
}
allContexts = new ArrayList<>();
identity = new Identity();
}
public final void initBeforeMapping(
@@ -1504,14 +1504,19 @@ public final class ChronicleMapBuilder<K, V> implements
} finally {
if (result != null) {
result.registerRafReleaser();
// Ensure safe publication of a ChronicleMap
OS.memory().storeFence();
prepareMapPublication(result);
} else {
CanonicalRandomAccessFiles.release(file);
}
}
}
private static void prepareMapPublication(VanillaChronicleMap map) {
// Ensure safe publication of a ChronicleMap
OS.memory().storeFence();
ChronicleMapCloseOnExitHook.add(map);
}
/**
* @return size of the self bootstrapping header
*/
@@ -1669,8 +1674,7 @@ public final class ChronicleMapBuilder<K, V> implements
lazyNativeBytesStoreWithFixedCapacity(map.sizeInBytesWithoutTiers());
map.createMappedStoreAndSegments(bytesStore);
establishReplication(map);
// Ensure "safe publication" of a ChronicleMap
OS.memory().storeFence();
prepareMapPublication(map);
return map;
} catch (IOException e) {
// file-less version should never trigger an IOException.
@@ -0,0 +1,73 @@
/*
* Copyright (C) 2016 Roman Leventov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.impl.VanillaChronicleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.TreeMap;
import java.util.WeakHashMap;
final class ChronicleMapCloseOnExitHook {
private static final Logger LOG = LoggerFactory.getLogger(ChronicleMapCloseOnExitHook.class);
private static WeakHashMap<VanillaChronicleHash.Identity, Long> maps = new WeakHashMap<>();
private static long order = 0;
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
closeAll();
}
});
}
static synchronized void add(VanillaChronicleHash hash) {
if (maps == null)
throw new IllegalStateException("Shutdown in progress");
maps.put(hash.identity, order++);
}
private static void closeAll() {
try {
WeakHashMap<VanillaChronicleHash.Identity, Long> maps;
synchronized (ChronicleMapCloseOnExitHook.class) {
maps = ChronicleMapCloseOnExitHook.maps;
ChronicleMapCloseOnExitHook.maps = null;
}
TreeMap<Long, VanillaChronicleHash> orderedMaps = new TreeMap<>();
maps.forEach((identity, order) -> orderedMaps.put(order, identity.hash()));
// close later added maps first
orderedMaps.descendingMap().values().forEach(h -> {
try {
h.close();
} catch (RuntimeException | AssertionError e) {
LOG.error("", e);
}
});
} catch (Throwable t) {
LOG.error("", t);
throw t;
}
}
private ChronicleMapCloseOnExitHook() {}
}