user1982969
user1982969

Reputation: 39

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();
    }

}

Upvotes: 3

Views: 1003

Answers (6)

user166390
user166390

Reputation:

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

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:

Upvotes: 4

shaydel
shaydel

Reputation: 589

since String is immutable and you declare the field final ,with all threads accessing it after the field assignment, then surely there will be no concurrent issues since the field would be used only for Read operation,in contrast to the case where StringBuilder were used.

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

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);
  }
}

Upvotes: 1

imxylz
imxylz

Reputation: 7937

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.

Upvotes: 2

partlov
partlov

Reputation: 14277

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.

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

final variables are immutable, you can not change the value once it is constructed so it does not have concurrency issue.

Upvotes: 3

Related Questions