Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronizing access to file

 
Micah Wedemeyer
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that writes to a file inside my servlet. If I synchronize that method, will each instantiation of the servlet wait its turn to access the file?
I don't know much about servlets, and I am just assuming that a single one (source) can be running multiple instances of itself (processes) at the same time.
Basically, what I am saying is: How do I make sure only 1 process accesses the file at a time?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The most important point is that normally there will be only one instance of the servlet. However, multiple Threads may be processing requests at the same time using that instance.
If you have a File object representing the file:
File myLogFile ;
Then you can use that to synchronize on - just make sure you catch all the possible exceptions correctly. In other words, you can have a block of synchronized code like this:
synchronized( myLogFile ){
// open, write, close, etc.
}
Bill
------------------
author of:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic