Friday, November 30, 2012

Java-This


Definition for java this keyword:
Java this keyword is used to refer the current instance of the method on which it is used.

Following are the ways to use java this

1) To specifically denote that the instance variable is used instead of static or local variable.That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the “this” denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
2) Java This is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
Java This invokes the constructor of the same java class which has two parameters.
3) Java This is used to pass the current java instance as parameter
obj.itIsMe(this);
4) Similar to the above, java this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to theinner class and not the outer instance.
5) Java This can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by, Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, java this is associated with its instance and this will not work in static methods.

http://stackoverflow.com/questions/4394976/what-is-the-difference-between-synchronizedthis-and-synchronized-method
Question:

Lets say we have these 2 sample code :
public synchronized void getSomething(){
     this.hello = "hello World";
}
and this one
public void getSomething(){
   synchronized(this){
     this.hello = "hello World";
   }
}
So some one can tell me what's the difference now?
Answer:




In the code presented, there is no functional difference. There may be a very small performancedifference:
At the bytecode level, the synchronized method advertises its need for synchronization as a bit set in the method's access flag. The JVM looks for this bit flag and synchronizes appropriately.
The synchronized block implements its synchronization through a number of bytecode operations stored in the class file's definition of the method.
So the synchronized method should execute ever so slightly faster and take up less space in terms of bytecode.
Again, the two are, by specification, functionally identical.
I'm guessing that the performance difference is probably negligible for most applications.





No comments:

Post a Comment