Search code examples
javamultithreadingstack-overflowshared

Two thread shared static variable


I want to run a simple server-client program where clients checks each 5 sec best server and connect always best server. So I wrote following code but I get stackoverflow error.

public static void main(String[] args) throws IOException, InterruptedException {
        RTT best = null;
        BestServer bestserver = new BestServer(best);

        Socket clientSocket = new Socket(bestserver.bestserver.ip, 6789);
        System.out.println("I connect best server");
}   

public class BestServer implements Runnable{

    static RTT bestserver;

    public BestServer(RTT best) throws InterruptedException{
        bestserver = best;
        findBest();
    }

    public static void findBest() throws InterruptedException{

        Thread t = new Thread(new BestServer(bestserver));
        t.start();
        t.sleep(5000);
}

public void run(){
    //..
}

Solution

  • Your StackOverflow comes from this line.

    while(true){
        Socket clientSocket = new Socket(bestserver.bestserver.ip, 6789);
        System.out.println("I connect best server");
    }
    

    You make Sockets until you run out of memory.

    You need to make a set amount of sockets, otherwise you'll always run out of memory.

    Another problem is these two lines:

    public BestServer(RTT best) throws InterruptedException{
        bestserver = best;
        findBest();
    }
    
    public static void findBest() throws InterruptedException{
        Thread t = new Thread(new BestServer(bestserver));
    }
    

    One calls findbest(), and the other calls the constructor. Since this is the case, one will call the other until you run out of memory.