public class LockFileFactory extends Object
LockFile
instances.
All methods of this class are thread-safe.
Modifier | Constructor and Description |
---|---|
protected |
LockFileFactory() |
Modifier and Type | Method and Description |
---|---|
LockFile |
acquire(File file,
long timeoutMillis)
Acquire an exclusive lock on the specified file.
|
static LockFileFactory |
getInstance() |
protected void |
postRelease(co.codewizards.cloudstore.core.io.LockFileImpl lockFileImpl)
Callback from
LockFileImpl.release() . |
protected LockFileFactory()
public static LockFileFactory getInstance()
public LockFile acquire(File file, long timeoutMillis) throws TimeoutException
Important: You must invoke LockFile.release()
on the returned object! Use a try-finally-block
to ensure it:
LockFile lockFile = LockFileFactory.getInstance().acquire(theFile, theTimeout); try { // do something } finally { lockFile.release(); }
Since Java 7, it is alternatively possible to use the try-with-resources clause like this:
try ( LockFile lockFile = LockFileFactory.getInstance().acquire(theFile, theTimeout); ) { // do something while the file represented by 'lockFile' is locked. }
If the JVM is interrupted or shut down before release()
, the file-lock is released by the
operating system, but a missing release()
causes the file to be locked for the entire remaining runtime
of the JVM! This problem does not exist using the new try-with-resources-clause (since Java 7).
Important: This is not usable for the synchronization of multiple threads within the same Java virtual machine!
Multiple LockFile
s on the same File
are possible within the same JVM! This locking mechanism
only locks against separate processes! Since this implementation is based on FileLock
,
please consult its Javadoc for further information.
To make it possible to synchronise multiple threads in the same JVM, too, there's LockFile.getLock()
.
Multiple invocations of this method on the same given file
return multiple different LockFile
instances.
The actual lock is held until the last LockFile
instance was released.
This method is thread-safe.
file
- the file to be locked. Must not be null
. If this file does not exist in the file system,
it is created by this method.timeoutMillis
- the timeout to wait for the lock to be acquired in milliseconds. The value 0 means to
wait forever.LockFile
. Never null
. This must be
released
(use a try-finally-block)!TimeoutException
- if the LockFile
could not be acquired within the timeout specified by timeoutMillis
.LockFile.release()
protected void postRelease(co.codewizards.cloudstore.core.io.LockFileImpl lockFileImpl)
LockFileImpl.release()
.lockFileImpl
- the LockFileImpl
which notifies this factory about being released.Copyright © 2013–2019. All rights reserved.