Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to synchronize

 
Renata fonseca
Ranch Hand
Posts: 48
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that access some DATABASE and write the result to a file. Like this...

yyy class will be INSTANTIATE by the servlet.
The point is IF some request execute the first line (#1), it MUST execute the second line (#2) IMMEDIATELY because I want to preserve the order of line that is writing to file. If some other threading (by another client request) execute between #1 and #2 of firt request, I'll have a file output like this:
-- somefile.txt (just an example) --
BD - Autoincrement column = 2
BD - Autoincrement column = 1
I tried to put synchronized keyword in the method, but it didn't work.
My test: I press the F5 key (refresh) of browser many times (quickly)... and when I see the file, some line is not in order.
Why didn't synchronized help me?
 
Steve Granton
Ranch Hand
Posts: 200
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
This should probably be in the Threads group - did you post there too?
Presumably (though I can't tell for sure as you haven't included the code) each instance of class yyy has its own file pointer to the file. Therefore you are simply synchronising on different instances of the file class. What you need is a single point (probably a helper class) that all classes use when they want to write to the file - effectively you write a wrapper/protector for the file, which you may wish to implement as a singleton to ensure that only one instance of the wrapper can be created. This helper can then control access and writes to the file so that they appear in the order they are meant to.
Things will get more complicated if you need to do this from different JVMs but by your description it appears to be from one JVM. However, with it being a servlet you will need to consider what will happen if you need to cluster the application servers - you will then have a number of jvms.
I hope this helps.
Steve
[ January 31, 2003: Message edited by: Steve Granton ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic