Hey,

I have been reading Java oracle tutorials. I read this thing.

Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

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++;
        }
    }
}

Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields

Question: Can you please tell what exactly we pass in syncronized parameter. Why do we pass "this" usually? Also, how is "lock1" variable doing stuff for this example? Passing "this" only makes it object level locking? Please clarify this thing confusing me.
Thanks in advance.

What you pass is the object that you are using as a lock. Only one thread can have the lock at any given time. (Every object has an associated monitor and wait and notify methods; these are the fundamental pieces with which thread synchronisation is implemented.)
"this" is the current object, so it gives you object-level locking.
"lock1" is only needed when you use the inc1 method, so only one thread can use that method at a time. Similarly inc2 is synchronised on lock2, so only one thread can use inc2 at a time, BUT one thread can use inc1 while another thread uses inc2 becuase they are locked on different objects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.