Корректный способ синхронизировать ArrayList в Java

То, что Вы ищете, технически известно как приправление карри.

function getMyCallback(randomValue)
{
    return function(otherParam)
    {
        return randomValue * otherParam //or whatever it is you are doing.
    }

}

var myCallback = getMyCallBack(getRand())

alert(myCallBack(1));
alert(myCallBack(2));

Вышеупомянутое не является точно функцией с приправой карри, но оно достигает результата поддержания существующего значения, не добавляя переменные к глобальному пространству имен или требуя некоторого другого объектного репозитория для него.

35
задан WoLfPwNeR 7 January 2016 в 03:06
поделиться

4 ответа

You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list) Using Collections.synchronizedList() is superfluous in that case (it creates a wrapper that synchronizes individual operations).

However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.

Instead, simply call clear() - no iteration needed.

Edit: If you need the single-method synchronization of Collections.synchronizedList() later on, then this is the correct way:

List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly, 

But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList() is just useless additional overhead.

46
ответ дан 27 November 2019 в 07:03
поделиться

Глядя на ваш пример, я думаю, что ArrayBlockingQueue (или его братья и сестры) могут быть полезны. Они следят за синхронизацией за вас, поэтому потоки могут писать в очередь или просматривать / принимать без дополнительной работы по синхронизации с вашей стороны.

8
ответ дан 27 November 2019 в 07:03
поделиться

Это верно и задокументировано:

http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedList (java.util. List)

Однако, чтобы очистить список, просто вызовите List.clear () .

5
ответ дан 27 November 2019 в 07:03
поделиться

Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.

However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue

5
ответ дан 27 November 2019 в 07:03
поделиться
Другие вопросы по тегам:

Похожие вопросы: