Skip to content

Commit

Permalink
Cache improvements (tipsy#91)
Browse files Browse the repository at this point in the history
* Improve Cache (storage, reading, and retrieval)

* Don't bother going through mutableMap
  • Loading branch information
iProdigy authored and tipsy committed Apr 10, 2018
1 parent 463498e commit 892e736
Showing 1 changed file with 29 additions and 13 deletions.
42 changes: 29 additions & 13 deletions src/main/kotlin/app/Cache.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,29 @@ package app
import java.io.*
import java.time.Instant
import java.time.temporal.ChronoUnit.HOURS
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors

object Cache {

private const val path = "cache/userinfo"
private val userProfiles = readUserProfilesFromDisk()
private val fileSaveExecutor = Executors.newSingleThreadExecutor()

// Put userProfile in cache, then serialize cache and write it to disk
fun putUserProfile(userProfile: UserProfile) {
userProfiles[userProfile.user.login.toLowerCase()] = userProfile
val byteArrayOutputStream = ByteArrayOutputStream()
ObjectOutputStream(byteArrayOutputStream).writeObject(userProfiles)
File(path).apply {
if (!exists()) {
parentFile.mkdirs()
createNewFile()
fileSaveExecutor.execute {
ByteArrayOutputStream().let {
ObjectOutputStream(it).writeObject(userProfiles)
File(path).apply {
if (!exists()) {
parentFile.mkdirs()
createNewFile()
}
writeBytes(it.toByteArray())
}
}
writeBytes(byteArrayOutputStream.toByteArray())
}
}

Expand All @@ -31,12 +37,22 @@ object Cache {

// Read cache from disk, return empty map if no cache file exists
@Suppress("UNCHECKED_CAST")
private fun readUserProfilesFromDisk(): MutableMap<String, UserProfile> = if (File(path).exists()) {
ObjectInputStream(
ByteArrayInputStream(File("cache/userinfo").readBytes())
).readObject() as MutableMap<String, UserProfile>
} else {
mutableMapOf()
private fun readUserProfilesFromDisk(): ConcurrentHashMap<String, UserProfile> {
try {
File(path).apply {
if (exists()) {
ObjectInputStream(ByteArrayInputStream(readBytes())).let {
val obj = it.readObject()

if (obj is ConcurrentHashMap<*, *>)
return obj as ConcurrentHashMap<String, UserProfile>
}
}
}
} catch (e: Exception) {
}

return ConcurrentHashMap()
}

}

0 comments on commit 892e736

Please sign in to comment.