Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices or principles for sharing objects between threads in Java

I tried to search but couldn't find exact answer I was looking for hence putting up a new question.

If you wish to share any mutable object(s) between multiple threads, are there any best practices/principles/guidelines to do it ?

Or will it simply vary case by case ?

like image 577
handiekarm Avatar asked Feb 28 '17 12:02

handiekarm


People also ask

How do you share objects between threads?

There are many ways to share same Object between multiple threads. You can use a BlockingQueue to pass an Object from one thread to another thread. You can also use Exchanger class for this purpose. An Exchanger is a bidirectional form of a SynchronousQueue in Java.

How is data shared between two threads in Java?

As a result, each thread receives its own copy of those variables. In contrast, threads can share class fields and instance fields because those variables do not allocate on a thread's method-call stack. Instead, they allocate in shared heap memory—as part of classes (class fields) or objects (instance fields).

How do you communicate between two threads?

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: wait() notify() notifyAll()


3 Answers

Sharing mutable objects between threads is risky.

The safest way is to make the objects immutable, you can then share them freely.

If they must be mutable then each of the objects each needs to ensure their own thread safety using the usual methods to do so. (synchronized, AtomicX classes, etc).

The ways to protect the individual objects will vary a lot though depending on how you are using them and what you are using them for.

like image 155
Tim B Avatar answered Oct 14 '22 04:10

Tim B


In java, you should synchronize any method that changes/reads the state of shared object, it is the easiest way.

other strategies are:

  • make use of thread safe classes (ConcurrentHashMap) for example
  • use of locks
  • use of volatile keyword, to avoid stale objects (sometimes could be used as lightweight synchronizer)

they key is sync your updates/reads to guarantee consistent state, the way you do it, could vary a lot.

like image 20
Paulo Ricardo Almeida Avatar answered Oct 14 '22 06:10

Paulo Ricardo Almeida


The problems with sharing objects between threads are caused by having the two threads access the same data structure at the same time, with one mutating the structure while the other depends on the structure to be complete, correct or stable. Which of these cause the problem is important and should be considered when choosing the strategy.

These are the strategies I use.

  1. Use immutable objects as much as possible.

This removes the issue of changing the data structure altogether. There are however a lot of useful patterns that can not be written using this approach. Also unless you are using a language/api which promotes immutability it can be inefficient. Adding a entry to a Scala list is much faster than making a copy of a Java list and adding a entry to the copy.

  1. Use the synchronize keyword.

This ensures that only one thread at a time is allowed to change the object. It is important to choose which object to synchronize on. Changing a part of a structure might put the hole structure in an illegal state until another change is made. Also synchronize removes many of the benefits of going multithreaded in the first place.

  1. The Actor model.

The actor model organizes the world in actors sending immutable messages to each other. Each actor only has one thread at once. The actor can contain the mutability. There are platforms, like Akka, which provide the fundamentals for this approach.

  1. Use the atomic classes. (java.util.concurrent.atomic)

These gems have methods like incrementAndGet. They can be used to achieve many of the effects of synchronized without the overhead.

  1. Use concurrent data structures.

The Java api contains concurrent data structures created for this purpose.

  1. Risk doing stuff twice.

When designing a cache it is often a good idea to risk doing the work twice instead of using synchronize. Say you have a cache of compiled expressions from a dsl. If an expression is compiled twice that is ok as long as it eventually ends up in the cache. By allowing doing some extra work during initialization you may not need to use the synchronize keyword during cache access.

like image 21
Espen Brekke Avatar answered Oct 14 '22 05:10

Espen Brekke