A Bad Way of Getting Java System Property

I don't like code like this:

String flag1 = System.getProperties().getProperty("flag1.key");
String flag2 = System.getProperties().getProperty("flag2.key");
Why not just call System.getProperty("flag1.key")? In most cases, the two produces the same result. But the former is unnecessarily verbose.

You may be able to save some security check overhead by caching the system properties inside your application, if you need to get a series of properties, and if SecurityManager is enabled. For example,
Properties sysProps = System.getProperties();
String flag1 = sysProps.getProperty("flag1.key");
String flag2 = sysProps.getProperty("flag2.key");
The security check is only performed once in the above block. But it requires both read and write permission on all system properties: permission java.util.PropertyPermission "*", "read,write";

With System.getProperty("key"), security check is performed for every call. But it only requires read permission on the target property: permission java.util.PropertyPermission "key", "read";

The savings may be negligible, if any. The only time I will use System.getProperties() is when the property key is unknown, and the application needs to iterate through all system properties based on some criteria. For example,
Properties myProps = new Properties();
Properties sysProps = System.getProperties();
Set<Map.Entry<String, String>> entrySet =
while(entrySet.hasNext()) {
Map.Entry entry = entrySet.next();
String key = entry.getKey();
if(key.startsWith("foo.")) {
myProps.setProperty(key, entry.getValue(key));


Unknown said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

eMexoT said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

Internet Of Things training in electronic city

Cipro said...

Thanks for your informative blog! Your article helped me to understand the future of programming language. Keep on updating your with such awesome information about Friv 2020

keanna said...

The CCNA training in Gurgaon is the composite test associated with the Cisco Certified Network Associate Routing and Switching accreditation. Different ccna institutes in Gurgaon and This test tests a contender's data and capacities expected to present, work, and explore a little to medium size endeavor branch framework.
For More Details:- CCNA course in Gurgaon