0

I know thread synchronization. But in this code from the book Java Network Programming by Merlin Hughes, it is written that the println method synchronizes on System.out. I don’t understand how a method could be synchronized on System.out.

Second question I wanna ask: Is the println function an overridden method or is it just a user defined method in this code?

import java.io.*;

public class SimpleOut  {

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < args.length; i++) {
            println (args[i]);
        }
    }

    public static void println(String msg) throws IOException {
        synchronized (System.out) {
            for (int i=0 ; i<msg.length(); i++) {
                System.out.write(msg.charAt (i) & 0xff);
            }
            System.out.write('\n');
        }
        System.out.flush();
    }

}
Palec
  • 12,743
  • 8
  • 69
  • 138
Junaid Shirwani
  • 360
  • 1
  • 6
  • 20
  • 1
    You can synchronize on any object via a reference - why would you expect `System.out` to be different? And the `println` method in your code can't be overriding anything - it's static... – Jon Skeet Feb 22 '14 at 18:09
  • is system.out an object ,if yes? whos object is it? and when was it created? the reason i asked println to an overridden method is that println is a predefined function ,please explain – Junaid Shirwani Feb 22 '14 at 18:11
  • refer what is system.out http://javapapers.com/core-java/system-out-println/ – NFE Feb 22 '14 at 18:13
  • Synchronizing on a globally available reference, which can be reassigned (using `System.setOut()`) doesn't look like a very good idea to me. The method should use its own private, final lock. – JB Nizet Feb 22 '14 at 18:15
  • @JunaidShirwani: Well `out` is a class field in the `System` class. You'd be synchronizing on the object that the value of the field refers to... – Jon Skeet Feb 22 '14 at 18:29

2 Answers2

1

You can synchronize over any Object/Instance. out is an class variable declared in the class java.lang.System.

public final static PrintStream out
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

Synchronization is mechanism that you do it on specified 'resource' ~ reference. System.out is also that resource. There is also link to post about that link

This is also very good blog to understand some harder things in java I am reading it when I have time there is lot of useful stuff. Java revisited

Community
  • 1
  • 1
RMachnik
  • 3,598
  • 1
  • 34
  • 51