The moose likes Threads and Synchronization and the fly likes Auto save thread in a Swing application Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Auto save thread in a Swing application" Watch "Auto save thread in a Swing application" New topic
Author

Auto save thread in a Swing application

Veronique Kus
Ranch Hand

Joined: Jun 13, 2010
Posts: 41
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
Saloon Keeper

Joined: Jul 26, 2007
Posts: 7059

This would be more suitable on the Thread forums.
Moving.


[Donate a pint, save a life!] [How to ask questions]
Veronique Kus
Ranch Hand

Joined: Jun 13, 2010
Posts: 41
Anyone, please?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 23248

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.


[Jess in Action][AskingGoodQuestions]
Veronique Kus
Ranch Hand

Joined: Jun 13, 2010
Posts: 41
Thanks!
 
 
subject: Auto save thread in a Swing application
 
developer file tools