Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

java Objects in Multiple Threads

UdithaPereraJun 6 2011 — edited Jun 7 2011
Hi all,

* In a Java based web application, if we check the value of an instance variable, each Thread (Request to the Server) has different values.
* This means each thread has newly created object of a Java class.
* But when we talk about thread safe Java methods, it's recommended that you use "Synchronized" to protect particular steps in a method for thread safety.

So my question is, if each thread create a brand new object, how come different threads invoke the same method? All instance & local variable will be completely new from thread to thread.

Please help to understand this.

Thanks
Uditha

************************************************************************************************
Reference:
Java class that will be invoked by URL
************************************************************************************************

public class HelloObjectWorld
{
private double testVariable;
private static int testConstant;


public HelloObjectWorld()
{
testVariable=Math.random();
System.out.println("############################ I AM AN INSTANCE VARIABLE" + testVariable); // Different for each Thread(Request)
testConstant=121;
System.out.println("############################ I AM A CLASS VARIABLE" + testConstant); // Same for every Thread
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 5 2011
Added on Jun 6 2011
8 comments
610 views