Java MultiThreading Best Practices

In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads.Since version 5.0, the Java platform has also included high-level concurrency APIs. Multi threading in java is a process of executing multiple threads simultaneously.

Here I would like to share some java multithreading related best practices here.

  1. If you are using ArrayList in the Multithread application, then you can should make ArrauList as thread safe using below method.

2. BlockingQueue

BlockingQueue provides a rich API of thread-safe adding and removal of items. This is the best practice to add/remove items from the queue. It will be really useful for Producer and Consumer scenarios.

3. Best way to Shutdown the ExecutorService

4. Difference between ConcurrentHashMap and Collections.synchronizedMap(Map)

If you have Map which is to be modified by several threads concurrently then consider below approach.

In this case, you can use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance.

5.  Use Locks

Always use locks when you access mutable shared data, both for reads and writes.

6. Fork/Join

The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

7. Avoid Concurrent Modification Exception in Java Multi thread Applications

If you are using ArrayList then you need to put inside the sync


8. Use Local Variables

Always try to use local variables instead of creating class or instance variables in multi thread applications. And avoid static variables.

9. Use Immutable Classes

Always try to use Immutable class in multi thread applications.

10 .Prefer Synchronized block instead of Synchronized Methods

I hope above points will be really useful and need to consider when you write java multi thread applications.



About mohan

This is Mohan Jayapalan author of TechPages Blog.I am a part time blogger and Currently working for private Software Concern.

© Copyright 2010-2016 · All Rights Reserved · Powered by WordPress ·