gosr
gosr

Reputation: 4708

Variable acts differently according to position of breakpoint

This is a really strange issue, and I can't for the life of me figure out what's wrong.

I have two string arrays, declared at the top of the class:

String[] artistsURLIndexArray;
String[] artistsOnlyArray;

They are both updated in a separate thread (background worker) which is run in the onCreate method. I see in debug that everything is working, and the arrays are correctly updated.

After the background thread I have the following code (still in the onCreate method):

String[] test;

if(artistsOnlyArray == null) // point A
{
    test = new String[] { "empty...", "asd" }; // point B
}
else
{           
    test = new String[] { "not empty!", "asd" }; // point C
}

Now, when I just 'run' the application (no debug), test[0] is "empty...". That is, the artistsOnlyArray is null! This should not be the case. (Btw, I'm testing the test array visually with a listview.)

If I go ahead and place a breakpoint at point B and I debug the application, the app stops (breaks) here. This is expected of course, seeing as it's claiming that the artistsOnlyArray is null.

If I place a breakpoint at point C instead, the breakpoint is not reached. Also 'ok'.

If I place a breakpoint at point A, however, everything changes. The breakpoint is reached of course, and now it has to check whether the array is null. I press F8 to resume (I'm using Eclipse), and suddenly, test[0] is "not empty!". I can also see that the artistsOnlyArray is correct (not null).

Why is the appearance (and position) of a breakpoint causing this behaviour?

Upvotes: 0

Views: 78

Answers (2)

dar7yl
dar7yl

Reputation: 3747

You answered it yourself: "They are both updated in a separate thread".

The breakpoint is possibly causing a "race" condition, where the relative timing of the threads are interfered with. Specifically, the update thread may or may not be blocked before the breakpoint occurs.

Upvotes: 0

Telmo Marques
Telmo Marques

Reputation: 5106

I can only assume this is because of the "extra time" the worker thread has when you place a breakpoint at point A.

When you don't place any breakpoint, the execution of the if statement happens before any worker thread populates the array, and so it enters on the if.

On the other hand, when you place a breakpoint at point A, you give time for the worker thread to populate the array. So, by the time you continue the array is already populated and it enters the else.

Upvotes: 1

Related Questions