• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File reloading problem

 
Patrik Westlund
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone!
I have a problem with a servlet. It's displaying short news articles which it reads from files, one article per file. When a file is added (or removed) I want the changes to show up on the web page. The code that loads the files look like this:
******
public void loadArticles() throws ArticleFileException {
pathFile = new File(path);
articleList = new ArrayList();
articleFile = pathFile.listFiles();
FileReader fr;
char[] buffer;
Article article;
File file;
for(int i=0;i<articleFile.length;i++) {
file = articleFile[i];
buffer = new char[(int) file.length()];
try {
fr = new FileReader(file);
fr.read(buffer);
fr.close();
} catch (IOException exc) {
throw new ArticleFileException("IO Exception when reading file: " + file.getName());
}
String block = new String(buffer);
article = new Article(block);
articleList.add(article);
}
}
}
*******
Path is the path to the directory where the files are located. Always the same.
This method is called from the servlet's init() the first time. When an article has been added I call this method again by visiting a web page that only call this method. But the servlet still displays the old content. Does anyone know what my error is? Probably a simple one...
I'm using TeaServlet (from opensource.go.com) to handle the html layout on the pages.
I appreciate any suggestions. Thanks!
/Patrik
 
Zakaria Haque
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at this part of your code
//within loop
article = new Article(block);
articleList.add(article);
everytime you are adding new articles to the List, but not replacing the old one. a simple solution would be to create a new List, and assign its reference to the articleList variable, here is the pseudo code
List articleTempList = new List();
for(...... ){
....
article = new Article(block);
articleTempList.add(article);
}
articleList = articleTempList;
technically you should make the articleList volatile, since sifferent threads are usign this variable and you want to avoid any caching at thread's so called working memory.

But There could be another issue. You are keeping all the articles in memory. Depending on the size and number of files it could slow down the system significantly. Use a caching mechanism (for simplicity you can just use a LRU cache) to resolve this. If you need any help with the cache, post your questions.
 
Patrik Westlund
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Volatile was the solution for the problem. Now it works. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic