skip to content

What does java.lang.System provide, how do getProperty and getenv differ, and which of currentTimeMillis and nanoTime measures elapsed time?

level: juniorimportance: should knowfreq 54%

answer

  1. static access to the runtime's surroundings
  2. JVM settings versus OS settings
  3. -D on the command line
  4. wall clock versus arbitrary origin
  5. subtract two readings from one JVM

basics

~20 s

java.lang.System is a static utility class for standard streams, properties, the environment, time and array copying. getProperty reads this JVM's settings; getenv reads the OS process environment. Measure elapsed time with nanoTime, since currentTimeMillis is a wall-clock timestamp.

solid answer

~40 s

`java.lang.System` cannot be instantiated; it offers static access to the standard streams, system properties, environment variables, native library loading, `arraycopy` and the clocks. `System.getProperty` reads the JVM's own properties, which come from JVM start-up, `-Dname=value` or `setProperty`, whereas `System.getenv` reads the variables the OS gave the process, which Java can read but not change; both return `null` for a missing name. `currentTimeMillis()` gives wall-clock milliseconds since the 1970 epoch, so it suits a timestamp, but the difference between two readings can jump if the system clock is adjusted. `nanoTime()` counts from an arbitrary origin unrelated to wall-clock time, and its documentation says it can only be used to measure elapsed time, so I subtract two readings from the same JVM and compare them as `now - start >= timeout`.

code

java · 18 lines
java
import java.time.Duration;

public class SystemDemo {
    public static void main(String[] args) throws InterruptedException {
        // Run with: java -Dregion=eu SystemDemo
        System.out.println(System.getProperty("region"));          // eu
        System.out.println(System.getProperty("tier", "free"));    // free
        System.out.println(System.getenv("region"));               // null unless the OS set it

        long start = System.nanoTime();
        Thread.sleep(50);
        long elapsed = System.nanoTime() - start;
        System.out.println(Duration.ofNanos(elapsed).toMillis()); // roughly 50, often a little more

        long timeoutNanos = Duration.ofSeconds(5).toNanos();
        System.out.println(System.nanoTime() - start >= timeoutNanos); // false
    }
}

go deeper

for a junior

Recall what System offers, that getProperty reads JVM settings such as -D values while getenv reads OS variables, and that nanoTime is the one for elapsed time.

for a middle

Explain why nanoTime has an arbitrary origin and only differences mean anything, why the timeout check subtracts rather than adds, and that changing a standard property may have no effect because values can be cached.

for a senior

Show production judgment: timeouts and metrics that survive a wall-clock adjustment, nanoTime values never persisted or sent to another JVM, and settings read once at start-up rather than through scattered getenv calls.

for a principal

Weigh how far a team lets code read the environment and clocks directly: one start-up configuration object and an injected time source cost some wiring, and they buy testability and one clear place to audit settings.

