I am trying to understand ConcurrentHashMap
and see if I can leverage it w/o adding any locks on my side. I have a ConcurrentHashMap
with number of books at the beginning of a day.
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)
}
}
The above would be threadsafe. But now if I need to add in a validation just to be sure the book isn't being added twice during initialization I need to add a synchronized
block just to be sure that I am not adding something like below.
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)
numberOfBooks=books.remove(book)
}
}
Is there a better way for me to do this. I hate adding a synchronized
block just to put in a log statement in there.