• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread safty in static method  RSS feed

 
rupesh patil
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the static method handels thread safty. As per the explaination read till this time like each thread has its own stack and memory allocated to it.
Even method has single copy of code

How in the following code Object of stringBuffer is actually maintained by java.
If there is single copy of code. When I am creating the instance of StringBuffer for every thread new instance of StringBuffer is get created but the reference variable is same.

How these tow reference copy of the variable is maintained.

Please any one can answer my querry....?


public class Running extends Thread {

String value;


public Running(String value){
this.value = value ;
}

public void run(){

callstaticMethod(this.value);
// System.out.println("value");
}

public static void callstaticMethod(String value){
StringBuffer object = new StringBuffer(value);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
object.append("2" + value);
System.out.println(object.toString());

}
public static void main(String[] args ){
Thread t1 = new Running("First");
Thread t2 = new Running("Second");

t1.start();
t2.start();

try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How in the following code Object of stringBuffer is actually maintained by java.


Bytecode do *not* get duplicated. There is only one copy of the byte code for a method -- for static or non-static methods -- regardless of how static methods are used, or how many instances are created, or even how many other classes extend it.


If there is single copy of code. When I am creating the instance of StringBuffer for every thread new instance of StringBuffer is get created but the reference variable is same.


The "copy of code" doesn't determine the scope. The scope of the local variable is dependent on the thread (hence, related to the stack) and the actual method call.

How these tow reference copy of the variable is maintained.


The actual string buffer object is created (on the heap) and the only reference to it, is held in the current stack frame for the method.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!