Monday, March 30, 2015

How to Use Locks in Multi-threaded Java Program

How to Use Locks in Multi-threaded Java Program

Many Java programmers confused themselves like hell while writing multi-threaded Java programs e.g. where to synchronized? Which Lock to use? What Lock to use etc. I often receive request to explain about how to use Locks in Java, so I thought to write a simple Java program, which is multi-threaded and uses rather new Lock interface. Remember Lock is your tool to guard shared resource which can be anything e.g. database, File system, a Prime number Generator or a Message processor. Before using Locks in Java program, it’s also better to learn some basics. Lock is an interface from java.util.concurrent package. It was introduced in JDK 1.5 release as an alternative of synchronized keyword. If you have never written any multi-threading program, then I suggest first start with synchronized keyword because it’s easier to use them. Once you are familiar with working of multi-threading program e.g. How threads share data, how inter thread communication works, you can start with Lock facility. As I told you Lock is an interface, so we cannot use it directly, instead we need to use its implementation class. Thankfully Java comes with two implementation of java.util.concurrent.locks.Lock interface, ReentrantLock and ReentrantReadWriteLock, later provides two more inner implementation known as ReentrantReadWriteLock.ReadLock and ReentrantReadWriteLock.WriteLock. For our simple multi-threaded Java program's purpose ReentrantLock is enough.

2 comments:

  1. Did you know that that you can generate dollars by locking premium pages of your blog / site?
    Simply join AdscendMedia and embed their content locking tool.

    ReplyDelete
  2. Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up! life insurance over 50

    ReplyDelete