Skip to content

Instantly share code, notes, and snippets.

@ThakurPriyanka
Created June 2, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThakurPriyanka/35e996536714d63ce8fedbed5898eb3b to your computer and use it in GitHub Desktop.
Save ThakurPriyanka/35e996536714d63ce8fedbed5898eb3b to your computer and use it in GitHub Desktop.
//Helper Class for read and write operations for a file.
class FileStore {
private File storeFolder;
// Locks is used so that only one thread can update the file at a
// time.
private ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* Construct an FileStore Store
* @param storeFolder This folder will be used to store the object data.
*/
FileBasedObjectStore(Path storeFolder) {
this.storeFolder = storeFolder.toFile();
}
/**
* Reads the file from the file store.
*
* @param id - the ID of the object
* @return the object if it exists or empty if it does not.
*/
@Override
public Optional<Object> read(UUID id) {
lock.readLock().lock();
File file = new File(storeFolder, id.toString());
Optional<Object> result;
try (
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn)
) {
result = Optional.ofNullable(in.readObject());
} catch ( IOException | ClassNotFoundException ex) {
result = Optional.empty();
} finally {
lock.readLock().unlock();
}
return result;
}
/**
* Writes an object to a file in the file store.
*
* @param id - the id of the object being written.
* @param obj - the object to be written.
* @return true if the write was successful, false if it failed.
*/
@Override
public boolean write(UUID id, Object content) {
// lock before we can write i file
lock.writeLock().lock();
File file = new File(storeFolder, id.toString());
boolean result;
try (
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut)
) {
out.writeObject(content);
result = true;
} catch (IOException ex) {
result = false;
} finally {
lock.writeLock().unlock();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment