Search code examples
javamultithreadingthread-safetythread-synchronizationjava-threads

Do multiple threads Using the same object in java make a copy of it?


How do multiple threads in Java handle working with a single object reference passed to them?

Do they make a copy of the object and then use it, or do they use the same one?

Any technical explanation is welcome.

I am unable to comprehend this in the context that if the threads pass some data to the object and go to sleep, while one is asleep another thread uses the same object passes data to it and goes to sleep.

Will the last data overwrite the previous one in the object?


Solution

  • Do they make a copy of the object and then use it, or do they use the same one?

    Both, actually.

    Modern computers are designed according to Symmetric Multiprocessor Architecture (SMP), in which several CPUs compete for access a common memory system. In order to reduce the amount of competition, each processor has its own cache -- a small amount of higher-speed memory -- where it keeps working copies of data that belong in main memory.

    Cacheing happens in the hardware, and the hardware knows nothing about Java objects, so it happens on a byte-by-byte level, not on an object-by-object level.

    At the language level, there is only one copy of an object, but at the hardware level, different threads running on different processors can have their own copies of parts of the object.


    The topic of how different threads running on processors can agree on what some object actually is supposed to look like is called cache coordination.

    Java has strict rules about when and how different threads must coordinate their caches. To learn more about those rules, Google for "Java" and "memory model", or "memory visibility", or "happens before."


    If you don't want to read all of the gory details, the secret is in judicious use of synchronized blocks and synchronized methods. If you only want to remember one rule, remember this: Whatever one thread does to shared objects before it leaves a synchronized block is guaranteed to become visible to other threads after those threads enter a block that is synchronized on the same lock.