Any issues with swapping objects and thread safety?

Let's assume we have a property List<Bar> Foo that is being read by multiple threads.

Are there any issues that such a code:

Foo = GetNewFooList();

could cause?

PS 1: this question is out of curiosity, I don't have any particular code (yet)

PS 2: yep, I'm aware that 2 consecutive reads like Foo[0]; Foo[0]; may return different results. It's an expected behaviour

PS 3: the question is more about unexpected exceptions or any kind undefined behaviour or any other side effects (not sure of what undefined behaviour could be in this case - and if I knew it I wouldn't ask the question)


If GetFooList() returns an empty list, then the second of two consecutive reads of Foo[0] could throw an exception. More generally, if you have:

int i = Foo.IndexOf(something);
Bar b1 = Foo[i];
Foo = GetNewFooList(); // happens asynchronously
Bar b2 = Foo[i];

The second will throw an exception if i >= Foo.Count. That is, if the call returns a shorter list.

If one thread is iterating over the list:

for (int i = 0; i < Foo.Count; ++i)
    // At this point, the other thread gets a new list,
    // whose Count <= i
    Bar b = Foo[i];  // throws an exception
    // whatever

Which is really just another manifestation of the first problem.

That's the only one I can think of offhand. You might be able to solve the loop problem with a foreach. I can't say for certain, though, that there aren't other problems lurking in the weeds.

Generally, if you have any code that expects Foo not to change between two references to it, that code is going to fail.

Need Your Help

dynamic outlet name in ember js

ember.js outlet

Requirement: There will be few buttons, and on clicking every button the immediate outlet will be rendered with a view. (not the other outlets present in the page)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.