'what else we can use instead of import com.sun.management.OperatingSystemMXBean as this import is giving me Sonar issue
Due to project sec. issues . Not allowed to use com.sun.management.OperatingSystemMXBean . Instead i am trying to use java.lang.management.OperatingSystemMXBean . But in my method i need to know the cpuLoad (getSystemCpuLoad) . how can i get the same using lang.management ? is there any method present in java. lang.* to get the systemcpuLoad ?
Solution 1:[1]
I don't think there is an alternative. At least not in the standard Java SE class libraries1.
Not all
com.sun.*
packages are considered to be closed APIs. In this case the javadocs include this interface. I take that as an implicit statement that this is an open API.If this is just the generic warning from SonarQube that you shouldn't depend on
com.sun.*
andsun.*
APIs (see RSPEC-1191), my advice is to suppress the warning for this particular case.I don't see how this is a project "security" issue. Please explain why you think that.
Okay. Let me put my question in this way : How to
getSystemCpuLoad
method injava.lang.management.OperatingSystemMXBean
.
One way is just like your current code (presumably) does. Cast the MXBean
instance to a com.sun.management.OperatingSystemMXBean
and call the method. (And suppress the SonarQube warning.)
The one thing to note is that the getSystemCpuLoad
method is marked as deprecated in Java 17. You should now use getCpuLoad
instead.
1 - If you found and used a 3rd-party library2 that provides this functionality, or it you implemented your own (in native code, for example), I think you will be making the problem worse. Now you have an extra dependency to track or extra code to maintain. Bear in mind that the implementation of this functionality is OS specific, so you would need to find or write an implementation that works on all of your platforms, both now and in the future.
2 - Beware of posts that suggest using the SIGAR library. It hasn't been updated in a long time, and there are reports that its problematic on some platforms.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |