Reputation: 2066
This application initiates a new thread for each connection it receives, in this example, 2 clients (connections) tries to increment a variable 10 times each.
so at the end it should be 20, but instead its just 10.
The Server listener:
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(1994);
Socket socket=null;
while (true) {
socket = serverSocket.accept();
new TestingSession(socket).start();
}
}
Server's Thread ( session )
class TestingSession extends Thread {
private Socket socket;
TestingSession(Socket socket) { this.socket = socket;}
public void run() {
try {
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
dataOutputStream.writeInt(number.getI());
int i = dataInputStream.readInt();
number.setI(i);
System.out.println(i);
Clients main method :
public class Run {
public static void main(String[] args) {
UpdateTest t1 = new UpdateTest();
UpdateTest t2 = new UpdateTest();
t1.start();
t2.start();
System.out.println("finished creation");
}
}
Clients Thread :
public class UpdateTest extends Thread {
public void run() {
try {
Socket socket;
socket = new Socket("127.0.0.1", 1994) ;
for(int i=0; i <10;i++){
int z=dataInputStream.readInt(); // read the static num
dataOutputStream.writeInt(z+1); // write it incremented one
}
socket.close();
} catch(Exception e){
System.out.println(e.getMessage());
}
}
}
i want the variable to become 20, but instead it prints the following on the server side
1 1 2 2 3 3 .. 10 10
Upvotes: 1
Views: 101
Reputation: 7968
From the code you provided, it looks like you dont provide any synchronization to update and read number value. That's why you dont see 20 in the end. This code should be inside a synchronized block.
synchronized (number) {
dataOutputStream.writeInt(number.getI());
int i = dataInputStream.readInt();
number.setI(i);`
}
Upvotes: 1