This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "synchronizing access to file" Watch "synchronizing access to file" New topic

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

Joined: Mar 22, 2000
Posts: 12676
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.
author of:

Java Resources at
I agree. Here's the link:
subject: synchronizing access to file
Similar Threads
inputting file path to java servlets
Help with directory tree in JSP/Servlet
FileInputStream in Servlets
Refresh a Singleton Object values
how to create a file on server for ALL clients to use ?