Synchronized File IO in Java
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Bhavin_Mehta
Posted On:   Saturday, October 19, 2002 12:46 AM


I want to update an XML file using Simple Java File IO
Which is required to be Synchronized i.e 1 thread at a time.


The Problem is that my application is ported on a
Weblogic 5.1 server which is running in cluster
how do i achieve Synchronized file io in this case.?
will a simple Synchronized block do the trick?

as weblogic is running in cluster mode there might be more then 1 jvm running.


Thanks,
Bhavin

Re: Synchronized File IO in Java

Posted By:   Shawn_Alexander  
Posted On:   Sunday, November 10, 2002 05:25 PM

Eric's idea has a lot of merit and i would certainly recommend it if a database is available.



However, if you wish to avoid the performance and latency issues or creating transactions to the database, there are other options. Here is one that I thought of, changing the extension of the file to locked.



1) JVM 1 searches for the fie with the original extension. If found, the class changes the file extension to something like *.LOCKED. The class then continues its update and modifications to the file. After saving it, the file extension is changed back to the original .xml.



2) if the JVM cannot find the file, it searches for the file with a .LOCKED extension. If it exists, the JVM waits for an interval of time before checking again. When the file becomes available, the JVM proceeds with step one. After x number of tries, if a lock cannot be obtained, the thread throws an exception (FileNotAvailableException or something similiar).



CAUTIONARY NOTE: Thread death is possible in this scenario (ie, a thread may "try for a lock" for a period of time and never obtain it). That is why in step two, the thread attempts a lock for x number of times and throws an exception if the file is still not available.




One question, why do you want to use this approach? If it is for logging, why not have a file on a per JVM basis? Can multiple files be created (one per JVM) and the files merged later?



Shawn

Re: Synchronized File IO in Java

Posted By:   Eric_Lindauer  
Posted On:   Tuesday, October 22, 2002 08:39 PM

Hi,



I don't know about WebLogic in particular, but one strategy for synchronizing multiple JVMs is to let the database do the work. With pessimistic transactions you can lock out other JVMs from making changes to an object so...




step 1: obtain a singleton database object in a transaction <-- database locks until other JVM releases object

step 2: perform file IO work

step 3: end transaction





Hope this helps.

Eric
About | Sitemap | Contact