How do I suppress warning "Synchronization on a non-final field" - java

Is it possible to suppress this kind of warning?
Note: I am not looking for suppressing all warnings(like this #SuppressWarnings("all") ), but only the mentioned type.

For Intellij, put this annotation on the class that has the warnings
#SuppressWarnings("SynchronizeOnNonFinalField")
This lead me to the tag to use for suppression and trial and error lead me to put it on the class instead of on the field or synchronized statement. :-P

If you're using IntelliJ, it looks like it's #SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter"). Otherwise it depends. You might find the answer on the list here: What is the list of valid #SuppressWarnings warning names in Java?
Note that the warning is usually correct. In most cases you should just use a final field.

This would help you,
All values are permitted (unrecognized ones are ignored). The list of
recognized ones is compiler specific.
'unchecked' and 'deprecation' are required by the Java Language
Specification, and so should be valid with all compilers. For Sun's
compiler, running 'javac -X' gives a list of all values recognized by
that version. For 1.5.0_17, the list appears to be:
all deprecation unchecked fallthrough path serial finally
Please refer this, same has discussed here What is the list of valid #SuppressWarnings warning names in Java?

Related

Google errorprone java compiler - Default bugpatterns? Mark ignore?

I am getting some warnings regarding the accessing static method from a variable over class.
Is there a way to tell errorprone to ignore these warnings? Is error-prone loaded with a set of "bugpatterns"? Is it all of these:
https://github.com/google/error-prone/tree/master/core/src/main/java/com/google/errorprone/bugpatterns
How can I override for instance this to stop complaining:
Warning:(111, 21) java: [StaticAccessedFromInstance] Static method
info should not be accessed from an object instance; instead use
Log.info (see errorprone.info/bugpattern/StaticAccessedFromInstance)
Did you mean 'Log.info( EntityError.class, Gson.asString(this) );'?
I am using Intellij.
Maybe I am mistaken; but I think that "eclipse code cleanup" is able to fix this kind of code problem automatically.
My suggestion would be to rather spend time to understand how such bugs can be easily fixed; versus spending time to suppress the corresponding warning.
According to the errorprone flags documentation, you can switch the check off with:
-Xep:StaticAccessedFromInstance:OFF
However, I agree with Kayaman: you are better off fixing the problem than working to ignore it.

Advantage of #SuppressWarnings annotation

#SuppressWarnings annotation is for cleaner code or by adding it is there any performance gain or any advantage ?
or can we reduce compile time by doing so.
The #SuppressWarnings annotation type allows Java programmers to disable compilation warnings for a certain part of a program (type, field, method, parameter, constructor, and local variable). Normally warnings are good. However in some cases they would be inappropriate and annoying. So programmers can choose to tell the compiler ignoring such warnings if needed.
There is no relation with performance.
The developer who wrote the code knew that it was always going to be safe, decided to use #SuppressWarnings("unchecked") to suppress the warning at compilation.
As mentioned by others, it is just a trust between the developer and code written.
more info here and here
There is no performance gain, only when compiling, compiler will or will not write a waring. However after compilation, there is no difference whatsoever.
It does not make your code cleaner or improve the performance. It just helps you to concentrate your attention on potentially dangerous code. If you have a list of 130 warnings you will soon stop to read them.
Most warnings represents bad programming practices or potencial problems that the compiler is not able to solve. A finished program should, ideally, compile with no warnings. This way, when you modify it and a new warning appears you can decide what to do.
For example:
Unreachable code. What was I thinking here
Lib ZZZ is deprecated. Should I upgrade to the new one? Can I continue with this for now?
Add type arguments to list... ups, I should be using generics
SuppressWarnings annotation is just to suppress warnings that you know are sure to occur and you don't care about it. Its just helps you to have a cleaner inspection, suppressing warnings you expect to see. No performance gain.

How to specifically suppress "Comparing identical expressions" in Eclipse-Helios JDT

I tried annotating the enclosing method with
#SuppressWarnings("compareIdentical")
but this does not work (worse yet, the annotation results in its own Unsupported #SuppressWarnings("compareIdentical") warning!)
I know that I can always use
#SuppressWarnings("all")
but that'd be more warning-suppression than I want.
FWIW, I got the "compareIdentical" string from the "Warning Options" table in http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_api_compile.htm (a hail-mary pass, to be sure).
Thanks!
Officially, there are only 3 supported arguments to #SuppressWarnings(), as specified by the standard $9.6.4.5:
Unchecked warnings (§4.8, §5.1.6, §5.1.9, §8.4.1, §8.4.8.3, §15.12.4.2, §15.13.2, §15.27.3) are specified by the string "unchecked".
Deprecation warnings (§9.6.4.6) are specified by the string "deprecation".
Removal warnings (§9.6.4.6) are specified by the string "removal".
But, in small text, the standard mentions support for extra types:
For other kinds of warnings, compiler vendors should document the strings they support for #SuppressWarnings. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.
These are supported by some compilers:
all to suppress all warnings
boxing to suppress warnings relative to boxing/unboxing operations
cast to suppress warnings relative to cast operations
dep-ann to suppress warnings relative to deprecated annotation
deprecation to suppress warnings relative to deprecation
fallthrough to suppress warnings relative to missing breaks in switch statements
finally to suppress warnings relative to finally block that don't return
hiding to suppress warnings relative to locals that hide variable
incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
nls to suppress warnings relative to non-nls string literals
null to suppress warnings relative to null analysis
raw to suppress warnings relative to usage of raw types
restriction to suppress warnings relative to usage of discouraged or forbidden references
serial to suppress warnings relative to missing serialVersionUID field for a serializable class
static-access to suppress warnings relative to incorrect static access
super to suppress warnings relative to overriding a method without super invocations
synthetic-access to suppress warnings relative to unoptimized access from inner classes
unchecked to suppress warnings relative to unchecked operations
unqualified-field-access to suppress warnings relative to field access unqualified
unused to suppress warnings relative to unused code and dead code
So, there is nothing which might help you.

Java: complete list of #SuppressWarnings(...) parameters (in Netbeans)?

Netbeans provides a lot of custom "hints", which are like warnings, only that most of them can't be suppressed (just disabled IDE-globally).
But now I looking at code which uses
#SuppressWarnings("element-type-mismatch")
to suppress a hint/warning which is called "suspicious method call" (such as remove(...) for a collection with a "wrong" type).
Well, I would never come to the idea to suppress a hint named "suspicious method call" with a SuppressWarnings-parameter called "element-type-mismatch", but apparently, it works.
So, is there a "magic list" of such parameters?
How, for instance, do I suppress the hint/warning "return of collection field"?
NOTE: for this similar question, "element-type-mismatch" is not listed.
After a brief look at the NB-sourcecode, I found these in some of the java.hint -classes:
#Hint(category="bitwise_operations", suppressWarnings="IncompatibleBitwiseMaskOperation")
#Hint(category="initialization", suppressWarnings="LeakingThisInConstructor")
#Hint(category="logging", suppressWarnings={"NonConstantLogger"}) //NOI18N
#Hint(category="logging", suppressWarnings={"ClassWithMultipleLoggers"}) //NOI18N
#Hint(category="logging", suppressWarnings={"ClassWithoutLogger"}, enabled=false) //NOI18N
#Hint(category="code_maturity", suppressWarnings="UseOfObsoleteCollectionType")
#Hint(category="initialization", suppressWarnings="OverridableMethodCallInConstructor")
#Hint(category="bitwise_operations", suppressWarnings="PointlessBitwiseExpression")
#Hint(category="code_maturity", suppressWarnings="CallToThreadDumpStack")
#Hint(category="bitwise_operations", suppressWarnings="ShiftOutOfRange")
#Hint(category="initialization", suppressWarnings="StaticNonFinalUsedInInitialization")
#Hint(category="code_maturity", enabled = false, suppressWarnings="UseOfSystemOutOrSystemErr")
#Hint(category="code_maturity", suppressWarnings="CallToPrintStackTrace")
Apparently, not all IDE-hints that are displayed as warnings are made suppressable...
Don't know why though, 'cause the AbstractHint class wich many of them extends easily provides this ability...
These are just the suppress-names though, so to find the mapping to the names of the warnings they represent, a deeper dig in the source is needed.
The documentation says:
Compiler vendors should document the warning names they support in conjunction with this annotation type. They are encouraged to cooperate to ensure that the same names work across multiple compilers.
Since NetBeans is using javac I think, here is a list.
See also this question.
If you are using another compiler, or some compiler plugin, search for its documentation.
Well the list is hard to find. Did find the sources of the hint classes of Netbeans.
So the 'list' is here. (also look at the sub packages; e.g. jdk and perf)
All classes can be supressed by using its camel cases name like:
// org.netbeans.modules.java.hints.jdk.UnnecessaryBoxing.java
#SuppressWarnings("UnnecessaryBoxing")

How to avoid unchecked-conversion-warning in Java, if you use legacy libraries?

I like the generics-feature in java and use it often. But I have a problem, if I use libraries that aren't yet aware of generics. An example are servlets. If you use ServletRequest.getParameterMap() the result will be a raw map, but it includes only String as keys and String[] as values. So I want to assign it to a Map<String, String[]>. But for this assignment I get an warning. How can I avoid this warning with the language, not by simply suppressing the warning with the #SuppressWarnings annotation.
As others have said the warnings cannot be avoided except by suppressing them. The issue IMHO is that either you have to litter your code with annotations that apply to small scope or ignore them globally and risk errors.
IIRC there is a proposal to generate warnings where the raw types are being returned instead of at the call.
Meanwhile, I think the best approach is to use a wrapper method so that the warnings are limited to a single place, where it is safe to ignore them:
class NoWarn {
public static Map<String, String[]> getParameterMap(ServletRequest r)
{
#SuppressWarnings("unchecked")
Map<String, String[]> result = r.getParameterMap();
return result;
}
}
Note
This answer was edited with a comment that annotations cannot be inside method bodies. That is incorrect, the above is syntactically correct. I have reverted the change.
The cleanest thing you can do is to encapsulate the conversion from legacy to generic code and suppress the warning only there.
E.g. you could put a generic facade on your legacy library, though this might not always be worthwhile.
How can I avoid this warning with the
language, not by simply suppressing
the warning with the
SuppressWarnings-annotation.
The annotation is the way to avoid the warning with the language. There is no other way.
Stumbled upon this question as I was also trying to figure out a way to avoid using the suppress annotation in such cases. I found another alternative which I thought was worth mentioning:
Map<?, ?> map = servletRequest.getParameterMap();
String[] values = (String[]) map.get("key");
We are basically using wildcard '?' to indicate that the map can have any type of key and value.
Potential downside I see here is that we are doing an explicit cast while fetching values, which I think will result in a slight performance overhead during runtime.
I don't think you can. The warning will appear unless you suppress it, or filter it from your IDE's warnings list.
I had the same problem, i just turned off all generic warnings and im happy :) You could also turn off serialVersionUID warning since many people dont use serialVersionUID.
in Eclipse - Window/Perferences/Java/Compiler/Errors/Warnings and turn off all Generic types.
P.S. Many bad warnings make you ignore all the warnings and some might be usefull.
as others said, the only way to get rid of this warning is to suppress it.
the best practice is to encapsulate the warning using methods and classes.
but with other warnings, always try to solve the problem that are making them, like remove unused imports and etc... it makes your application leaner and better.
happy coding

Categories