- can be smaller than a method (can be inside a unsynchronized method), allows holding locks for a smaller time and i.e. to protect only a single field assignment .
- allow to synchronize on other objects than this
Example :
class separateGroups {
private double aVal = 0.0;
private double bVal = 1.1;
protected Object lockA = new Object();
protected Object lockB = new Object();
public double getA(){
synchronized (lockA){
return aVal;
}
}
public void setA(double val){
synchronized (lockA){
aVal=val;
}
}
public double getB(){
synchronized (lockB){
return bVal;
}
}
public void setB(double val){
synchronized (lockB){
bVal=val;
}
}
public void reset(){
synchronized (lockA){
synchronized (lockB){
aVal=bval=0.0;
}
}
}
the reset method changes both values therefore it acquires both locks.
Thursday, March 26, 2009
Static synchronized Method in java
Static synchronized methods synchronize on the class object (this.getClass()) of the class.
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class)
{
}
In JAVA we hav a class named CLASS. JVM creates an object of this class every time a class is loaded thus a class itself has a monitor object so when we make a method static synchonized, thread takes the ownership of this object which JVM creates..this is how a method can be declared as both static and synchronized
Static Methods can be declared Synchronized
- Associated with every class is a Class object (there is a class Class)
- Static synchronized methods acquire the lock of the Class obj for their class
- Two threads can not execute static synchronized methods of the same class at the same time
- If static data is shared between two threads, it must be protected using static synchronized methods
Acquiring the Class object lock in a static synchronized method, has no effect on any object of that class.
It is possible to invoke synchronized methods of an object while another thread holds the Class object lock in a static synchronized method.
Only the other static synchronized methods are blocked.
Synchronized Statements
Enables :
- executing code that acquires the lock of any object, not just the current object
- acquiring the lock for duration of less than a whole method
The synchronized statement has two parts:
- an object whose lock is to be acquired
- a statement to be executed when this lock is acquired
General Form :
synchronized (expr) {
statements
}
expr – is an object reference.
When the lock is obtained – the statements in the block are executed
At the end of the block – the lock is released
A synchronized statement block with a this reference is equivalent to a synchronized method in this object:
synchronized ( this ){
statements
}
Example : make all array elements positive:
public static void abs ( int[] arr ){
synchronized ( arr ) {
for (int i = 0;i < arr.length;i++){
if(arr[i]<0) arr[i] *= -1;
}
}
}
Because arrays objects do not have synchronized methods this is the only way to protect them when they can be shared.
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class)
{
}
In JAVA we hav a class named CLASS. JVM creates an object of this class every time a class is loaded thus a class itself has a monitor object so when we make a method static synchonized, thread takes the ownership of this object which JVM creates..this is how a method can be declared as both static and synchronized
Static Methods can be declared Synchronized
- Associated with every class is a Class object (there is a class Class)
- Static synchronized methods acquire the lock of the Class obj for their class
- Two threads can not execute static synchronized methods of the same class at the same time
- If static data is shared between two threads, it must be protected using static synchronized methods
Acquiring the Class object lock in a static synchronized method, has no effect on any object of that class.
It is possible to invoke synchronized methods of an object while another thread holds the Class object lock in a static synchronized method.
Only the other static synchronized methods are blocked.
Synchronized Statements
Enables :
- executing code that acquires the lock of any object, not just the current object
- acquiring the lock for duration of less than a whole method
The synchronized statement has two parts:
- an object whose lock is to be acquired
- a statement to be executed when this lock is acquired
General Form :
synchronized (expr) {
statements
}
expr – is an object reference.
When the lock is obtained – the statements in the block are executed
At the end of the block – the lock is released
A synchronized statement block with a this reference is equivalent to a synchronized method in this object:
synchronized ( this ){
statements
}
Example : make all array elements positive:
public static void abs ( int[] arr ){
synchronized ( arr ) {
for (int i = 0;i < arr.length;i++){
if(arr[i]<0) arr[i] *= -1;
}
}
}
Because arrays objects do not have synchronized methods this is the only way to protect them when they can be shared.
Wednesday, March 25, 2009
Different Ways of creating Objects in Java.
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99 of objects are created in this way.
MyObject object new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object (MyObject) Class.forName( subin.rnd.MyObject ).newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject new MyObject();MyObject object anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream new ObjectInputStream(anInputStream );MyObject object (MyObject) inStream.readObject();
5. Using class loader
one more is through creation of object using classloader
like
this.getClass().getClassLoader().loadClass( com.amar.myobject ).newInstance();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.
This is the most common way to create an object in java. I read somewhere that almost 99 of objects are created in this way.
MyObject object new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object (MyObject) Class.forName( subin.rnd.MyObject ).newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject new MyObject();MyObject object anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream new ObjectInputStream(anInputStream );MyObject object (MyObject) inStream.readObject();
5. Using class loader
one more is through creation of object using classloader
like
this.getClass().getClassLoader().loadClass( com.amar.myobject ).newInstance();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.
What is Interthread communication in Java?
Interthread communication
In Java for interthread communication there are methods provided in Object class called wait, notify, notifyall. Since they are in Object class they are available to all the classes in java. These methods should always be called from inside a synchronized block or else there will be an exception, IllegalMonitorException. When a thread is waiting to get a lock on an object it calls wait on that object .
There are three ways in which Threads communicate with each other :
wait: It tells the calling thread to give up the monitor until some other thread enters the same monitor an calls Notify or Notifyall.
notify: It wakes up the first thread that called Wait() on the same object.
NotifyAll: It allows all the threads that called Wait() on the same object.The thread having the highest priority will run first.
Example
class Shared {
int num=0;
boolean value = false;
synchronized int get() {
if (value==false)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num) {
if (value==true)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.num=num;
System.out.println("Produce: " + num);
value=true;
notify();
}
}
class Producer extends Thread {
Shared s;
Producer(Shared s) {
this.s=s;
this.start();
}
public void run() {
int i=0;
s.put(++i);
}
}
class Consumer extends Thread{
Shared s;
Consumer(Shared s) {
this.s=s;
this.start();
}
public void run() {
s.get();
}
}
public class InterThread{
public static void main(String[] args)
{
Shared s=new Shared();
new Producer(s);
new Consumer(s);
}
}
In Java for interthread communication there are methods provided in Object class called wait, notify, notifyall. Since they are in Object class they are available to all the classes in java. These methods should always be called from inside a synchronized block or else there will be an exception, IllegalMonitorException. When a thread is waiting to get a lock on an object it calls wait on that object .
There are three ways in which Threads communicate with each other :
wait: It tells the calling thread to give up the monitor until some other thread enters the same monitor an calls Notify or Notifyall.
notify: It wakes up the first thread that called Wait() on the same object.
NotifyAll: It allows all the threads that called Wait() on the same object.The thread having the highest priority will run first.
Example
class Shared {
int num=0;
boolean value = false;
synchronized int get() {
if (value==false)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num) {
if (value==true)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.num=num;
System.out.println("Produce: " + num);
value=true;
notify();
}
}
class Producer extends Thread {
Shared s;
Producer(Shared s) {
this.s=s;
this.start();
}
public void run() {
int i=0;
s.put(++i);
}
}
class Consumer extends Thread{
Shared s;
Consumer(Shared s) {
this.s=s;
this.start();
}
public void run() {
s.get();
}
}
public class InterThread{
public static void main(String[] args)
{
Shared s=new Shared();
new Producer(s);
new Consumer(s);
}
}
What is the difference between checked and unchecked exception ?
Checked Exceptions are the one for which a handling needs to be provided in the application i.e a try catch block is required or a throws clause is required or else the compiler will not allow to compile the file.These are exceptions for which some alternative corrective measure can be taken and the program can continue executing. Example IOException or FileNotFoundException.
Unchecked exceptions are Runtime Exceptions and errors like NullPOinterException and ClassCastException which normally occur due to programming errors and should not happen, if they do it is a bug or a wrong code.These exception need not be catched since they need to be fixed if at all they come up.
Unchecked exceptions are Runtime Exceptions and errors like NullPOinterException and ClassCastException which normally occur due to programming errors and should not happen, if they do it is a bug or a wrong code.These exception need not be catched since they need to be fixed if at all they come up.
Subscribe to:
Comments (Atom)