ss: Remove cache-level synchronization in HT_IO
[deliverable/tracecompass.git] / statesystem / org.eclipse.tracecompass.statesystem.core / src / org / eclipse / tracecompass / internal / statesystem / core / backend / historytree / HT_IO.java
CommitLineData
a52fde77 1/*******************************************************************************
60ae41e1 2 * Copyright (c) 2012, 2014 Ericsson
a52fde77
AM
3 * Copyright (c) 2010, 2011 École Polytechnique de Montréal
4 * Copyright (c) 2010, 2011 Alexandre Montplaisir <alexandre.montplaisir@gmail.com>
3de60236 5 *
a52fde77
AM
6 * All rights reserved. This program and the accompanying materials are
7 * made available under the terms of the Eclipse Public License v1.0 which
8 * accompanies this distribution, and is available at
9 * http://www.eclipse.org/legal/epl-v10.html
3de60236 10 *
a52fde77
AM
11 *******************************************************************************/
12
e894a508 13package org.eclipse.tracecompass.internal.statesystem.core.backend.historytree;
a52fde77 14
1f48ef66
AM
15import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
16
a52fde77
AM
17import java.io.File;
18import java.io.FileInputStream;
19import java.io.FileOutputStream;
20import java.io.IOException;
3b7f5abe 21import java.nio.channels.ClosedChannelException;
a52fde77 22import java.nio.channels.FileChannel;
b2648641 23import java.util.logging.Logger;
a52fde77 24
aa353506 25import org.eclipse.jdt.annotation.NonNull;
b2648641 26import org.eclipse.tracecompass.common.core.log.TraceCompassLog;
1f48ef66
AM
27import java.util.Objects;
28import java.util.concurrent.ExecutionException;
29
30import org.eclipse.jdt.annotation.Nullable;
49a817d5
MK
31import org.eclipse.tracecompass.internal.statesystem.core.Activator;
32
1f48ef66
AM
33import com.google.common.cache.CacheBuilder;
34import com.google.common.cache.CacheLoader;
35import com.google.common.cache.LoadingCache;
36
a52fde77 37/**
360f899e
EB
38 * This class abstracts inputs/outputs of the HistoryTree nodes.
39 *
40 * It contains all the methods and descriptors to handle reading/writing nodes
41 * to the tree-file on disk and all the caching mechanisms.
42 *
49a817d5
MK
43 * This abstraction is mainly for code isolation/clarification purposes. Every
44 * HistoryTree must contain 1 and only 1 HT_IO element.
3de60236 45 *
ffd0aa67 46 * @author Alexandre Montplaisir
a52fde77
AM
47 */
48class HT_IO {
4018d70a 49
1f48ef66
AM
50 private static final Logger LOGGER = TraceCompassLog.getLogger(HT_IO.class);
51
52 // ------------------------------------------------------------------------
53 // Global cache of nodes
54 // ------------------------------------------------------------------------
55
56 private static final class CacheKey {
57
58 public final HT_IO fStateHistory;
59 public final int fSeqNumber;
4018d70a 60
1f48ef66
AM
61 public CacheKey(HT_IO stateHistory, int seqNumber) {
62 fStateHistory = stateHistory;
63 fSeqNumber = seqNumber;
4018d70a
MK
64 }
65
1f48ef66
AM
66 @Override
67 public int hashCode() {
68 return Objects.hash(fStateHistory, fSeqNumber);
4018d70a
MK
69 }
70
1f48ef66
AM
71 @Override
72 public boolean equals(@Nullable Object obj) {
73 if (this == obj) {
74 return true;
75 }
76 if (obj == null) {
77 return false;
78 }
79 if (getClass() != obj.getClass()) {
80 return false;
81 }
82 CacheKey other = (CacheKey) obj;
83 return (fStateHistory.equals(other.fStateHistory) &&
84 fSeqNumber == other.fSeqNumber);
4018d70a
MK
85 }
86 }
87
1f48ef66
AM
88 private static final int CACHE_SIZE = 256;
89
90 private static final LoadingCache<CacheKey, HTNode> NODE_CACHE =
91 checkNotNull(CacheBuilder.newBuilder()
92 .maximumSize(CACHE_SIZE)
93 .build(new CacheLoader<CacheKey, HTNode>() {
94 @Override
95 public HTNode load(CacheKey key) throws IOException {
96 HT_IO io = key.fStateHistory;
97 int seqNb = key.fSeqNumber;
98
99 LOGGER.finest(() -> "[HtIo:CacheMiss] seqNum=" + seqNb); //$NON-NLS-1$
100
4790127e
AM
101 synchronized (io) {
102 io.seekFCToNodePos(io.fFileChannelIn, seqNb);
103 return HTNode.readNode(io.fConfig, io.fFileChannelIn);
104 }
1f48ef66
AM
105 }
106 }));
107
108
109 // ------------------------------------------------------------------------
110 // Instance fields
111 // ------------------------------------------------------------------------
112
360f899e
EB
113 /* Configuration of the History Tree */
114 private final HTConfig fConfig;
a52fde77
AM
115
116 /* Fields related to the file I/O */
c772ff74
MK
117 private final FileInputStream fFileInputStream;
118 private final FileOutputStream fFileOutputStream;
119 private final FileChannel fFileChannelIn;
120 private final FileChannel fFileChannelOut;
a52fde77 121
1f48ef66
AM
122 // ------------------------------------------------------------------------
123 // Methods
124 // ------------------------------------------------------------------------
125
6993c1ca 126
b2648641 127
a52fde77
AM
128 /**
129 * Standard constructor
3de60236 130 *
360f899e 131 * @param config
49a817d5 132 * The configuration object for the StateHistoryTree
ab604305 133 * @param newFile
360f899e 134 * Flag indicating that the file must be created from scratch
49a817d5 135 *
a52fde77 136 * @throws IOException
360f899e 137 * An exception can be thrown when file cannot be accessed
a52fde77 138 */
8d47cc34 139 public HT_IO(HTConfig config, boolean newFile) throws IOException {
360f899e 140 fConfig = config;
a52fde77 141
360f899e 142 File historyTreeFile = config.getStateFile();
a52fde77 143 if (newFile) {
360f899e 144 boolean success1 = true;
a52fde77
AM
145 /* Create a new empty History Tree file */
146 if (historyTreeFile.exists()) {
ab604305
AM
147 success1 = historyTreeFile.delete();
148 }
cb42195c 149 boolean success2 = historyTreeFile.createNewFile();
ab604305
AM
150 if (!(success1 && success2)) {
151 /* It seems we do not have permission to create the new file */
152 throw new IOException("Cannot create new file at " + //$NON-NLS-1$
153 historyTreeFile.getName());
a52fde77 154 }
c772ff74
MK
155 fFileInputStream = new FileInputStream(historyTreeFile);
156 fFileOutputStream = new FileOutputStream(historyTreeFile, false);
a52fde77
AM
157 } else {
158 /*
159 * We want to open an existing file, make sure we don't squash the
160 * existing content when opening the fos!
161 */
c772ff74
MK
162 fFileInputStream = new FileInputStream(historyTreeFile);
163 fFileOutputStream = new FileOutputStream(historyTreeFile, true);
a52fde77 164 }
c772ff74
MK
165 fFileChannelIn = fFileInputStream.getChannel();
166 fFileChannelOut = fFileOutputStream.getChannel();
a52fde77
AM
167 }
168
a52fde77 169 /**
8d47cc34 170 * Read a node from the file on disk.
3b7f5abe 171 *
8d47cc34
AM
172 * @param seqNumber
173 * The sequence number of the node to read.
174 * @return The object representing the node
3b7f5abe
AM
175 * @throws ClosedChannelException
176 * Usually happens because the file was closed while we were
177 * reading. Instead of using a big reader-writer lock, we'll
178 * just catch this exception.
a52fde77 179 */
4790127e 180 public @NonNull HTNode readNode(int seqNumber) throws ClosedChannelException {
1f48ef66
AM
181 /* Do a cache lookup. If it's not present it will be loaded from disk */
182 LOGGER.finest(() -> "[HtIo:CacheLookup] seqNum=" + seqNumber); //$NON-NLS-1$
183 CacheKey key = new CacheKey(this, seqNumber);
a52fde77 184 try {
1f48ef66 185 return checkNotNull(NODE_CACHE.get(key));
6993c1ca 186
1f48ef66
AM
187 } catch (ExecutionException e) {
188 /* Get the inner exception that was generated */
189 Throwable cause = e.getCause();
190 if (cause instanceof ClosedChannelException) {
191 throw (ClosedChannelException) cause;
192 }
4018d70a 193 /*
1f48ef66 194 * Other types of IOExceptions shouldn't happen at this point though.
4018d70a 195 */
49a817d5 196 Activator.getDefault().logError(e.getMessage(), e);
aa353506 197 throw new IllegalStateException();
a52fde77
AM
198 }
199 }
200
4790127e 201 public void writeNode(HTNode node) {
a52fde77 202 try {
6993c1ca 203 int seqNumber = node.getSequenceNumber();
1f48ef66
AM
204
205 /* "Write-back" the node into the cache */
206 CacheKey key = new CacheKey(this, seqNumber);
207 NODE_CACHE.put(key, node);
6993c1ca 208
a52fde77 209 /* Position ourselves at the start of the node and write it */
4790127e
AM
210 synchronized (this) {
211 seekFCToNodePos(fFileChannelOut, seqNumber);
212 node.writeSelf(fFileChannelOut);
213 }
a52fde77
AM
214 } catch (IOException e) {
215 /* If we were able to open the file, we should be fine now... */
49a817d5 216 Activator.getDefault().logError(e.getMessage(), e);
a52fde77
AM
217 }
218 }
219
e8b7cc14 220 public FileChannel getFcOut() {
c772ff74 221 return fFileChannelOut;
a52fde77
AM
222 }
223
8d47cc34 224 public FileInputStream supplyATReader(int nodeOffset) {
a52fde77
AM
225 try {
226 /*
227 * Position ourselves at the start of the Mapping section in the
228 * file (which is right after the Blocks)
229 */
c772ff74 230 seekFCToNodePos(fFileChannelIn, nodeOffset);
a52fde77 231 } catch (IOException e) {
49a817d5 232 Activator.getDefault().logError(e.getMessage(), e);
a52fde77 233 }
c772ff74 234 return fFileInputStream;
a52fde77
AM
235 }
236
8d47cc34 237 public synchronized void closeFile() {
3de60236 238 try {
c772ff74
MK
239 fFileInputStream.close();
240 fFileOutputStream.close();
3de60236 241 } catch (IOException e) {
49a817d5 242 Activator.getDefault().logError(e.getMessage(), e);
3de60236 243 }
1a4205d9
AM
244 }
245
8d47cc34 246 public synchronized void deleteFile() {
1a4205d9 247 closeFile();
3de60236 248
360f899e 249 File historyTreeFile = fConfig.getStateFile();
6993c1ca 250 if (!historyTreeFile.delete()) {
36bf82a2 251 /* We didn't succeed in deleting the file */
49a817d5 252 Activator.getDefault().logError("Failed to delete" + historyTreeFile.getName()); //$NON-NLS-1$
36bf82a2
AM
253 }
254 }
255
a52fde77
AM
256 /**
257 * Seek the given FileChannel to the position corresponding to the node that
258 * has seqNumber
3de60236 259 *
49a817d5
MK
260 * @param fc
261 * the channel to seek
262 * @param seqNumber
263 * the node sequence number to seek the channel to
a52fde77 264 * @throws IOException
49a817d5 265 * If some other I/O error occurs
a52fde77
AM
266 */
267 private void seekFCToNodePos(FileChannel fc, int seqNumber)
268 throws IOException {
a52fde77 269 /*
360f899e 270 * Cast to (long) is needed to make sure the result is a long too and
a52fde77
AM
271 * doesn't get truncated
272 */
360f899e 273 fc.position(HistoryTree.TREE_HEADER_SIZE
49a817d5 274 + ((long) seqNumber) * fConfig.getBlockSize());
a52fde77
AM
275 }
276
277}
This page took 0.110392 seconds and 5 git commands to generate.