Sunday 22 April 2012

Concurrency and thread synchronization in Java

There are various problems while working with multiple threads. One of them is resource access. If both of the threads are trying to access a single resource, chances are that they will wind up. If the resource is shareable, then it might cause glitches in the system. For instance, picture a situation where two threads are trying to print two different files on a printer. It might happen that printer would print one character from one file and another character from another file. This would result in a jumbled up situation. Solution to this is concurrency. It is to make sure that only one thread accesses one resource at a time. Luckily, Java has pretty straight forward solution for this. If you have a method and if you wish to make it such that only one thread can access it at a time, put keyword 'synchronized' in it. So, if I have a method to print a line, it will be:

public synchronized void print(String s)


The word 'synchronized' in the method signature makes sure that only one thread uses that method until it finishes execution. If two threads are trying to access it, the other one will have to wait while the first method finishes its execution.

Watch the video here:

No comments:

Post a Comment