[imagine a picture with a can of worms, with worms starting to spread out, here]
Don’t be surprised, but the custom Gallery from yesterday, it’s buggy.
I was looking at one of the bugs, my investigation involved lots of debug messages about touchscreen events in rapid succession. While scrutinizing these, I spotted a boolean variable that was flipping seemingly without me assigning anything to it.
OK easy, I thought, apparently there’s some code assigning to it that I don’t know about. Maybe the superclass is messing with me, maybe I’ve leaked some object reference somewhere, maybe it’s threading issue. Or maybe there’s several copies of my code running, with several corresponding boolean variables.
So I wrapped my boolean in object that
- prints all reads and assignments to debug console: nobody can bypass my logging statements now
- is threadsafe: assignments, reads and logging statements won’t get interleaved
- doesn’t leak reference to wrapped value, but primitive Java types are pass-by-value anyway right?
- prints its
hashCodeand timestamp of creation: gives some affirmation that I’m looking at the same object all of the time
And as I was staring at the log, the value was still flipping! Two reads, with no write inbetween, were reporting different values. So my next line of thought touched on aspects of JVM, CPU, radioactivity and sanity. As usual though, explanation turned out to be simple and boring: debug log not outputting messages in chronological order. I came up with a counter variable that I would increment on every assignment, so it should only monotonically grow. Lo and behold, in the log messages it was going up and down! Quick glance at timestamps of debug messages and there was my answer, in plain sight, the order of messages was clearly not chronological.
By the way, it appears that printing debug messages in terminal with
adb logcat is fine, the messages come in order.