I have found a post here in SO discussing the code change required to prevent writing to a static field from an instance method but why is not a good practice to do so ? Why did Java designers allow this then ?In other words why does the compiler not throw an error when some one attempts to do this ?
3 Answers
In the words of the 'findbugz' documentation:
This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
Which is to say it isn't always wrong, simply that it is something that is often a source of errors. Instance objects manipulating static fields can be useful for example for lazy initialization of shared objects, so it is not always wrong, but it can be hard to get it right (particularly if multiple threads may be running at the same time).

- 14,841
- 9
- 83
- 130
-
how does running multiple threads runnning concurrently in this code make it buggy ? My question was to get an answer to this actually. Do we have the possiblity of creating multiple instances of the field ? – Inquisitive Jul 04 '12 at 08:29
-
There's only one field still, but if two of them both try to write at about the same time, then you can have end up with two objects being created and the field changing, whereas you probably wanted only one copy of the object to exist. This could cause serious issues in some cases, because different instances of the owner object could be using different shared objects. You'd need to put a synchronized(this.getClass()) block around any code that might change the static field to be sure it worked. – Jules Jul 04 '12 at 08:33
In addition to the above, from a documentation point of view it is easy for someone to assume it is an instance field, if you use the form:
someField = null
or
myObj.someField = null
Using the form
myClass.someField = null
makes it clearer and prevents the findbugz warning (apparently, I haven't tested). Note, that won't prevent the multi-threading issues described.

- 4,877
- 4
- 27
- 56
It can be usefull, for example if you got an application that manages ants and you need to be able to acces the total number of created ants from the ant class. This can be done by writing to a static method that keeps track of the total number of ants every time you create a new ant writes to the static method addAnt();

- 267
- 1
- 3
- 7