Sync file object

From what I know and have researched, the synchronized in Java allows you to synchronize a method or code statement to handle multi-threaded access. If I want to lock the file for writing in a multi-threaded environment, I have to use the classes in the Java NIO package to get the best results. Yesterday I had a question about working with a common servlet for file I / O operations, and BalusC comments are good to help with the solution, but the code in this answer confuses me. I don’t ask the community to “burn this post” or “let it downgrade” (note: I haven’t rejected it anywhere, and I have nothing against the answer), I ask you to explain whether a piece of code can be considered good practice

 private static File theFile = new File("theonetoopen.txt"); private void someImportantIOMethod(Object stuff){ /* This is the line that confuses me. You can use any object as a lock, but is good to use a File object for this purpose? */ synchronized(theFile) { //Your file output writing code here. } } 
+7
source share
4 answers

The problem is not locking the File object - you can lock any object, and it does not matter (to some extent).

What amazes me is that you are not using the final monitor, so if another part of your code redistributes the file: theFile = new File(); , the next thread that appears will be blocked by another object, and you have no guarantee that your code will not be executed by two threads at the same time.

If theFile were final, the code would be fine, although private monitors are preferable, just to make sure there is no other piece of code that uses it for other locking purposes.

+4
source

If you only need to lock the file in one application, then it is OK (subject to the addition of final ).

Note that the solution will not work if you load the class more than once using different class loaders. For example, if you have a web application deployed twice on the same web server, each instance of the application will have its own lock object.

As you noticed, if you want the lock to be reliable and have a file locked from other programs, you should use FileLock (see documents, on some systems it is not guaranteed that all programs must comply with the lock).

+2
source

If you saw: final Object lock = new Object() you ask? As @assylias pointed out that the problem is that the castle is not final here

+1
source

Each object in Java can act as a lock for synchronization. They are called internal locks. Only one thread at a time can execute a code block protected by this block.

More on this: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

Using a synchronized keyword for the entire method can affect the performance of your application. This is why you can sometimes use a synchronized block.

You must remember that the lock reference cannot be changed. The best solution is to use the final keyword.

+1
source

All Articles