Reputation: 1046
I have an application (server side) that sits on a port and listens for client connections. Once a connection is made, the app launches a parser (another thread) that deals with that connection.
My problem is that at some points (because the parsing can take long) the server app launches a new thread while other is being processed. This is a desired behavior, not a problem per se. what happens is that the new thread seems to read some state-variable from the old thread and therefore acts wrongly.
Loosely, what the parser does is this: the client always sends two packets; the first is basically an knock knock packet and the second is the real data packet. I read the first, and if i decide to accept it i put that in a variable, so that the next packet can be read.
On the scenario am describing, the first thread reads the knock knock packet and validates it. The next packet arrives (on the same thread) and the parsing starts.
In the mean time, another parser is created and it waits for its first packet; What then happens (the problem) is that it checks for the validation variable (which should be false for this thread) and it finds it to be ok (it reads from the previous thread, which is still executing) and proceeds to parse the knock knock packet as if it were the data packet.
What am lokoing for is a way to completely eliminate data sharing. am using the following class to keep track of the session state:
public class SessionInfo {
private Constants.PacketValidity validity;
private int packetSize;
private String IMEI;
private int packetReportedSize;
private Constants.PacketType packetType;
private int codec;
private int records;
private boolean valid;
private Constants.ResponseType responseType;
private String clientIP;
private int serverPort;
private Date parseInit;
private Date parseEnd;
}
apart from that, the class has a bunch of setters and getters.
the parser has a instance of this object as a private field.
How would i achieve this?
Upvotes: 0
Views: 136
Reputation: 23373
the parser has a instance of this object as a private field.
This is your problem. A solution would be to create a new SessionInfo
and pass it as a method argument to the parser, passing it on to further method calls. Once you do this the reference to the session state will be local to the current thread execution.
If your parser contains more private attributes that are updated during parsing, you need to extract these also. Combining them in a private subclass and creating an instance of that class when you are called to parse would be a possible solution to that problem.
Upvotes: 2
Reputation: 308041
You need to make sure that the two separate threads use two separate SessionInfo
instances.
The easiest way to do this is probably to create a new parser instance, which in turn creates a new SessionInfo
instance. Once you make sure that they have separate instances, you should be fine.
Upvotes: 2