Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

synchronization block

Posted on 2011-04-26
9
Medium Priority
?
302 Views
Last Modified: 2012-08-13
>>When a synchronized block is executed, its object is locked and it cannot be called by any other code until the lock is freed.

synchronized void first();
synchronized void second();
There is more to obtaining the benefits of synchronization than placing the keyword synchronized before a block of code. It must be used in conjunction with code that manages the lock on the synchronized code .




I read above synchronization and explanation from link
http://www.jchq.net/certkey/0703certkey.htm

It is not clear to me in terms why the object is locked when we apply synchronization on individual specific block. Also following is not clear to me
>>>There is more to obtaining the benefits of synchronization than placing the keyword synchronized before a block of code. It must be used in conjunction with code that manages the lock on the synchronized code .


Any ideas, resources, links, sample code highly appreciated. thanks in advance.
0
Comment
Question by:gudii9
  • 4
  • 3
  • 2
9 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 600 total points
ID: 35471563
> It is not clear to me in terms why the object is locked when we apply synchronization on individual specific block.

thats what the syncronizatiomn keyword does.
It says that only one thread at a time can enter that method. So if another thread is already running a synchronized method of that object then it will block and wait for the other thread to finich

http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
0
 
LVL 28

Expert Comment

by:dpearson
ID: 35488421
When synchronize is used on a method like:

synchronized void first();

this means it's holding a lock on the object that has the "first" method.  It's the same as writing:

void first() {
    synchronize(this) {
        ... Do the operation
    }
}

Only one thread can hold a lock on an object at a time, so it stops a second thread from manipulating "this" object at the same time.

>>>There is more to obtaining the benefits of synchronization than placing the keyword synchronized before a block of code. It must be used in conjunction with code that manages the lock on the synchronized code .

The second part of synchronize is that it's important in telling Java how to correctly manage memory on a multiprocessor machine.  Most people are unaware of this, but the synchronize keyword is very important for ensuring that your code runs correctly when there are multiple CPUs in use.  The full explanation is lengthy, but the key concept is to always put in a synchronize statement when two threads and interacting and you want each thread to see the changes made by the other.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 35757611
>>>
synchronized void first();

this means it's holding a lock on the object that has the "first" method.  It's the same as writing:

void first() {
    synchronize(this) {
        ... Do the operation
    }
}


how both are same. What 'this' represents here.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 92

Expert Comment

by:objects
ID: 35757750
yes they r both the same
0
 
LVL 28

Expert Comment

by:dpearson
ID: 35757895
"this" refers to the object whose method you are inside:

String getName() { return "Hello" ; }

void whatIsThis() {
    // "this" refers to the current object
    System.out.println(this.getName()) ;

    synchronized(this) {
        // Two threads won't try to modify "this" object at the same time.
    }
}

Putting the keyword "sychronized" on the method is just shorthand for writing "sychronized(this)" within the method.

I hope that helps.
0
 
LVL 7

Author Comment

by:gudii9
ID: 35889257
>>>he Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods.
To make a method synchronized, simply add the synchronized keyword to its declaration:

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}
If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

Warning:  When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the line
instances.add(this);
to your constructor. But then other threads can use instances to access the object before construction of the object is complete.
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. (An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness, as we'll see later in this lesson.




if you have more synchronized methods as in above example like decrement(), increment() which increase or decrease value of counter will synchronizing each method like this is useful at all?


other thread might decrement while original, first thread might increament same count which could corrupt data right. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 35889267
>>>this" refers to the object whose method you are inside:

String getName() { return "Hello" ; }

void whatIsThis() {
    // "this" refers to the current object
    System.out.println(this.getName()) ;

    synchronized(this) {
        // Two threads won't try to modify "this" object at the same time.
    }
}

Putting the keyword "sychronized" on the method is just shorthand for writing "sychronized(this)" within the method.




so when you say
are we synchronizing entire object not the individual method. please advise
0
 
LVL 28

Accepted Solution

by:
dpearson earned 1400 total points
ID: 35891823

if you have more synchronized methods as in above example like decrement(), increment() which increase or decrease value of counter will synchronizing each method like this is useful at all?

other thread might decrement while original, first thread might increment same count which could corrupt data right. please advise
Synchronize ensures that while one thread is executing code inside "increment" no other thread can be executing code within a method of the same object.  So this ensures no other thread is modifying
private int c = 0;
while one thread is executing any of the other methods.

So in this case the value of c cannot be corrupted.


so when you say
are we synchronizing entire object not the individual method. please advise
Synchronize always means you're making sure two threads cannot execute two methods at the same time.  The question though is which threads are blocked?  If you use:

synchronize void myMethod()
or
void myMethod() {
   synchronize(this) {
   }
}
in both cases it's any methods within this object which are blocked.

You could also write:
public class MyClass {
    public static Object myLock = new Object() ;
}

public class MyOtherClass {
    public void method1() {
       synchronized(MyClass.myLock) {
       }
    }
}

public class MyThirdClass {
    public void method2() {
       synchronized(MyClass.myLock) {
       }
    }
}

now method1 and method2 can't execute at the same time (in 2 different threads) because the object they're synchronized on is "MyClass.myLock".  Rather than "this" object (in each case).

Does that help make it clearer?

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 36005187
i am trying to understand
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month20 days, 16 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question