Context: highly threaded server-side application with many reads, occasional writes.
Let us consider the following simple code:
[Serializable]
public class BusinessObject
{
// ... lot's of stuff, all READ ONLY!!!
}
public class BusinessObjectHost
{
private BusinessObject bo;
public BusinessObject BO
{
get { return this.bo; }
set { this.bo = value; }
}
}
The intended use is as follows: The BusinessObject is immutable. If I occasionally want to change it, I just need to replace BusinessObjectHost.bo field with a new instance.
Q1: What happens if I do not apply any lock in BusinessObjectHost.BO property and there is a thread conflict between read and write on BusinessObjectHost.bo field? Will the thread throw exceptions? If yes, which one?
Q2: If thread crash causes exception, would the following code work?
public class BusinessObjectHost
{
private BusinessObject bo;
public BusinessObject BO
{
get
{
int i = 5; // Max 5 tries
while (i-- > 0)
{
try { return this.bo; }
catch (WhateverThreadConflictException) {}
}
throw new MyException();
}
set
{
int i = 5; // Max 5 tries
while (i-- > 0)
{
try { this.bo = value; return; }
catch (WhateverThreadConflictException) {}
}
throw new MyException();
}
}
}
Q3: If the above solution is not good, what would you recommend?