Solved

Java File lock

Posted on 2009-03-31
8
543 Views
Last Modified: 2013-11-24
I am using the following method to marshal user specific data to an XML file using Castor.  I would like to insure that multiple-threads are NOT saving the same user file at the same time..

Any suggestions would be appreciated

Thanks,
public boolean saveUserFilterFile() {

	Debug.debug(

		"WebViewUser.saveUserFilterFile() - entry",

		Debug.LEVEL_TRACE);

	if ((isCreateNewFilter()|| isAdministrator()) && saveFilter) {

		FilterGroupList expFl = new FilterGroupList();

	

		FileWriter writer  = null;

		String filename =

			ExpAppProperties.getExpFilterPath() + getUserName() + ".xml";

		String tempFileName = ExpAppProperties.getExpFilterPath() + "~~" + getUserName() + ".xml";

		try {

			//---( Clear current FilterGroupList in expUserProperties )---

			//---( Step through consolidated filter list copying user groups to expUserProperties )--

			for (Enumeration fl = allFilterGroupList.enumerateFilterGroup(); fl.hasMoreElements(); ) {

				FilterGroup fg = (FilterGroup) fl.nextElement();

				if ( fg.getUserFilterGroup() ) {

					expFl.addFilterGroup(fg);

				}

			}

			expUserProperties.setFilterGroupList(expFl);
 

			//---( Marshal expUserProperties )---

			writer = new FileWriter(tempFileName);

			Marshaller marshaller = new Marshaller(writer);

			marshaller.setNamespaceMapping("xsi","http://www.w3.org/2001/XMLSchema-instance");

			marshaller.setSchemaLocation("http://www.S4iSystems.com xsd/wvUserFilterFileSchema.xsd");

			marshaller.marshal(expUserProperties);

			if (writer != null ) {

				writer.close();

				// Rename temporary file to user file

				File tf = new File(tempFileName);

				File of = new File(filename);

				of.delete();

				tf.renameTo(of);

			}

		} catch (Exception e) {

			if (writer != null ) {

				try {

					writer.close();

				} catch (IOException e1) {

					e1.printStackTrace();

				}

			} else {

				e.printStackTrace();

			}

				Debug.debug(

					"Critical Error! WebViewUser.saveUserFilterFile(" +

						filename + 

						") - Save failed. " + e.getMessage(),

						Debug.LEVEL_ERROR);

				System.out.println(

					"Critical Error! WebViewUser.saveUserFilterFile(" +

						filename + 

						") - Save failed. " + e.getMessage());

				return false;

			}

		}

		return true;

}//--( end saveUserFilterFile() )--

Open in new window

0
Comment
Question by:sol400
8 Comments
 
LVL 17

Assisted Solution

by:Thomas4019
Thomas4019 earned 200 total points
ID: 24033970
You could use java syncronization to do this. Basically you need one object that never changes in you code, it doesnt matter what it is. Java will make sure it is only in 1 synchronized block at any given time. Note that each thread must synchronize around the same integer.

Here is a link explaining sychronization.
http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html
Integer holder = 0;
 

public void write()

{

   synchronized(holder)

   {

       //IO CODE

   }

}
 

public void read()

{

   synchronized(holder)

   {

       //IO CODE

   }

}

Open in new window

0
 
LVL 5

Expert Comment

by:avya2k
ID: 24037565
you can have private static String object with any string and use it in synchronized block as follows
say private static String myStr="";
public boolean saveUserFilterFile() {
    synchronized(myStr){
       //method body
    }
}

This would ensure that at a time only one thread is using ur method
0
 

Author Comment

by:sol400
ID: 24038269
Hi,
I am NOT trying to single thread the method BUT only single thread multiple saves of the same file.  I can have end users saving unique files, multiple users saving the same file and a single user saving the same file in multiple threads.

Spencer
0
 
LVL 12

Accepted Solution

by:
basav_com earned 300 total points
ID: 24040810
Create a lock file ( tmp file ) to check that no one is using.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:sol400
ID: 24041121
Hi,
So are you saying that the solution would be to create a temporary file with the same name of every file I save and then check for it's existance before starting the save. I would then delay and loop on the existance check. then delete the file when I exit.. This seems like a lot of overhead.
0
 
LVL 17

Expert Comment

by:Thomas4019
ID: 24043937
Will the file only be edited by one program with multiple threads. Or is it possible there might be multiple Java programs running at the same time changing the files.
0
 

Author Comment

by:sol400
ID: 24044178
This is a web aplication where the xml file is used to contain single or group of end user specific persistance data. Each end user will have the file unmarshaled into their session object when they login to the web application.

I think I have solved the problem (I am testing now) based on the suggestion from basav.com.  I marshal the data into a temporary file then delete the orginal file & rename the temporary file.  It looks like all I have to do is check for the temporary files existance.
e.g.:
String tempFileName = ExpAppProperties.getExpFilterPath() + "~~" + getUserName() + ".xml";
File ckTemp = new File(tempFileName);
for ( int x = 0; x < 3; x++) {
      if (!ckTemp.exists()) {
            break;
      }
      try {
            Thread.sleep(2000);
      } catch (InterruptedException e) {
      }
}
      if (ckTemp.exists()) {
            ckTemp.delete();
}

0
 
LVL 92

Expert Comment

by:objects
ID: 24044322
all you need is to synchronize Thomas4019 suggested earlier.

> I am NOT trying to single thread the method BUT only single thread multiple saves of the same file.

so you just synch the block of code that does the save

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
allswap challenge 6 80
numbers ascending pyramid 100 141
eclipse shortcuts 9 45
servlet example 11 19
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now