I'm new to Java and is struggling with some of its concepts. I saw this statement at Java Tutorial Oracle: "Threads communicate primarily by sharing access to fields and the objects reference fields refer to." Could someone please explain it to me what do they mean by "the objects reference fields refer to"? What is the "object reference"? Thanks in advance!!
-
See "[Using Objects](https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html)". – Andreas Dec 22 '15 at 02:04
-
Possible duplicate of [What is Object Reference Variable?](http://stackoverflow.com/questions/16504084/what-is-object-reference-variable) – Andreas Dec 22 '15 at 02:06
2 Answers
A very basic answer is that when a thread has access to an object other threads should not be able to access the same object at the same time and they should not be able to access the objects references either.
In regard to the object reference, as quoted from What is Object Reference Variable? linked above.
A reference is what is used to describe the pointer to the memory location where the Object resides.
Threads should share time using objects and object references between them, make sure you avoid deadlocking objects with threads that will never release an object for another thread to use.
Here's the quote:
Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
A reference is a pointer to an object in memory. Sharing a reference means that a reference belonging to an object being executed by one thread gets copied into an object being accessed in another thread.
Let's say we have a queue, where some threads are putting things in the queue and other threads are taking things from the queue. When a thread puts an object in the queue, it starts out with the thread (called the producer) referencing the object, then after it's put in the queue the queue is referencing it. Then some other thread that is consuming items from the queue comes along and takes the object from the queue and now the consumer thread is referencing it. So the object reference gets passed between threads.
The tutorial is talking about the measures that need to be taken in order for the reference to be passed reliably from one thread to another. Making changes to objects visible across threads is too expensive to do all the time, when you want to publish changes to another thread there are specific things you have to do, such as locking or using the volatile keyword.

- 1
- 1

- 94,330
- 19
- 181
- 276