GH-3076: NioFileLocker: add file existence check

Fixes spring-projects/spring-integration#3076

* Return `null` instead of throwing an exception

* Fix license header

* Add missing `@since`

* Avoid over-engineered test logic

* Fix code style

* Test non-existent file does not get created

* Fix: remove unused import
This commit is contained in:
Emmanuel Roux
2019-10-17 20:52:46 +02:00
committed by Artem Bilan
parent 1e50707370
commit c420c414d3
3 changed files with 77 additions and 1 deletions

View File

@@ -25,11 +25,14 @@ import java.nio.channels.OverlappingFileLockException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.lang.Nullable;
/**
* Static cache of FileLocks that can be used to ensure that only a single lock is used inside this ClassLoader.
*
* @author Iwein Fuld
* @author Gary Russell
* @author Emmanuel Roux
* @since 2.0
*/
final class FileChannelCache {
@@ -49,9 +52,10 @@ final class FileChannelCache {
* <p>
* Thread safe.
*/
@Nullable
public static FileLock tryLockFor(File fileToLock) throws IOException {
FileChannel channel = channelCache.get(fileToLock);
if (channel == null) {
if (channel == null && fileToLock.exists()) {
@SuppressWarnings("resource")
FileChannel newChannel = new RandomAccessFile(fileToLock, "rw").getChannel();
FileChannel original = channelCache.putIfAbsent(fileToLock, newChannel);