Search code examples
javamultithreadingconcurrencysleepthread-sleep

How to get rid of this "static method should be acessed in a static way" in java?


I have the following piece of code in a java application

Thread.currentThread().sleep(10000);

However eclipse is showing me the following warning:

The static method sleep(long) from the type Thread should be accessed in a static way

I am very proud of never release code with warnings, and I would like to get rid of this warning (it occurs in two different classes). Do I need to post the entire code?


Solution

  • You call

    Thread.sleep(10000);
    

    It always makes the current thread sleep. Even if you did:

    Thread t = new Thread(...);
    t.start();
    t.sleep(10000);
    

    That would still make the current thread sleep for 10 seconds, while leaving the new thread to go on its merry way. This is almost the canonical example for why this warning is important - it's because you're calling a static method as if it were an instance method, which makes it look like it matters what you're calling it on. It doesn't. The value isn't even checked for nullity:

    Thread t = null;
    t.sleep(10000); // Still sleeps for 10 seconds...
    

    (I'm proud to say I originally filed a feature request for this warning in Eclipse back in June 2002 :)