Is multi-thread output from System.out.println interleaved

后端 未结 4 962
青春惊慌失措
青春惊慌失措 2020-11-22 08:19

If multiple threads call System.out.println(String) without synchronization, can the output get interleaved? Or is the write of each line atomic? The API makes no mention of

4条回答
  •  無奈伤痛
    2020-11-22 08:56

    Since the API documentation makes no mention of thread safety on the System.out object nor does the PrintStream#println(String) method you cannot assume that it is thread-safe.

    However, it is entirely possible that the underlying implementation of a particular JVM uses a thread-safe function for the println method (e.g. printf on glibc) so that, in reality, the output will be guaranteed per your first example (always ABC\n then ABC\n, never interspersed characters per your second example). But keep in mind that there are lots of JVM implementations and they are only required to adhere to the JVM specification, not any conventions outside of that spec.

    If you absolutely must ensure that no println calls will intersperse as you describe then you must enforce mutual exclusion manually, for example:

    public void safePrintln(String s) {
      synchronized (System.out) {
        System.out.println(s);
      }
    }
    

    Of course, this example is only an illustration and should not be taken as a "solution"; there are many other factors to consider. For example, the safePrintln(...) method above is only safe if all code uses that method and nothing calls System.out.println(...) directly.

提交回复
热议问题