Many Java programmers confused themselves similar hell land writing multi-threaded Java programs e.g. where to synchronized? Which Lock to use? What Lock to usage etc. I ofttimes have asking to explicate nearly how to usage Locks inwards Java, thus I idea to write a uncomplicated Java program, which is multi-threaded as well as uses rather novel Lock interface. Remember Lock is your tool to guard shared resources which tin sack live anything e.g. database, File system, a Prime number Generator or a Message processor. Before using Locks inwards Java program, it’s also ameliorate to larn approximately basics. Lock is an interface from java.util.concurrent package. It was introduced inwards JDK 1.5 unloose every bit an choice of synchronized keyword. If you lot have got never written whatever multi-threading program, as well as then I propose showtime start amongst synchronized keyword because it’s easier to usage them. Once you lot are familiar amongst working of multi-threading programme e.g. How threads part data, how inter thread communication works, you lot tin sack start amongst Lock facility. As I told you lot Lock is an interface, thus nosotros cannot usage it directly, instead nosotros demand to usage its implementation class. Thankfully Java comes amongst 2 implementation of java.util.concurrent.locks.Lock interface, ReentrantLock as well as ReentrantReadWriteLock, after provides 2 to a greater extent than inner implementation known every bit ReentrantReadWriteLock.ReadLock as well as ReentrantReadWriteLock.WriteLock. For our uncomplicated multi-threaded Java program's role ReentrantLock is enough.
Here is the idiom to usage Locks inwards Java :
For illustration nosotros tin sack usage Lock to protect a counter, whose sole role is to render a count incremented yesteryear one, when anyone calls its getCount() method. If nosotros don't protect them yesteryear parallel access of thread, as well as then it’s possible that 2 thread receives same count, which is against the program's policies.
Now, coming dorsum to semantics, nosotros have got used lock() method to acquire lock as well as unlock() method to unloose lock.
Always retrieve to unloose lock inwards lastly block, because every object has exclusively 1 lock as well as if a thread doesn't unloose it as well as then no 1 tin sack acquire it, which may effect inwards your programme hung or threads going into deadlock.
That's why I said that synchronized keyword is simpler than lock, because Java itself brand certain that lock acquired yesteryear thread yesteryear entering into synchronized block or method is released every bit shortly every bit it came out of the block or method. This happens fifty-fifty if thread came out yesteryear throwing exception, this is also nosotros have got unlock code inwards lastly block, to brand certain it run fifty-fifty if endeavour block throws exception or not.
In adjacent department nosotros volition run across illustration of our multi-threaded Java program, which uses Lock to protect shared Counter.
You tin sack fifty-fifty seat a long loop within Runnable's run() method to telephone weep upwards getCount() numerous time, if you lot run across a duplicate way at that spot is a occupation amongst your code, but without whatever duplicate way it’s working fine.
1) Instead of sharing lock they furnish dissimilar locks to each thread. This ofttimes happens to them unknowingly because they normally seat the lock as well as guarded block within Runnable, as well as they exceed 2 different instances of Runnable to 2 dissimilar threads e.g. where SimpleLock is a Runnable, every bit shown below :
Since hither myLock is instance variable, each instance of SimpleLock has their ain myLock instance, which way firstThread as well as secondThread are using dissimilar lock as well as they tin sack run protected code simultaneously.
2) Second error Java beginners do is forget to telephone weep upwards unlock() method, but similar inwards a higher house example. without calling unlock() method, Thread volition non unloose its lock as well as approximately other thread waiting for that lock volition never acquire that. Nothing volition occur inwards this examine program, but 1 time you lot write this sort of code inwards existent application, you lot volition run across nasty issues similar deadlock, starvation as well as information corruption. By the way Lock interface also offers several advantages over synchronized keyword, banking concern tally here to larn more.
That's all nearly how to usage Locks inwards multi-threaded Java programme for synchronization. Let me know if you lot have got whatever hard agreement Locks inwards Java or anything related to multi-threading, Will live glad to assist you. For farther reading, you lot tin sack explore Java documentation of Lock interface as well as it's diverse implementation classes
Further Learning
Multithreading as well as Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency as well as Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course yesteryear Heinz Kabutz
Here is the idiom to usage Locks inwards Java :
You tin sack run across that Lock is used to protect a resource, thus that exclusively 1 thread tin sack access it at a time. Why nosotros do that? to brand certain our application deport properly.Lock l = ...; l.lock(); try { // access the resources protected yesteryear this lock } finally { l.unlock(); }
For illustration nosotros tin sack usage Lock to protect a counter, whose sole role is to render a count incremented yesteryear one, when anyone calls its getCount() method. If nosotros don't protect them yesteryear parallel access of thread, as well as then it’s possible that 2 thread receives same count, which is against the program's policies.
Now, coming dorsum to semantics, nosotros have got used lock() method to acquire lock as well as unlock() method to unloose lock.
Always retrieve to unloose lock inwards lastly block, because every object has exclusively 1 lock as well as if a thread doesn't unloose it as well as then no 1 tin sack acquire it, which may effect inwards your programme hung or threads going into deadlock.
That's why I said that synchronized keyword is simpler than lock, because Java itself brand certain that lock acquired yesteryear thread yesteryear entering into synchronized block or method is released every bit shortly every bit it came out of the block or method. This happens fifty-fifty if thread came out yesteryear throwing exception, this is also nosotros have got unlock code inwards lastly block, to brand certain it run fifty-fifty if endeavour block throws exception or not.
In adjacent department nosotros volition run across illustration of our multi-threaded Java program, which uses Lock to protect shared Counter.
Java Lock as well as ReentrantLock Example
Here is a sample Java program, which uses both Lock as well as ReentrantLock to protect a shared resource. In our instance it’s an object, a counter's object. Invariant of Counter shape is to render a count incremented yesteryear 1 each fourth dimension somebody calls getCount() method. Here for testing 3 threads volition telephone weep upwards getCount() method simultaneously but guard provided yesteryear Lock volition forestall shared counter. As an exercise you lot tin sack also implement same shape using synchronized keyword. Here is consummate code :import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * Java Program to exhibit how to usage Locks inwards multi-threading * e.g. ReentrantLock, ReentrantReadWriteLock etc. * * @author Javin Paul */ public class LockDemo { public static void main(String args[]) { // Let's do a counter as well as shared it betwixt 3 threads // Since Counter needs a lock to protect its getCount() method // nosotros are giving it a ReentrantLock. final Counter myCounter = new Counter(new ReentrantLock()); // Task to live executed yesteryear each thread Runnable r = new Runnable() { @Override public void run() { System.out.printf("Count at thread %s is %d %n", Thread.currentThread().getName(), myCounter.getCount()); } }; // Creating 3 threads Thread t1 = new Thread(r, "T1"); Thread t2 = new Thread(r, "T2"); Thread t3 = new Thread(r, "T3"); //starting all threads t1.start(); t2.start(); t3.start(); } }
class Counter { private Lock lock; // Lock to protect our counter private int count; // Integer to concord count public Counter(Lock myLock) { this.lock = myLock; } public final int getCount() { lock.lock(); try { count++; return count; } finally { lock.unlock(); } } } Output: Count at thread T1 is 1 Count at thread T2 is 2 Count at thread T3 is 3
You tin sack fifty-fifty seat a long loop within Runnable's run() method to telephone weep upwards getCount() numerous time, if you lot run across a duplicate way at that spot is a occupation amongst your code, but without whatever duplicate way it’s working fine.
Common Mistakes made yesteryear beginners land using Locks inwards Java
Here are approximately of the mutual mistakes I have got observed yesteryear looking at Java beginners lock related code :1) Instead of sharing lock they furnish dissimilar locks to each thread. This ofttimes happens to them unknowingly because they normally seat the lock as well as guarded block within Runnable, as well as they exceed 2 different instances of Runnable to 2 dissimilar threads e.g. where SimpleLock is a Runnable, every bit shown below :
Thread firstThread = new Thread(new SimpleLock()); Thread secondThread = new Thread(new SimpleLock()); class SimpleLock implements Runnable { private Lock myLock = new ReentrantLock(); public void printOutput() { System.out.println("Hello!"); } public void run() { if (myLock.tryLock()) { myLock.lock(); printOutput(); }else System.out.println("The lock is non accessible."); } }
Since hither myLock is instance variable, each instance of SimpleLock has their ain myLock instance, which way firstThread as well as secondThread are using dissimilar lock as well as they tin sack run protected code simultaneously.
2) Second error Java beginners do is forget to telephone weep upwards unlock() method, but similar inwards a higher house example. without calling unlock() method, Thread volition non unloose its lock as well as approximately other thread waiting for that lock volition never acquire that. Nothing volition occur inwards this examine program, but 1 time you lot write this sort of code inwards existent application, you lot volition run across nasty issues similar deadlock, starvation as well as information corruption. By the way Lock interface also offers several advantages over synchronized keyword, banking concern tally here to larn more.
That's all nearly how to usage Locks inwards multi-threaded Java programme for synchronization. Let me know if you lot have got whatever hard agreement Locks inwards Java or anything related to multi-threading, Will live glad to assist you. For farther reading, you lot tin sack explore Java documentation of Lock interface as well as it's diverse implementation classes
Further Learning
Multithreading as well as Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency as well as Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course yesteryear Heinz Kabutz