Search code examples
javaandroidmultithreadingthread-safetythread-sleep

why object.wait(value) is not accurate?


consider this code which basically has an object(WaitedObject) and two threads(SomeTask and SomeTaskWithWait) compete to call the methods (longRunningTask() and withWaitTask() respectively) of the object synchronously

package closerLookAtWait;
class WaitedObject
{
    int i=0;
    synchronized void longRunningTask()
    {

            System.out.println(i++);
            for(long j=999; j>0; j--)
            {}
    }
    synchronized void withWaitTask()
    {

            System.out.println("Now Waiting");
            long time1 = System.currentTimeMillis();
            try {
                //Thread.sleep(500);
                wait(50);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            long time2 = System.currentTimeMillis() - time1;
            System.out.println("Done Waiting for "+time2);

    }
}
class SomeTask implements Runnable
{
    WaitedObject wo;
    SomeTask(WaitedObject wo)
    {
        this.wo = wo;
    }
    @Override
    public void run() {

        while(true)
            wo.longRunningTask();
    }
}
class SomeTaskWithWait implements Runnable{

    WaitedObject wo;
    SomeTaskWithWait(WaitedObject wo)
    {
        this.wo = wo;
    }
    @Override
    public void run() {
        while(true)
        wo.withWaitTask();
    }
}
public class SomeWaitingWithLong {

    public static void main(String[] args) {
        WaitedObject wo = new WaitedObject();
        new Thread(new SomeTask(wo)).start();
        new Thread(new SomeTaskWithWait(wo)).start();
    }

}

sample output:

well i got output as 54,54,50,65,51,52,..,78,..84,..50,52,52.

now my question is why such inaccuracy? (even 65 is ok, but why 84?)


Solution

  • One of the reasons is, OS puts that thread in suspended mode for the time(ms) you provide in wait(). When the time completes it isn't guarrented that your thread will be executed at once because OS has assigned another thread with a higher priority in your process to be executed by the processor or some other higher priority process is being assigned to the processor for execution. Even if your thread was at highest priority, even then there will be some delay sometimes because of context switching & in Java's case, GC.