java: "final" System.out, System.in and System.err?

JavaFinal

Java Problem Overview


System.out is declared as public static final PrintStream out.

But you can call System.setOut() to reassign it.

Huh? How is this possible if it's final?

(same point applies to System.in and System.err)

And more importantly, if you can mutate the public static final fields, what does this mean as far as the guarantees (if any) that final gives you? (I never realized nor expected System.in/out/err behaved as final variables)

Java Solutions


Solution 1 - Java

JLS 17.5.4 Write Protected Fields:

> Normally, final static fields may not be modified. However System.in, System.out, and System.err are final static fields that, for legacy reasons, must be allowed to be changed by the methods System.setIn, System.setOut and System.setErr. We refer to these fields as being write-protected to distinguish them from ordinary final fields. > > The compiler needs to treat these fields differently from other final fields. For example, a read of an ordinary final field is "immune" to synchronization: the barrier involved in a lock or volatile read does not have to affect what value is read from a final field. Since the value of write-protected fields may be seen to change, synchronization events should have an effect on them. Therefore, the semantics dictate that these fields be treated as normal fields that cannot be changed by user code, unless that user code is in the System class.

By the way, actually you can mutate final fields via reflection by calling setAccessible(true) on them (or by using Unsafe methods). Such techniques are used during deserialization, by Hibernate and other frameworks, etc, but they have one limitation: code that have seen value of final field before modification is not guaranteed to see the new value after modification. What's special about the fields in question is that they are free of this limitation since they are treated in special way by the compiler.

Solution 2 - Java

Java uses a native method to implement setIn(), setOut() and setErr().

On my JDK1.6.0_20, setOut() looks like this:

public static void setOut(PrintStream out) {
    checkIO();
    setOut0(out);
}

...

private static native void setOut0(PrintStream out);

You still can't "normally" reassign final variables, and even in this case, you aren't directly reassigning the field (i.e. you still can't compile "System.out = myOut"). Native methods allow some things that you simply can't do in regular Java, which explains why there are restrictions with native methods such as the requirement that an applet be signed in order to use native libraries.

Solution 3 - Java

To extend on what Adam said, here is the impl:

public static void setOut(PrintStream out) {
	checkIO();
	setOut0(out);
}

and setOut0 is defined as:

private static native void setOut0(PrintStream out);

Solution 4 - Java

Depends on the implementation. The final one may never change but it could be a proxy/adapter/decorator for the actual output stream, setOut could for example set a member that the out member actually writes to. In practice however it is set natively.

Solution 5 - Java

the out which is declared as final in System class is a class level variable. where as out which is in the below method is a local variable. we are no where passing the class level out which is actually a final one into this method

> public static void setOut(PrintStream out) { > checkIO(); > setOut0(out); > }

usage of the above method is as below:

System.setOut(new PrintStream(new FileOutputStream("somefile.txt")));

now the data will be diverted to the file. hope this explanation makes the sense.

So no role of native methods or reflections here in changing purpose of the final keyword.

Solution 6 - Java

As far as how, we can take a look at the source code to java/lang/System.c:

/*
 * The following three functions implement setter methods for
 * java.lang.System.{in, out, err}. They are natively implemented
 * because they violate the semantics of the language (i.e. set final
 * variable).
 */
JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
    jfieldID fid =
        (*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
    if (fid == 0)
        return;
    (*env)->SetStaticObjectField(env,cla,fid,stream);
}

...

In other words, JNI can "cheat". ; )

Solution 7 - Java

I think setout0 is modifying local level variable out, it can't modify class level variable out.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason SView Question on Stackoverflow
Solution 1 - JavaaxtavtView Answer on Stackoverflow
Solution 2 - JavaAdam BatkinView Answer on Stackoverflow
Solution 3 - JavaAmir RaminfarView Answer on Stackoverflow
Solution 4 - JavavickirkView Answer on Stackoverflow
Solution 5 - JavaKrish KrishnaView Answer on Stackoverflow
Solution 6 - JavaRadiodefView Answer on Stackoverflow
Solution 7 - Java坂田鈴木View Answer on Stackoverflow