• Post Reply Bookmark Topic Watch Topic
  • New Topic

Auto save thread in a Swing application  RSS feed

 
Veronique Kus
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got an application with a Swing GUI and I want it to save some data at a regular time intervals. I've just created a new auto save thread in my application based on the below example code found o the internet:


My question relates to the two last lines (the commented out ones).
ad. 1) The auto save thread is created in the main class called X. This class contains method saveDatabaseToFile() which calls a function located in another class (Y) which saves the state of the database to file. My question is, which of these two methods should be synchronized - the one in class X or the one in class Y?
ad. 2) What does the author mean in here? The function that shuts down the program is located in class X and consists of only two lines:
protected void quit(){
frame.dispose();
System.exit(0);
}
It it enough to just make this function synchronized to (and why is it needed anyway)? What does "synchronized on *SAME* object" mean?

This is the first time I am doing multithreading so I am quite confused. Thank you in advance for any hints.

 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This would be more suitable on the Thread forums.
Moving.
 
Veronique Kus
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anyone, please?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Who wrote the comments? Are they part of the sample code, or were they added by someone else? They may be slightly taken out of context, especially the second one, but I think the concern is that we don't want the application to call System.exit() while we're in the middle of a save, or the application could exit while the save file is incomplete, thus losing data.

It's not so much that saveDatabaseToFile() or any other such methods should be synchronized; it's that there should be an application-level lock object -- say like this:



and then any code that does some critical operation (like overwriting a file, and especially like exiting the application) should grab that lock first; i.e.,



or



that way you can't exit during a save.
 
Veronique Kus
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!