Answer the question
In order to leave comments, you need to log in
What is the correct way to work with CopyOnWriteArrayList?
Good afternoon!
Task
Let's say there is a web page on which users perform actions. The history of actions is written to a variable of type CopyOnWriteArrayList . As soon as the size of the array reaches 10, I need to store the data in the database.
The question is how to implement it correctly in multithreading conditions. I did this (but it hurts to look at):
private val syncMinLimit = 10
private val userActions = CopyOnWriteArrayList<UserAction>()
fun addAction (action: UserAction) {
userActions.add(action)
// Условие перед synchronized чтобы постоянно не блокировать поток
if (userActions.size >= syncMinLimit) {
synchronized(userActions) {
// Еще раз это условие, т.к. перед synchronized могла выстроиться очередь пока выполнялся код ниже
if (userActions.size >= syncMinLimit) {
val iterator = userActions.iterator()
val removed = mutableListOf<UserAction>()
while (iterator.hasNext())
removed.add(iterator.next())
userActions.removeAll(removed)
saveToDB(removed) // my function
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Let's say there is a web page on which users perform actions. The history of actions is written to a variable of type CopyOnWriteArrayList
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question