stella
stella

Reputation: 2596

Is it safe to read from StdIn and write to StdOut concurrently?

Here's the code:

public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(new Runnable() {
        public void run() {
            while(true){
                BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
                try {
                    System.out.println(buffer.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    t.start();
    while(true){
        System.out.println("Text");
        Thread.sleep(1000);
    }
}

I'm not quite sure if it's actually safe to do so. Can some cucncurrency bug arise in such code? I ran a couple of tests and it works pretty fine, but who knows how it will behave after 1000000 attempts...

Upvotes: 1

Views: 137

Answers (1)

sstan
sstan

Reputation: 36503

Yes, it's safe. If you look at the implementation for println, you'll see that the code is synchronized:

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

Upvotes: 2

Related Questions