top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are few multi-threading best practices which one should follow while programming in Java?

+4 votes
457 views
What are few multi-threading best practices which one should follow while programming in Java?
posted Apr 23, 2015 by Shyam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

I believe that you must follow certain best practices while writing concurrent code which helps in performance, debugging and maintenance. Following are three best practices, I think an average Java programmer should follow:

Always give meaningful name to your thread

This goes a long way to find a bug or trace an execution in concurrent code. OrderProcessor, QuoteProcessor or TradeProcessor is much better than Thread-1. Thread-2 and Thread-3. Name should say about task done by that thread. All major framework and even JDK follow this best practice.

Avoid locking or Reduce scope of Synchronization

Locking is costly and context switching is even more costlier. Try to avoid synchronization and locking as much as possible and at bare minimum, you should reduce critical section. That’s why I prefer synchronized block over synchronized method, because it gives you absolute control on scope of locking.

Prefer Synchronizers over wait and notify

Synchronizers like CountDownLatch, Semaphore, CyclicBarrier or Exchanger simplifies coding. It’s very difficult to implement complex control flow right using wait and notify. Secondly, these classes are written and maintained by best in business and there is good chance that they are optimized or replaced by better performance code in subsequent JDK releases. By using higher level synchronization utilities, you automatically get all these benefits.

Prefer Concurrent Collection over Synchronized Collection

This is another simple best practice which is easy to follow but reap good benefits. Concurrent collection are more scalable than their synchronized counterpart, that’s why its better to use them while writing concurrent code. So next time if you need map, think about ConcurrentHashMap before thinking Hashtable

answer Apr 24, 2015 by Karthick.c
...