Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 422
Victor Avatar asked Oct 03 '11 22:10

Victor


People also ask

How do you remove a static method in Java?

runCommandLoop(); skeleton. closeDown(); This will let you remove the static keyword from all of the other method signatures, as they are now associated with an instance of the ProgramSkeleton class.

How static method should be accessed in a static way?

This is what is meant with the warning, “a static method (sayHello) should be accessed in a static way (via the class name Parent or Child).” This convention helps reduce the chance that we've made a coding mistake and it helps clarify that a class method is being called to those who subsequently read our code.

How do I make a static method thread safe?

Now if you want to make this method really thread safe then one simple thing you can do. Either use non-mutable variables / objects or do not change / modify any method parameters.

What can I use instead of static methods?

You can use the full power of inheritance and overriding since your methods are no longer static. You can use the constructor to do any initialisation, including associating SQL with the table (SQL that your methods can use later). This should make all your problems above go away, or at least get much simpler.


1 Answers

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 :)

like image 167
Jon Skeet Avatar answered Nov 06 '22 15:11

Jon Skeet