0

For example 1 employee class is there contains employee id and employee name,and i created object for this employee class, then here 2 threads are there, these 2 threads want to execute the same employee object, then what problem will occur?

If 1 thread(t1) changes the value of employee id to 1 and another thread(t2) change the value of employee id to 2, then what problem will occur? and how to resolve it?

I checked in internet and i got it as race condition, but didn't understand completely.

Here thread names are t1,t2 and employee class is

public class Employee{

 private int employeeid;

 private string empname;
}

employee object creation:
Employee employee = new Employee()
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
Devi George
  • 45
  • 2
  • 8

1 Answers1

0

if 1 thread(t1) changes the value of employee id to 1 and another thread(t2) change the value of employee id to 2, then what problem will occur?

That scenario is called a data race. If two threads each set the same variable to one value or another, then the end result will be that the variable holds one value or the other. It is not actually possible for two threads to store to the same location at the same time: The memory system will serialize the stores. So, the outcome depends on which one went first and which one went second.

There's no practical way to predict which one will go first and which will go second, so that means there's no practical way to predict the outcome. In most programs, that's considered to be a Bad Thing.

and how to resolve it?

That's up to you. Really! There is no correct answer to which thread should win the race. Usually, we "resolve" the problem by designing our programs so that their behavior doesn't depend on data races.

In your example, you have two threads that are trying to do two incompatible things. They both want to assign the same variable, but they disagree on what its value should be. That's a sign of Bad Design. It probably means that you haven't really thought about what that variable stands for in your program, or you haven't really thought about why or when it should ever be changed.


P.S., If a field of an Employee object holds an employee's ID, then it almost certainly should be a final field.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57