I'm attempting to cache contents of a file to avoid frequent reads, using a very simple implementation in a single class. The file contains a list of emailids, one per line. The file changes rarely, and the cache should be updated immediately when it does. So I've checked the file's timestamp in each read operation. The class will be used in servlets and rest apis - as member variable. Although I've synchronized the only public method of the class, I'm not sure whether the code is threadsafe. Do I need to add/change something here to ensure thread safety ?
public class CachedFile {
private File file ;
private long lastModified ;
private List<String> fileLines ;
private boolean fileCached ;
public CachedFile( final String inputFileName )
{
file = new File( inputFileName ) ;
fileCached = false ;
}
public synchronized List<String> getLines() throws IOException
{
//if file is not cached or if its modified after the last read, read & cache it
if( fileCached == false || fileModifiedAfterLastRead() )
{
readFile() ;
}
return fileLines ;
}
private void readFile() throws IOException
{
//read file to cache
fileLines = FileUtils.readLines( file ) ;
//cache the last modified time
lastModified = file.lastModified() ;
//set the cached flag to true
fileCached = true ;
}
private boolean fileModifiedAfterLastRead()
{
return( file.lastModified() > lastModified ) ;
}
}
file
might no longer be valid. \$\endgroup\$