У меня есть блок, завернутый в синхронизированный (это), и я вижу как в режиме отладки, так и в журналах, что 2 потока одновременно входят в этот раздел.
public void dispatch(Event.Builder eventBuilder) {
synchronized (this) {
index++;
getLogger().d(TAG, "race condition line A - The index is " + index);
try {
Event event = eventBuilder.build();
getLogger().d(TAG, "race condition line B - The index is " + index);
mDispatcher.dispatch(event);
} catch (InstantiationWithoutBuilderException e) {
// Dev time Exception. Should be caught by Developer
throw e;
} catch (StateMachineException e) {
if (!e.wasWrittenToErrorHistory()) {
printError(new ExceptionHistoryElement(mState, eventBuilder.getTemporaryEventWithTypeForException(), e));
}
} catch (Exception e) {
printError(new ExceptionHistoryElement(mState, eventBuilder.getTemporaryEventWithTypeForException(), e));
}
getLogger().d(TAG, "race condition line C - The index is " + index);
}
}
Журналы:
race condition line A - The index is 1
race condition line B - The index is 1
race condition line A - The index is 2
race condition line B - The index is 2
race condition line C - The index is 2
race condition line A - The index is 3
race condition line B - The index is 3
race condition line C - The index is 3
race condition line C - The index is 3
race condition line A - The index is 4
race condition line B - The index is 4
race condition line C - The index is 4
race condition line A - The index is 5
race condition line B - The index is 5
race condition line C - The index is 5
Как видите, я увеличиваю индекс элемента данных каждый раз, когда вхожу в синхронизированный блок. Должно быть напечатано 3 строки журнала с каждым индексом, но, как вы можете видеть в журналах, индекс 1 печатается дважды, а индекс 3 печатается 4 раза.
Спасибо
ОБНОВЛЕНИЕ : Оказывается, это происходило потому, что один и тот же поток вводил этот метод несколько раз. синхронизированный блок работает только между разными потоками. как это происходит в синхронном коде - новая загадка.