• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Threads and instance variables

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm confused about what happens with instance variables in a multi- threaded class. If I have a class such as



And I instantiate and start two instanced of this class




Is there a situation where both threads see the value of myID as 2?

I tried to write a test program to demonstrate this to myself but myId is always correct. I'm wondering if I completely misunderstand the relationship of instance variables to multiple threads.

Thanks for any guidance on this issue,
jefsmith


 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Threads are no different to any other objects. If you declare an instance variable, then the value of that variable belongs to a specific object. Create two objects, you get two separate values.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, I strongly recommend implementing Runnable instead of extending Thread. You're not creating a specialized kind of Thread; you're creating a task to be run in its own thread.

As for your question, it's unclear what you're asking, but I'll try taking a guess at the general idea.

As Matthew pointed out, an object is an object and an instance variable is an instance variable, and there's nothing special about an instance variable in a Thread object (or in an object that implements Runnable).

The main context in which threads and instance variables interact in a way that needs study and examples, and what I'm guessing you're looking to play around with, is when multiple threads are accessing some variable one the same object. (In your code, you had two separate objects. Those objects happened to be Thread objects, which may have confused the issue for you.)

So you start T1, and it has a reference to some object, and you start T2, and it has a reference to the same object. The place where undesirable behavior may occur is if you're not properly using synchronization, or volatile, or the classes in java.util.concurrent.* and at least one of those threads is writing to the object and at least one is reading from it. You may get improper results, invalid or intermediate states, or a write by one thread not being seen by a read by another thread. There's a whole lot of explanation of how that stuff works and examples of handling different cases--too much to go into here--but if you start with that in mind--2 or more threads accessing instance variables in the same object--you should be heading down the right path toward what you're trying to experiment with.
 
Jef Smith
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Matthew,
Could you elaborate on how this works? I thought that when you did something like:



That you are actually starting two threads on the SAME instance. If t1 and t2 are different instances, is the benefit of multi-threading just that these two instances can work independently but do a similar job because they are the same class?

Sorry if these questions are really dumb but I'm finding the concept of threads very confusing.

jef
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, you've created two objects there, both of which are threads. They don't share anything.

Perhaps what you're thinking of is related to what Jeff was talking about - you should separate the task that you want completing from the threads that are running it. That way, you can either choose to share the task between threads or not.

This is the sort of thing I'm talking about:
Then the following will have two threads sharing the same Worker object:
Whereas this has two threads which are indepedent because they have separate Worker objects:

In both cases the threads can do a similar job, because they are working on an instance of the same class. The question is, do the threads need to interact by sharing state? If they do, then they'd could share a Runnable object - but then you have to make sure they don't stop each other working correctly. If you can make your threads not need to interact with each other, life is easier.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jef Smith wrote:Matthew,
Could you elaborate on how this works? I thought that when you did something like:



That you are actually starting two threads on the SAME instance.



No. You're not starting any threads. You're just creating objects. You have created two distinct WT objects.

If t1 and t2 are different instances, is the benefit of multi-threading just that these two instances can work independently but do a similar job because they are the same class?



Yes and no. You're probably confusing yourself because you're extending Thread. Forget about that. You start a thread of execution (lower case "t") via a Thread object (uppercase "T"). Having a separate thread of execution means that thread can perform its task in parallel to and independently of other threads. It's the Runnable that defines exactly what that task is, via the steps in its run() method. (Thread implements Runnable, and you can just extend Thread and override its run() method, but that's bad design, and I think it contributes to the kind of confusion you're having now.)

Note that it's threads (lowercase "t") that work independently, not "instances". For each independent thread of execution, we need a Thread object. Sometimes we can talk about them as if they're the same thing, but it's worth understanding the difference.

Sorry if these questions are really dumb but I'm finding the concept of threads very confusing.



Multithreading is a complex topic, and it takes an adjustment to your way of thinking. It's perfectly normal for it to take some time to grok it all.

At a high (and very rough) level, you can look at it like this: Think of each thread running inside your program as similar to how you have multiple programs running on your computer. You can start your web browser, tell it to download a huge file, and while that's in progress, fire up chat client and converse with your buddy. Those two tasks run independently of each other, and in parallel. Roughly speaking, those programs are to your computer as multiple threads are to a single program.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matthew Brown wrote: The question is, do the threads need to interact by sharing state? If they do, then they'd could share a Runnable object - but then you have to make sure they don't stop each other working correctly. If you can make your threads not need to interact with each other, life is easier.



Or, each my have its own Runnable object, but those Runnables may operate on some of the same objects. In my experience, this is the more common case, and in general, I feel it's a more appropriate division of responsibility.
 
Ranch Hand
Posts: 233
1
Eclipse IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sorry if these questions are really dumb but I'm finding the concept of threads very confusing.



Hi Jef, I am also learning Java like milliothers. No problemo. Trust me, learn the theory basics, immediately execute programs. Gradually, you will muster.
As of your question, Using new keyword creates a new instance/ object each time, and in this new instance/ object, the instance (non-static) variables get memory.
You have used new keyword twice, so first thread (its name is Thread-0, find out why if you don't know) has myId = 1, and the second Thread (Thread-1) has myId = 2.
 
Jef Smith
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Matthew and Jeff,
Thanks for the great answers. I think my confusion came from thinking that:

was actually:


So, in the second case, if Worker has the method setMyId() the value of myId will be the same
for both t1 and t2 even of the method was only called on t2. Whereas in the first case nothing
done to t2 will have any effect on t1?

jef

p.s. Radjeep, thanks for the words of encouragement
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jef Smith wrote:Matthew and Jeff,
Thanks for the great answers. I think my confusion came from thinking that:

was actually:


So, in the second case, if Worker has the method setMyId() the value of myId will be the same
for both t1 and t2 even of the method was only called on t2.



It was only called by thread t2, on the Worker object pointed to by both Thread objects. Note that this has nothing to do with multiple threads. If you instead had:


Then any access to worker by any thread through f1 will give the same results as any access to worker by any thread through f2.

On the other hand, if you had


Then if any thread calls f1.getWorker().setId(1); then any other thread accessing f1's worker will see the id of 1. That is, the values of the member variables are bound to the object that defines them, to the thread. Your comments above seem to be conflating the Thread object with its corresponding thread of execution.


Whereas in the first case nothing
done to t2 will have any effect on t1?



Right. Just like any other time you have two separate objects, and again, not specific to threads. These are the Thread objects we're talking about, whose member variables are just like any other object's member variables. We're not talking about threads of execution.
 
Jef Smith
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I just wanted to thank Jeff and Matthew again for taking the time to walk me through this threading business. I understand things a lot better now because the explanations and example were just great.

Thanks again, JavaRanch forums are a wonderful resource.

jefsmith
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome! Glad to be of help!
 
Wanna see my flashlight? How about this tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic