Reputation: 2318
I know there are many questions asked on this but in my case i have it in a synchronised block and i am sure that nobody will be changing my array list.. But still i get this exception SOMETIMES if i am using for-each loop.. Why ?
Here is my code snippet
final static Object mLock = new Object();
private static ArrayList<ConnectionAndAuthCallback> mCallbacks;
private void callAuthCallbacks() {
synchronized (mLock) {
if (mCallbacks != null)
for (ConnectionAndAuthCallback calback : mCallbacks) { //here i get exception
calback.onAuthentication(mToken, calback.intent);
}
}
}
here is the code i do on Callback
@Override
public void onAuthentication(String token, Intent intent) {
web.loadUrl("xyz.com");
//unregister so that we wong get any exception or some more callbacks
SameClass.unRegisterAuthCallbacks(this);
}
and in Unregister function
public static void unRegisterAuthCallbacks(ConnectionAndAuthCallback callback) {
synchronized (mLock) {
if (mCallbacks != null)
if (mCallbacks.contains(callback)) {
mCallbacks.remove(callback); // This causing problem ?? In same thread "syncronised" wont work ??
}
}
}
Upvotes: 2
Views: 152
Reputation: 2318
Answer was, In the same thread synchronised(){}
wont work.
Even if you think it works then there might be a dead lock.
In my case i was removing callback object from ArrayList
in the same thread where i called callback.
Upvotes: 0
Reputation: 1885
You can't perform modifications on an ArrayList or remove() in this case that you are currently reading out of or looping through. Use iterators instead.
Check out this link. And this link.
Upvotes: 1