Two Laptop Bag*
The moose likes Servlets and the fly likes synchronizing access to file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "synchronizing access to file" Watch "synchronizing access to file" New topic
Author

synchronizing access to file

Micah Wedemeyer
Ranch Hand

Joined: Jun 11, 2001
Posts: 68
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

Joined: Mar 22, 2000
Posts: 12769
    
    5
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:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronizing access to file