On Thursday Jul 6, 2000, Marcos Lloret wrote:

> hi,
> 
> i have running a sevlets that reads from a file a number and it adds
> one more. after changes it saves.
>     i want to use the same file from another servlet. any problem?? if
> both servlets try to open and save at the same time.
> 
>         file =  4455
> 
> servlet 1                                              servlet2
> {                                                          {
> read from file   4455                            read from file 4455
> ++                                                        ++
> 4456                                                     4456
> save                                                     save
> }                                                           }
> 
> it is wrong. in file should be  4457.

Big problems. Welcome to the world of multi-threaded (or thread
safe) programming.

You need to find some way to synchronize access to the file so that
different readers / writers don't step on each other.

Some ideas:

When some servlet wants to access the file with the number in it
(I'll call it the "counter" file), it must check for a "lock" file
on the filesystem. If the file doesn't exist, it creates it. If the
creation is successful, it can go ahead and modify the counter
file. When it is done making the changes (and has closed the counter
file), it deletes the lock file. 

Any servlet that wants to modify the counter file must be made to
wait until it can create the "lock" file.

There are some problems with the above approach, but it illustrates
the concept.


Another (probably much better) approach is to have a single servlet
that has the responsibility of modifying the counter file (call it
the "counter" servlet). Any worker servlet that wants to make
changes to the counter file must make a call to the counter
servlet. All the methods in the counter servlet that can be accessed
from your worker servlets must by declared "synchronized". This
tells the Java VM to only let one thread into that method at one
time. This way, all of the callers will need to wait their turn
to read or write the file.

This has some implications on performance, but that's the classic
tradeoff between safety and performance in this type of programming.

Good luck
-John

----------------------------------------------------------------
John Rousseau                               [EMAIL PROTECTED]
SilverStream Software                     Phone: +1 978 262 3564
2 Federal Street                            Fax: +1 978 262 3499
Billerica, MA 01821                  http://www.silverstream.com
----------------------------------------------------------------


----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]

Reply via email to