0

I was reading about synchronization concept in java and came across synchronized statements .

I want to know , why do we pass arguments to it , though it appears like static block(it's just an example) , and the arguments passed do not have any data type specified with it .

Example :

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}

If any one knows about it , please explain .

1 Answers1

-2

In a multithreaded application when you want the states of an object to be read and written in a synchronized way by multiple threads then you use synchronized keyword.

The mechanism that Java uses to support synchronization is the monitor. Each object has a monitor associated with it. Synchronized block needs an object to work with, so that the threads in competition can compete and the winner thread can aquire the monitor.

Each non static method in java has an implicit this object upon which the particular method is invoked. If you use synchronized keyword in the method signature then it means you are depending upon the implicit this object for synchronization. If you wish to depend upon any other object then you can use the synchronized blocks and use the object reference in it.

Remember there may be various synchronized blocks but the blocks with synchronized block on same object will only gurantee the proper syncronized execution with respect to each other. Synchronized Blocks which have references of different objects do not force threads to work in synchronized way.

Thus Suppose when there is some threadA which modifies some states of an objectX and works with synchronized block with ObjectA. There may be another piece of code may be in some other class where some other threadB may be reading the states of the same objectX. Now threadB should also do the reading within a synchronized block with ObjectA so that states of objectX are read properly.

nits.kk
  • 5,204
  • 4
  • 33
  • 55
  • reason for downvote, I will be glad to correct myself. – nits.kk May 01 '17 at 15:20
  • It wasn't me ... but your answer doesn't really answer the question. The OP didn't ask for a tutorial on `synchronized`. The real answer is very simple: 1) `lock1` and `lock2` are the mutexes that you are locking, and 2) they are not arguments because this is not a method call. – Stephen C May 02 '17 at 03:23
  • @nits.kk it wasn't me but some one has marked my question as duplicate . May be he has downvote your answer. – Sidhant Bansal May 02 '17 at 07:25