Habin
Habin

Reputation: 802

How does variable scope affect multithreading race conditions?

Are instance variables also shared just like static variables? Does this mean that race conditions happen due to static and instance variables only?

Upvotes: 0

Views: 1389

Answers (5)

Martin James
Martin James

Reputation: 24847

Are instance variables also shared just like static variables?

No, they are per-object, whereas statics are per-class. You should have no direct issues with data members of thread objects - like any other object, each instance gets its own vars. Similarly, of course, stack-based auto vars.

To get into multithreaded problems with thread-object instance variables and instance members of objects created by thread objects on a per-thread basis, you have to try harder. With statics, it happens naturally:)

Does this mean that race conditions happen due to static and instance variables only?

If you try hard enough, you can screw up almost anything.

Upvotes: 2

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7367

Without specific constructs to create thread-local context, nothing which holds state is thread safe by default. It's not just the instances of Runnable, anything which the code can touch and fails to lock is a potential source for undefined behavior (not just race conditions, there are other unpredictable partial update results which will render your application state equally compromised).

Upvotes: 0

Tim Bender
Tim Bender

Reputation: 20442

Yes instance variables are shared as well, if multiple threads have access to the instance then there may be a need to protect against stale reads or multi-part writes that can corrupt the object's state.

Additionally, accessing external resources such as files on the file system can cause race conditions.

Upvotes: 4

Nir Alfasi
Nir Alfasi

Reputation: 53525

Doesn't matter if the shared resource is a shared object, public instance variables or static content, all of these might cause race-condition (that is, unless the shared resource is immutable ).

Upvotes: 4

kosa
kosa

Reputation: 66637

instance variables of Runnable/Thread object are shared among threads (if multiple threads working on same object) and order or sequence of thread execution is not guaranteed which may lead to inconsistent results.

Upvotes: 2

Related Questions