Should this variable be declared mutable?

outShould the variable in the MyThread class be declared mutable in this code, or will the "variability" of the variable stdoutin the ThreadTest class be carried?

import java.io.PrintStream;

class MyThread implements Runnable
{
    int id;
    PrintStream out; // should this be declared volatile?

    MyThread(int id, PrintStream out) {
        this.id = id;
        this.out = out;
    }

    public void run() {
        try {
            Thread.currentThread().sleep((int)(1000 * Math.random()));
            out.println("Thread " + id);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ThreadTest
{
    static volatile PrintStream stdout = System.out;

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new MyThread(i, stdout)).start();
        }
    }
}
+3
source share
4 answers

The qualifier volatilewill not migrate, and this makes no sense in the code above. Volatile sets a memory barrier when reading and writing to a variable that never changes after initialization in the constructor. For the same reason, the unstable classifier in ThreadTestalso has no purpose.

, volatile , .

+2

out MyThread "" stdout ThreadTest?

, .

JLS, volatile , out , , , .

out. - , / -, . , , ... ThreadTest.

:

  • out final. final , .

  • out private. " " start() , out .

+2

. , . volatile ThreadTest, .

0

.

Since there is a going- between objects created before calling Thread.start , and after calling Thread.start

0
source

Source: https://habr.com/ru/post/1747645/


All Articles