我正在尝试支持定期清除的哈希图上的并发性。我有一个缓存,可以存储一段时间的数据。每 5 分钟后,此缓存中的数据将发送到服务器。一旦我刷新,我想清除缓存。问题是当我刷新时,当我使用现有密钥执行此操作时,数据可能会写入此映射。我将如何使这个进程线程安全?
data class A(val a: AtomicLong, val b: AtomicLong) {
fun changeA() {
a.incrementAndGet()
}
}
class Flusher {
private val cache: Map<String, A> = ConcurrentHashMap()
private val lock = Any()
fun retrieveA(key: String){
synchronized(lock) {
return cache.getOrPut(key) { A(key, 1) }
}
}
fun flush() {
synchronized(lock) {
// send data to network request
cache.clear()
}
}
}
// Existence of multiple classes like CacheChanger
class CacheChanger{
fun incrementData(){
flusher.retrieveA("x").changeA()
}
}
Run Code Online (Sandbox Code Playgroud)
我担心上面的缓存没有正确同步。有没有更好/正确的方法来锁定这个缓存,这样我就不会丢失数据?我应该创建缓存的深层副本并清除它吗?
既然上面的数据可能被另一个更改器更改,那会不会导致问题?
java concurrency java.util.concurrent thread-synchronization kotlin
我试图了解ConcurrentHashMap并看看我是否可以利用它而无需在我这边添加任何锁。ConcurrentHashMap一天开始时我有很多书。
class Z {
val books: ConcurrentHashMap<String, Int> = ConcurrentHashMap()
fun addBook(book: String, numberOfBooks: Int) {
books[book] = numberOfBooks
}
fun doSomething(book: String) {
val numberOfBooks = books.remove(book)
}
}
Run Code Online (Sandbox Code Playgroud)
上面的内容是线程安全的。但是现在,如果我需要添加验证只是为了确保在初始化期间不会添加两次这本书,我需要添加一个synchronized块只是为了确保我没有添加如下所示的内容。
class Z {
val books: ConcurrentHashMap<String, Int> = ConcurrentHashMap()
val lock = Any()
fun addBook(book: String, numberOfBooks: Int) {
synchronized(lock) {
val existingBook = books[book]
if(existingBook!=null)
println("Book exists, BEWARE!!")
books[book] = numberOfBooks
}
}
fun doSomething(book: String) {
var numberOfBooks : Int?
synchronized(lock) …Run Code Online (Sandbox Code Playgroud)