0

So i'm digging into what is complex java for me. I'm looking at multithreading and i was wondering about when you send the same instance of an object to two different threads then assign that instance of the object to two separate instance variables in the two threads. Does java see this as the same instance of the original object? Is that only for Threads?

For example: in my driver

SharedCell share = new SharedCell();
Producer p = new Producer(accessCount, share);
Consumer c = new Consumer(accessCount, share);

and in the threads:

public Producer(int accesses, SharedCell cell) {
    super("Producer");
    this.accesses = accesses;
    this.cell = cell;
}

and

 public Consumer(int accesses, SharedCell cell) {
    super("Consumer");
    this.accesses = accesses;
    this.cell = cell;
}

where the run method in Producer changes the value of a variable in a SharedCell object and the run method in Consumer accesses that variable. these are supposed to switch off doing so.

So does the cell in Consumer and Producer reference the same object that the driver sent them?

1 Answer 1

1

Objects are reference type in java, as in most languages, which means yes in your example both consumer and producer point to the same object in memory. And no, it's not only for threads. Even in single thread they'll have reference to the same object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.