-
Notifications
You must be signed in to change notification settings - Fork 9.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
okhttp/src/main/kotlin/okhttp3/internal/cache/CacheLock.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package okhttp3.internal.cache | ||
|
||
import android.annotation.SuppressLint | ||
import java.io.Closeable | ||
import java.nio.channels.FileChannel | ||
import java.nio.file.StandardOpenOption | ||
import java.util.Collections | ||
import okhttp3.internal.platform.Platform | ||
import okio.FileSystem | ||
import okio.Path | ||
|
||
internal object CacheLock { | ||
private val openCaches = Collections.synchronizedMap(mutableMapOf<Path, Exception>()) | ||
|
||
fun openLock(fileSystem: FileSystem, directory: Path): Closeable { | ||
return if (fileSystem == FileSystem.SYSTEM && !Platform.isAndroid) { | ||
fileSystemLock(directory) | ||
} else { | ||
inMemoryLock(directory) | ||
} | ||
} | ||
|
||
@SuppressLint("NewApi") | ||
fun inMemoryLock(directory: Path): Closeable { | ||
// TODO solution for Android N? | ||
val existing = openCaches.putIfAbsent(directory, Exception("CacheLock($directory)")) | ||
if (existing != null) { | ||
throw IllegalStateException("Cache already open at '$directory'", existing) | ||
} | ||
return okio.Closeable { | ||
openCaches.remove(directory) | ||
} | ||
} | ||
|
||
@SuppressLint("NewApi") | ||
fun fileSystemLock(directory: Path): Closeable { | ||
val lockFile = directory / "lock" | ||
val channel = FileChannel.open(lockFile.toNioPath(), StandardOpenOption.APPEND) | ||
|
||
return okio.Closeable { | ||
channel.close() | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters