MemValueFactory valueFactory = createValueFactory();
currentSnapshot = 1;
if (persist) {
File dataDir = getDataDir();
DirectoryLockManager locker = new DirectoryLockManager(dataDir);
dataFile = new File(dataDir, DATA_FILE_NAME);
syncFile = new File(dataDir, SYNC_FILE_NAME);
if (dataFile.exists()) {
logger.debug("Reading data from {}...", dataFile);
// Initialize persistent store from file
if (!dataFile.canRead()) {
logger.error("Data file is not readable: {}", dataFile);
throw new StoreException("Can't read data file: " + dataFile);
}
// try to create a lock for later writing
dirLock = locker.tryLock();
if (dirLock == null) {
logger.warn("Failed to lock directory: {}", dataDir);
}
// Don't try to read empty files: this will result in an
// IOException, and the file doesn't contain any data anyway.
if (dataFile.length() == 0L) {
logger.warn("Ignoring empty data file: {}", dataFile);
}
else {
try {
new FileIO(this, valueFactory).read(dataFile);
logger.debug("Data file read successfully");
}
catch (IOException e) {
logger.error("Failed to read data file", e);
throw new StoreException(e);
}
}
}
else {
// file specified that does not exist yet, create it
try {
File dir = dataFile.getParentFile();
if (dir != null && !dir.exists()) {
logger.debug("Creating directory for data file...");
if (!dir.mkdirs()) {
logger.debug("Failed to create directory for data file: {}", dir);
throw new StoreException("Failed to create directory for data file: " + dir);
}
}
// try to lock directory or fail
dirLock = locker.lockOrFail();
logger.debug("Initializing data file...");
new FileIO(this, valueFactory).write(syncFile, dataFile);
logger.debug("Data file initialized");
}