当前位置:网站首页>Several ways to avoid concurrent modification exceptions of lists
Several ways to avoid concurrent modification exceptions of lists
2022-06-11 07:55:00 【tinyvampirepudge】
avoid list Several ways to modify exceptions concurrently
1、 Use list Of snapshot, Traverse its copy
Use as follows :com.bumptech.glide.manager.ActivityFragmentLifecycle#onStart()
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStart();
}
The specific implementation is as follows :
com.bumptech.glide.util.Util:
/**
* Returns a copy of the given list that is safe to iterate over and perform actions that may
* modify the original list.
*
* <p>See #303, #375, #322, #2262.
*/
@NonNull
@SuppressWarnings("UseBulkOperation")
public static <T> List<T> getSnapshot(@NonNull Collection<T> other) {
// toArray creates a new ArrayList internally and does not guarantee that the values it contains
// are non-null. Collections.addAll in ArrayList uses toArray internally and therefore also
// doesn't guarantee that entries are non-null. WeakHashMap's iterator does avoid returning null
// and is therefore safe to use. See #322, #2262.
List<T> result = new ArrayList<>(other.size());
for (T item : other) {
if (item != null) {
result.add(item);
}
}
return result;
}
2、 Use CopyOnWriteArrayList
For details, please refer to ViewTreeObserver add to OnGlobalLayoutListener:
// Non-recursive listeners use CopyOnWriteArray
// Any listener invoked from ViewRootImpl.performTraversals() should not be recursive
@UnsupportedAppUsage
private CopyOnWriteArray<OnGlobalLayoutListener> mOnGlobalLayoutListeners;
/**
* Register a callback to be invoked when the global layout state or the visibility of views
* within the view tree changes
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) {
checkIsAlive();
if (mOnGlobalLayoutListeners == null) {
mOnGlobalLayoutListeners = new CopyOnWriteArray<OnGlobalLayoutListener>();
}
mOnGlobalLayoutListeners.add(listener);
}
/**
* Remove a previously installed global layout callback
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @see #addOnGlobalLayoutListener(OnGlobalLayoutListener)
*/
public void removeOnGlobalLayoutListener(OnGlobalLayoutListener victim) {
checkIsAlive();
if (mOnGlobalLayoutListeners == null) {
return;
}
mOnGlobalLayoutListeners.remove(victim);
}
/**
* Notifies registered listeners that a global layout happened. This can be called
* manually if you are forcing a layout on a View or a hierarchy of Views that are
* not attached to a Window or in the GONE state.
*/
public final void dispatchOnGlobalLayout() {
// NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
// perform the dispatching. The iterator is a safe guard against listeners that
// could mutate the list by calling the various add/remove methods. This prevents
// the array from being modified while we iterate it.
final CopyOnWriteArray<OnGlobalLayoutListener> listeners = mOnGlobalLayoutListeners;
if (listeners != null && listeners.size() > 0) {
CopyOnWriteArray.Access<OnGlobalLayoutListener> access = listeners.start();
try {
int count = access.size();
for (int i = 0; i < count; i++) {
access.get(i).onGlobalLayout();
}
} finally {
listeners.end();
}
}
}
/**addOnGlobalLayoutListener
* Register a callback to be invoked when the global layout state or the visibility of views
* within the view tree changes
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) {
checkIsAlive();
if (mOnGlobalLayoutListeners == null) {
mOnGlobalLayoutListeners = new CopyOnWriteArray<OnGlobalLayoutListener>();
}
mOnGlobalLayoutListeners.add(listener);
}
/**
* Notifies registered listeners that a global layout happened. This can be called
* manually if you are forcing a layout on a View or a hierarchy of Views that are
* not attached to a Window or in the GONE state.
*/
public final void dispatchOnGlobalLayout() {
// NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
// perform the dispatching. The iterator is a safe guard against listeners that
// could mutate the list by calling the various add/remove methods. This prevents
// the array from being modified while we iterate it.
final CopyOnWriteArray<OnGlobalLayoutListener> listeners = mOnGlobalLayoutListeners;
if (listeners != null && listeners.size() > 0) {
CopyOnWriteArray.Access<OnGlobalLayoutListener> access = listeners.start();
try {
int count = access.size();
for (int i = 0; i < count; i++) {
access.get(i).onGlobalLayout();
}
} finally {
listeners.end();
}
}
}
边栏推荐
- TiDB Cloud 上线 Google Cloud Marketplace,以全新一栈式实时 HTAP 数据库赋能全球开发者
- Detailed explanation of shift operator and bit operator in C language
- Sort - select sort
- [the most complete ENSP [installation diagram] in history!]
- [atcoder2376] black and white tree (game)
- Modular linear equations (Chinese remainder theorem + general solution)
- Batch splice string
- A detailed explanation of one of the causes of dead loop caused by array out of bounds in C language
- [cluster] lvs+keepalived high availability cluster
- 2021-10-17
猜你喜欢

TiDB Cloud 上线 Google Cloud Marketplace,以全新一栈式实时 HTAP 数据库赋能全球开发者

Selenium click the floating menu and realize the functions of right mouse button

C language - Growth Diary -02- function

Storage of floating point in memory

Alchemy experience (model training of deep learning) the necessity of timely adjusting training parameters for some situations (the adjustment of learning rate LR is the primary) summarizes some metho

Zero foundation self-study SQL course | union joint query

C- print 99 multiplication table
![[IOT] intelligent hardware: how to obtain the WiFi signal strength of hardware products](/img/85/5766d8269391820b5e142178530657.png)
[IOT] intelligent hardware: how to obtain the WiFi signal strength of hardware products

Bubble sorting with C language

C language lesson 2
随机推荐
Tidb cloud launched Google cloud marketplace, empowering global developers with a new stack of real-time HTAP databases
Zero foundation self-study SQL course | outer join external connection
Tutoriel de démarrage bladed (vidéo)
Magnifying mirror rendering
Tidb Cloud est en ligne sur le marché Google Cloud pour permettre aux développeurs du monde entier d'utiliser une nouvelle pile de bases de données htap en temps réel
TypeScript-声明合并
Clipping and overlapping of YUV data
TypeScript-null和undefined
运筹学导论
Batch splice string
How to output the percent sign "%" in printf function in C language
Servlet、ServletConfig、ServletContext
【HDU6357】Hills And Valleys(DP)
[cluster] haproxy load balancing
排序——归并排序
[untitled] Weng_ C lesson 1
What exactly is PMP?
[atcoder1983] BBQ hard (combination number + clever model transformation)
代码设置ConstraintLayout的layout_constraintDimensionRatio
The solution of "no startup device" after running Bochs