What is the difference between Synchronizing mehtod &
Synchronizing block?

Answer Posted / kanu butani

The 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.

Is This Answer Correct ?    0 Yes 3 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Can you tell me range of byte?

753


Give some features of interface?

804


What is callable java?

743


What is the difference between interface & abstract class?

798


What is the difference between JDBC 1.0 and JDBC 2.0?

2912


Can inner class have constructor?

747


Why do we need autoboxing in java?

757


Does java support multiple inheritance or not?

808


What do you mean by an object in java?

869


how to create daemon thread in java?

828


What is a jit compiler?

869


How many bits are used to represent unicode, ascii, utf-16, and utf-8 characters?

822


What is the use of string and stringbuffer?

758


Is 0 an irrational number?

813


Does windows 10 need java?

800