## What System is `java.lang.System` is a final class with a private constructor, so it cannot be instantiated, and its fields and methods are static. Its documentation lists the main facilities, and a few more sit beside them: - **Standard streams:** `System.in`, `System.out` and `System.err`, replaceable with `setIn`, `setOut` and `setErr`. - **External settings:** system properties through `getProperty` and environment variables through `getenv`. - **Time:** `currentTimeMillis()` and `nanoTime()`. - **Array copying:** `arraycopy`. - **Native libraries:** `load` and `loadLibrary`. - **Runtime helpers:** `exit`, `gc`, `identityHashCode`, `lineSeparator`, `console` and `getLogger`. Interviews mostly ask about two pairs in that list, because each pair holds one behaviour people get wrong. ## System properties versus environment variables A **system property** is a name-value pair held inside this JVM, in the `java.util.Properties` object that `System.getProperties()` returns. The JVM fills in standard keys such as `java.version`, `os.name`, `user.home` and `java.io.tmpdir`, and you add your own with `-Dname=value` on the `java` command line or `System.setProperty` at run time. An **environment variable** is a name-value pair the operating system keeps for a process, inherited from the process that started it. Java reads it through `getenv`. | | `System.getProperty(name)` | `System.getenv(name)` | |---|---|---| | Where it lives | Inside this JVM | In the OS process environment | | How it is set | JVM start-up, `-Dname=value`, `System.setProperty` | The parent process, before the JVM starts | | Change from Java | Yes: `setProperty`, `clearProperty` | No: `System` has no setter, and `getenv()` returns an unmodifiable map | | Child processes | See only what you pass them | Start with a copy by default | | Missing name | `null`, or the default from `getProperty(name, def)` | `null`, with no default overload | | Name case | Exact | Typically significant on UNIX, typically not on Windows | Two cautions come from the documentation itself: - Changing a **standard** property after start-up "may have unpredictable results", because values may be cached during initialization or on first use. - The `getenv` documentation says it is best to use system properties where possible, because environment variables are visible to all descendants of the process and can have subtly different semantics between operating systems. It reserves them for when a global effect is wanted or an external system interface requires one, such as `PATH`. A deployment platform that injects settings as environment variables is that second case. Both methods reject a `null` name with `NullPointerException`, and `getProperty` also rejects an empty one with `IllegalArgumentException`. ## currentTimeMillis versus nanoTime | | `System.currentTimeMillis()` | `System.nanoTime()` | |---|---|---| | Meaning | Milliseconds since 1970-01-01 00:00 UTC | Nanoseconds since a fixed but arbitrary origin | | Tied to the wall clock | Yes | No | | Can be negative | Not for present-day dates | Yes: the origin may be in the future | | Between two JVMs | Comparable, subject to their machines' clocks | Not comparable: other JVMs are likely to use a different origin | | Granularity | Depends on the OS, possibly tens of milliseconds | Nanosecond precision, resolution at least as good as `currentTimeMillis()` | | Job | A timestamp | Elapsed time | Use `nanoTime()` for elapsed time. Its documentation says it "can only be used to measure elapsed time" and is not related to any notion of system or wall-clock time. `currentTimeMillis()` reports the wall clock, which time synchronization or an administrator can move, so the difference between two readings can jump or even go negative. ## Measuring elapsed time 1. Take `long start = System.nanoTime();` immediately before the work. 2. Run the work. 3. Compute `long elapsed = System.nanoTime() - start;`. 4. Convert it for display with `Duration.ofNanos(elapsed)` or `TimeUnit.NANOSECONDS.toMillis(elapsed)`. For a timeout, compare the difference: `System.nanoTime() - start >= timeoutNanos`. The documentation warns against `System.nanoTime() >= start + timeoutNanos` because of numerical overflow. Differences stay correct for spans up to about 292 years. ## Traps - **`nanoTime()` as a timestamp.** One reading means nothing alone, and a reading sent to another JVM or kept across a restart cannot be compared with anything there. - **Parser look-alikes.** `Boolean.getBoolean(name)` and `Integer.getInteger(name)` look up a system property with that name; they do not parse their argument. - **A missing variable.** `System.getenv("X").isEmpty()` throws `NullPointerException` when `X` is undefined, because the result is `null`, not an empty string. For domain code that needs the current time, `java.time.Clock` is the injectable form of the wall clock, covered with the zone-aware date-time types.

  • Why does Boolean.getBoolean("true") return false in Java?
    `Boolean.getBoolean(name)` is not a parser. It looks up the system property called `name` and returns true only if that property exists and equals `"true"`, ignoring case. `Integer.getInteger(name)` does the same for integers, returning `null` when the property is missing or not numeric. To parse a string, use `Boolean.parseBoolean` or `Integer.parseInt`.
  • What does System.nanoTime() promise about resolution, and does its Javadoc call it monotonic?
    It gives nanosecond precision but not necessarily nanosecond resolution: the only guarantee is a resolution at least as good as `currentTimeMillis()`, so two quick calls can return the same value and an elapsed time can read zero. Its Javadoc does not use the word monotonic. It promises one origin per JVM instance and that the difference between two values measures elapsed time.
  • Should a Java service read its settings from system properties or environment variables?
    The `getenv` documentation prefers system properties where possible, since environment variables reach all descendant processes and can differ subtly between operating systems. It keeps them for a wanted global effect or an external interface that requires one, and a platform injecting settings as variables is that case. A service can read both, with the precedence decided once, at start-up, in one place.

  • Differences of currentTimeMillis are always exact durations, because the system clock never moves backwards.
  • nanoTime returns nanoseconds since the Unix epoch, so it can serve as a timestamp.
  • nanoTime readings from two JVMs on one machine can be subtracted safely.
  • Passing -Dname=value also sets an environment variable of that name.
  • A Java program can change its own environment through System.setenv.
  • nanoTime always changes every nanosecond, because it returns nanoseconds.

java.lang.System
Java 1.0
System.nanoTime
Java 1.5

context