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()
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.
Related
Suppose I have DAO named Assignment which declare with #Document map with a mongo collection name Assignment.
Then I have a service bean for example AssigmentImpl which is in singleton scope, doing a update operation where it fetch the persisted DAO and update some with the REST input data for Assignment.
#Service
public class AssignmentImpl{
public Assignment updateAssignment(Assignment assignment){
Assignment assignmentExsisting = assignmentRepo.getAssignment(assignment.getId());
BeanUtils.copyProperties(assignment,assignmentExsisting);
assignmentRepo.save(assignmentExsisting);
}
}
Suppose multiple threads (users) doing the update operations to the different assignments.
Being AssignmentService is singleton it will return same copy to different users. How does it reference the Assignment object? If i say, since Assignment object is not singleton, it will return different object reference to AssignmentImpl when each users do update operation, is it right?
In that case user A might get assignment id 123 before do the update operation and when user B start do the update operation AssignmentImpl would change the assignment reference to different assignment id 456. In that case user A would update a totally different assignment. Is that be possible? If so how can we prevent it? Make the update operation synchronized or is there any other good solutions?
No, it won't be the way you are thinking, note that even service class is singlton every call to update won't overlap any other method call's execution as both will be executed in different threads created by server. So, the operation will take place as per the given assignment and two users' result won't get interchanged, why? because each thread executes method independently but the problem will arise when two threads tries to modify sate of shared element i.e. change value of object declared at class level in your service method.
For example, two buses are starting journey from point A to point B. Now, none of the buses have shared passengers (it's not possible right?), both have their own passengers and own fuel however the mechanism (repository and service) for both buses remains same.
You see two threads are not sharing anything here as far as I can tell, yes it uses repository bean but it doesn't modify it's state it will just send assignment to store and id to retrieve assignment.
My problem is a modification of the Capacitated Vehicle Routing Problem (CVRP) that will eventually include time windows as well.
Since time windows are already built into the examples, it shouldn't be too hard for me to figure them out. However, I need to change one of the core constraints of the CVRP examples, and I'm a bit lost on how to do it.
My Model
In the system I'm trying to model, a Vehicle can leave its Depot, go to several different Customers, and load up on material. However, where my model differs from the examples is that the Vehicle can visit any Depot mid-chain to deposit its current load.
Issues
I've been going over the documentation trying to figure out how to do this, and my basic understanding so far is that I'd have to change the definition of Depot (maybe by implementing Standstill) to be able to be part of the chain of places the vehicle visits, and/or maybe just integrate Depot into Customer with some kind of special rule that a visit to a Depot empties the vehicle instead of increasing the demand.
I've also been looking at shadow variables and variable listeners, but I don't know if that's the right way to go. It's all a little confusing.
Can anyone offer some tips or advice, or point me in the right direction as to where to start before I dig myself too far into a hole?
Based on Geoffrey's suggestion, rename your Vehicle class to VehicleTrip and let it point to the previous and the next trip by giving it a value previousVehicleTrip and nextVehicleTrip, and give it a variable start time and end time (code examples in Kotlin):
class VehicleTrip(
...,
var startTime: LocalDateTime? = null,
var endTime: LocalDateTime? = null,
val previousVehicleTrip?: VehicleTrip = null,
val nextVehicleTrip?: VehicleTrip = null
) : Standstill {
...
}
You can set these values when initiating your VehicleTrips. When you get a StackOverFlowError based on the VehicleTrip.hashCode(), simply override the hashCode() function of the VehicleTrip class. (Maybe someone has a better suggestion for dealing with this?)
Updating the shadow variables.
In your Customer class, you should have a variable arrivalTime (like in the CVRPTW example) which is a custom shadow variable. In the listener class of this variable you usually only update the arrival time of a vehicle at a customer, and the arrival times of the customers that come next in this trip. Now, you also need to update all the times of the trips that come after the trip your current customer is in.
For example, you might have two trips VT1 and VT2, and three customers C1, C2, and C3. When changing from
VT1 - C1 - VT2 - C2 - C3
to
VT1 - C2 - C1 - VT2 - C3
the things you want updated are (in order)
C2.arrivalTime
C1.arrivalTime
VT1.endTime
VT2.startTime
C3.arrivalTime
VT2.endTime
Notice that in the TimeWindowedCustomer example, the variable listener only does steps 1. and 2., so we have to add steps 3. until 6.
To do this, start by adding #CustomShadowVariable annotations to the start and end times of VehicleTrip (and don't forget to mark VehicleTrip as a planning entity), which uses the same variable listener class as the time windowed customer:
class VehicleTrip(
...,
#CustomShadowVariable(
variableListenerRef = PlanningVariableReference(
entityClass = TimeWindowedCustomer::class,
variableName = "arrivalTime"
))
var startTime: LocalDateTime? = null,
...
) : Standstill {
...
}
Now in the ArrivalTimeUpdatingVariableListener class, you can add steps 3. until 6. similar to how steps 1. and 2. are implemented. Make sure that you keep the order of updating these variables, and that you notify the ScoreDirector when changing a variable with the beforeVariableChanged() and afterVariableChanged() methods.
I have this 2 classes, and someone told me that I did it wrong.
class Employee {
private int employeeID;
private String employeeName;
private Seat employeeSeat;
}
This is for my employee class which has a relationship with the Seat class
class Seat {
private int seatID;
private String seatCode;
private Employee occupant;
}
I also added an employee attribute to my seat because when I retrieve the seat, I want to determine who is the current occupant of the seat. Same thing with my employee, when I retrieve it, I want to determine the employee's current seat. Now, they said that because the employee has a seat attribute, and the seat has an employee attribute, it's a terrible design.
You would have to ask the person that told you it was wrong to explain in detail what they mean. It may or may not be, but that would depend on the overall system architecture and requirements for navigating between objects.
Likely what they mean is that you should have an EmployeeSeat object to hold the relationship and any details pertaining to that relationship (start date, end date, hours, whatever). But then you have to worry about other problems like enforcing cardinality constraints (can an employee have multiple seats, or vice versa)?
Because the risk of updating one side of the relationship at runtime to point to another entity and forgetting to update the other side (leaving the model in an inconsistent state) is generally considered way worse than the slight inconvenience of working with a one-direction association. It's not always possible though.
The following classes display the concept of Composition in Java:
//Imagine constructors, accessors & mutators has already been created..
class Person{
private String name;
private Job job; //Person has Job
}
class Job{
private String name;
private double salary;
}
My question is: If I want to get the salary from Person, which of the following 2 options is a better practice?
1. Get job of person, then get salary from job of person
System.out.println( person.getJob().getSalary() );
OR
2. Create a getSalary method in person, so I can do this:
System.out.println(person.getSalary());
Create a method to get salary from job first.
class Person{
private String name;
private Job job;
public static double getSalary(){ //Is doing this redundant and bad practice?
job.getSalary();
}
}
Method 2 is a little bit better than method 1 because the code that gets the salary from a person is not dependent on any kind of Person->Salary relation implementation. You are free to change the way the salary is computed. In real life you can ask somebody what is is salary without knowing anything about his job. In your code, a liar can even returns an imaginary salary for him, etc.
To be honest I insist on the fact that method 1 cannot be considered as bad or false in any way, it has only small disadvantage in common situations...
Generally and personally I like method 1 because every redirection (how call this right?) make code a little bit more complicated. Imagine whole code has redirections for every relation. Even it's harder to communicate: 'do you mean Person.Salary or Person.Job.Salary?'.
But in your example I prefer method 2 because I can imagine extend Person to have multiple jobs or jobs beside pension or like.
There is a "Law" saying that option number 1 should be avoided, it's the Demeter's law aka principle of least knowledge
in particular
an object A can request a service (call a method) of an object
instance B, but object A should not "reach through" object B
to access yet another object, C, to request its services
HTH,
Carlo
Let's say I have a class Employee and I create the object of that class as
Employee emp = new Employee();
What is the difference between the below two synchronized blocks
synchronized(emp){ } and
synchronized(Employee.class)
The first one uses one Employee instance as monitor. The second one uses the Employee class as monitor.
If the goal is to guard instance variables of an employee, the first one is makes much more sense than the second one. If the goal is to guard static variables of the Employee class, the second one makes sense, but not the first one.
The first one synchronizes on specific instances of the class. So if you have 2 threads operating on two different instances of the class, they can both enter the block at the same time - within their own contexts, of course.
The second block synchronizes on the class itself. So even if you have 2 threads with two different instances, the block will be entered by only one thread at a time.
When you syncrhonize, you need an object to define as the semaphore. When thread A is inside a syncrhonized block defined by object A, no other thread can be in other such a block defined by the object A, but it can be inside any other synchronized block defined by other objects.
emp and Employee.class are distinct objects, so the two synchronized blocks are not incompatible (you can have a thread inside the first and another inside the second).
In a more general note, you should use the first block to protect sensitive code that only affects to the individual employee objects, and the second one in operations where changing one employee may affect other employee critical section or a collection/aggregate value of them.