• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to synchronize

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic