dependencies: Release file lock if an exception is thrown

This commit is contained in:
Ilya Matveev
2017-06-21 17:00:23 +07:00
committed by ilmat192
parent b8ead53487
commit a52f80c4e8
@@ -20,7 +20,9 @@ import java.io.*
import java.net.URL import java.net.URL
import java.nio.file.Files import java.nio.file.Files
import java.nio.file.StandardCopyOption import java.nio.file.StandardCopyOption
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread import kotlin.concurrent.thread
import kotlin.concurrent.withLock
// TODO: Try to use some dependency management system (Ivy?) // TODO: Try to use some dependency management system (Ivy?)
class DependencyDownloader(dependenciesRoot: File, val dependenciesUrl: String, val dependencies: List<String>) { class DependencyDownloader(dependenciesRoot: File, val dependenciesUrl: String, val dependencies: List<String>) {
@@ -172,11 +174,34 @@ class DependencyDownloader(dependenciesRoot: File, val dependenciesUrl: String,
) )
} }
fun run() { // stdlib `use` function adapted for AutoCloseable.
val systemLock = RandomAccessFile(lockFile, "rw").channel.lock() private inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R {
dependencies.forEach { var closed = false
processDependency(it) try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}
companion object {
val lock = ReentrantLock()
}
fun run() = lock.withLock {
RandomAccessFile(lockFile, "rw").channel.lock().use {
dependencies.forEach {
processDependency(it)
}
} }
systemLock.release()
} }
} }