Search code examples
javajava-threads

How can I wake a sleeping thread only with certain condition in java?


Currently I am accessing server from my client android device after every 10 second using Thread.sleep function and check if any new content have been updated to server and do the same update to client device after sleep. so every thing works well in one while loop. But now I even want to check if something has been updated to server even in that sleep mode. In case if some new update available to the server, then I have to break that sleep and do update to client device from the server, otherwise let it sleep for the duration of time. Main reason is I want to increase sleep time, but at the same time check the status of server for update and do update. Need to reduce server treffic by increasing sleep time ,but need to update even in between the sleep new update arise.

public void run() {

        while( m_KeepRunning ) {

            // 10s sleep to give the app time to start
            try {
                for( int i = 0; i < 10 && m_KeepRunning; i++) {
                    Thread.sleep( 1000 );
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        Log.d("SERVER", "--- Start update from Server ");

        servercallfunction();// suppose to call server and check for new update :if do then  update to client machine 

}
}

Solution

  • Since you are making server in sleep for some limited time , it wont be able to find server status in that period of time, so no question of getting server status in that period of time as its in sleep mode. In order to get server status , thread has to come out of sleep. So if you need to reduce server traffic by going to sleep , you have to sacrifice the offline from server during those period as well.