How to write safely in a static field in Java?

Let's say I had a class that creates objects and tracks the number of objects with a static variable. Something like that:

public class Apple { private static int count = 0; public Apple () { count++; } public void removeApple() { count--; } } 

When I check this code with FindBugs, I get a warning Write to static field from instance method , which is obvious, of course.

How can I get around this problem and make it safer and even get rid of this FindBugs warning?

+4
source share
4 answers

1. General programming advice

This message should warn you of a potential programming error, as this is a common mistake for novice programmers who do not know the differences between static and instance variables.

However, if you can declare your real version of the removeApple static method without causing compiler errors, then most likely you should. This will take care of the warning and make it clear that this method has nothing to do with any particular instance of your class.

2. Problems associated with concurrency

Another aspect of this warning is thread safety. If you write to the static field from an instance, this opens up the possibility that you will perform parallel updates from different threads, even without sharing class instances between threads.

If you do not need thread safety for your code (which is completely normal in general), you do not need to do anything. If you need it, synchronize all field updates or use the AtomicInteger wrapper.

Personally, I would choose AtomicInteger , because this is the safest option: for other parameters, you will need to chase all field updates around the class and make sure that they are synchronized. Using AtomicInteger very simple:

 private static final AtomicInteger count = new AtomicInteger(); 

and then use count.getAndIncrement() instead of count++ .

+9
source

Use AtomicInteger instead of int primitive.

You can synchronize the method.

+3
source

You have two options:

AtomicInteger is used in applications such as atomic stream increment counters.

or

2. Control variable access by synchronized block

And only in terms of removing Findbug error:

Logically, we expect instance methods to affect instance data. We expect static methods to affect static data.

Make the counter private and provide the public methods getter and setter will take this findbug error.

+1
source

In all likelihood, FindBugs would prefer that removeApple () were static

+1
source

Source: https://habr.com/ru/post/1489251/


All Articles