简体   繁体   中英

Is it thread-safe to access outer field (non-final) from inner class thread?

Basically the following works but since I read about the final keyword I am not sure anymore if I have to declare name final if different threads access it?

Thanks in advance.

public class Test4 {

    // to ensure thread-safety do we have to declare the variable name final ?
    private String name;

    public Test4 (String name) {
        this.name = name;
    }

    public void start() {
        new MyThread().start();
    }

    private class MyThread extends Thread {

        public void run() {
            System.out.println(name);
        }
    }

    public static void main(String[] args) {
        Test4 t = new Test4("Don't know if I am threadsafe");
        t.start();
    }

}

The final modifier - while preventing the member from being re-assigned - does not affect the correctness of the given code 1

From the the 17.4.4 Synchronization Order section for the Java 5 Language Specification:

A synchronization order is a total order over all of the synchronization actions of an execution .. Synchronization actions induce the synchronized-with relation on actions, defined as follows:

  • ..
  • An action that starts a thread synchronizes-with the first action in the thread it starts .
  • ..

Then, since the thread that sets the name member is the one that starts the thread, the synchronization order is guaranteed. (Synchronizes-with implies a Happens-before ordering .)

Note that:

  • The member name needs only be set before starting the thread: that is, it does not need to be set in the constructor for this synchronizes-with guarantee.
  • This does not guarantee synchronization ordering - and thus it does not guarantee happens-before or value visibility - between already running threads or threads created elsewhere!

However, final fields do give a much more comfortable feeling (ref. 17.5 Final Field Semantics ):

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object *after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields .

In this case, with final fields, the value is guaranteed to be visible on every thread after the constructor completes. (This guarantee can be violated by "constructor leaks" .)


1 In the supplied code the "non-final" name member is only assigned once before the thread is started.

In different , less trivial, programs other synchronization issues may be exposed. This answer examines if removing final alters the correctness of the supplied code.

All that being said, I consider it "good practice" to use both immutable variables ( final ) and immutable objects - especially when dealing with threads. Instead of needing to know the little arcane details of the JVM, do the safe proven things and strive for obvious correctness over cleverness or "performance".

See also:

最终变量是immutable ,一旦构造它就不能改变它,因此它没有并发问题。

You will not get the correct value of the field without final.

Maybe the thread got the old value after you changing the value of field.

Check the Visibility of JMM.

Another link of volatile .

Happends-Before Rule .

Happends-Before in JMM .

Could you be looking for an AtomicReference or perhaps volatile ? It depends what you mean by thread safe ?

// Atomic to allow deeper control of updates.
private AtomicReference<String> name = new AtomicReference<String>();
// Volatile to ensure it is not cached.
private volatile String vName;

public Test(String name) {
  this.name.set(name);
  this.vName = name;
}

public void start() {
  new MyThread().start();
}

private class MyThread extends Thread {
  public void run() {
    System.out.println(name.get());
    System.out.println(vName);
  }
}

final doesn't have nothing with multithreading, but you should put final if your fild shouldn't be changed and is initialized in constructor of class. This means that fild can't be changed latter.

因为String是不可变的,你声明字段final,所有线程在字段赋值后访问它,然后肯定不会有并发问题,因为该字段仅用于Read操作,与使用StringBuilder的情况相反。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM