F
F
furyon2020-05-27 10:29:14
Java
furyon, 2020-05-27 10:29:14

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

1 answer(s)
O
Orkhan, 2020-05-27
Hasanly @azerphoenix

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

I don’t quite understand you, how exactly the history of actions is written to the CopyOnWriteArrayList variable? And most importantly - why?
Maybe it makes sense to do the following:
write the history of actions in the localStorage of the user's browser (using JavaScript), and then after a certain time has elapsed or by pressing the "Save" button or some other trigger, save everything to the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question