Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stops at thread's try-catch

I'm trying to write a code that will return my raspberry's IP when it's on the same network as my computer. The idea is for it to make a broadcast like Samba (Broadcast resolution is the closest to the original NetBIOS mechanism. Basically, a client looking for a service named Trillian will call out "Yo! Trillian! Where are you?", and wait for the machine with that name to answer with an IP address. Source: Samba team)

So here is the code:

public class GetIP {
    static String url; //global so I can access it after the threads are finished

    public class CheckIP extends Thread {
       private String url_test;

        public CheckIP(String url_t) {
            url_test = url_t;
        }

        public void run(){
            try {
                result = getHTML(this.url_test);  //result = the response from the GET request to this.url_test
            } catch (Exception e) {

            }

            if(result <is what I want>) {
                url = this.url_test  
                System.out.println("Flag 1");
                <I'd like to do something here, preferebly kill all other 
                threads that are trying to connect to an 'unserved' URL>
            }
        }
    }


    public static void main(String[] args) throws Exception{

        String ip_partial = <my computer's IP without the last part - ex: "192.168.0." , I'll hide the functions to make it short>;

        Thread myThreads[] = new Thread[254];
        for (int i = 1; i < 255; i++) {
            String url_test="http://"+ip_partial+i+":<port + endpoint>";
            GetIP getip = new GetIP ();
            myThreads[i] = new Thread(getip.new CheckIP(url_test));
            myThreads[i].start();
        }
        for (int i = 1; i < 254; i++) {
            System.out.println("Flag 2");
            myThreads[i].join(); //todo add catch exception
        }
    }   
}

I can see flag 1, and I did print the first 'for' so I know there are 254 threads being created, however I cannot see flag 2. It never shows, nomatter how long I wait. Any ideas why?

like image 404
Laura Martins Avatar asked Oct 17 '22 03:10

Laura Martins


1 Answers

The problem with your code is java.lang.ArrayIndexOutOfBoundsException:

You are executing the loop till 254th index, whereas your array size itself is 254 which means the index present is 253 since java starts it's indexing from 0.

The first loop should also run the same no of iteration as your second loop.

for (int i = 1; i < 254; i++) {
                    /\
                    ||
                    ||
                    ||
      This should not be 255 else you'll get OutOfBounds Exception.
}
like image 132
Neeraj Jain Avatar answered Oct 21 '22 02:10

Neeraj Jain