Java Objects in Multi-threaded Environment

Discussions

Performance and scalability: Java Objects in Multi-threaded Environment

  1. Java Objects in Multi-threaded Environment (13 messages)

    I am a java developer with more than 6 year of experience but still I am frequently haunted by some pretty basic questions about thread safely. I am having trouble with the following

    1. I need to know how the private variables are handled in a multi-threading enviroment. Let me explain..

    Suppose I have a class that has private attributes and public methods. When I create objects of this class (with new XXXX..) , in different threads ( like what happens when you have Value Object pattern and in a web application or when you create instances of classes to store details exclusively for the current user during the execution life time.) , are the instance variables are thread safe? Is it that JVM creates deep copies of instance variables and put in different stacks for different objects and the master copy in heap is not touched ? I am little confused on these ... may be I am getting over causious about thread safety..


    2. How the static objects/methods are handled in a multythreaded environment? Does the JVM maintain locks and only one thread is allowed at a given time? (make it a single threaded case)

    Any help in understanding these issues is greately appreciated.
  2. Hi,
      Answering your first question :
       Thread safety for instance variables come into picture only when the same instance is accessed by many threads. Typical example would be a singleton instance accessed by many threads . In this case to make the instance variables thread safety they should be mutated through synchronized methods . For other cases where every thread creates a new instance there is no question of thread safety .
     
     For your second question the instance owning the static variables and methods is the class instance . Hence to protect the static variables again they should be mutated through static synchronized methods .

    Hope this answers your questions .

    Regards
    Debashish
  3. Hi,  Answering your first question :   Thread safety for instance variables come into picture only when the same instance is accessed by many threads. Typical example would be a singleton instance accessed by many threads . In this case to make the instance variables thread safety they should be mutated through synchronized methods . For other cases where every thread creates a new instance there is no question of thread safety .  For your second question the instance owning the static variables and methods is the class instance . Hence to protect the static variables again they should be mutated through static synchronized methods .Hope this answers your questions .RegardsDebashish

    ok I understand that. Now with regards to the static methods, how the jvm invokes it. Since it belongs to the class instance, there is only once copy right? so when multple threads call the same static method (example utility class method), howz the access controlled? Is the method is made available by 'first come first serve' basis? If so, in a multithreaded application, access to the static mehod is essentially single threaded right? What do you think?
  4. Only one thread can executes the the synchronized static method or block at any point of time and the other threads would wait to get the lock for execution of same.
    A lock is like a privilege that only one thread can "possess" at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock -- maybe very soon, maybe later, possibly never -- the JVM gives the lock to the thread. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.

    The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.

    Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code.

    When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.
  5. As explained above the thread executing the single instance of class object's static synchronized method has to first acquire a lock on that object to execute the method. Once it has entered the method the lock has been already acquired by that thread hence any another thread cannont exeucute this method because they cannot acquire the lock. The thread releases the lock once it has executed the method. Also during the time a lock is acquired by a thread another mehtods cannot execute any synchronized method but it can still execute any non-synchronized method because it doesnt have to acquire a lock.

    Cheers
    Debashish
  6. Thanks both for the explanation..
    I am not talking about a synchronized satatic method. I am talking about a 'regular public static method'. To give an example, say we have a utility class method (public static) to do some computational job. It gets the values as parameters and returns the result. ok..

    Now in a multithreaded environment, when many threads wanted to call this same static method, how the JVM handles that? Does only one thread get a handle to the method? If that is the case, all the threads will have to wait for the previous thead to complete right?

    I am trying to understand the value/trade off for static methods. It's nice to have utility classes and methods over utility object instances.
  7. As far as the static methods are not syncrhonized other threads dont have to wait for the lock .. They simultaneously execute the method . Hence u need to be careful if the changes in your static variables affect your output in such a case . Static methods are preferable for immutable business cases .

    Cheers
    Debashish
  8. Thanks

    I am little confused about the concurrent execution of the static method. When one thread enters the static method, how the other thread concurrently execute the same method. We have only one copy of the method here right? I know JVM can suspend any thread any time to allow other threads, is that's what happening here? But does it make any sense to suspend one thread to allow another one to access a static method. Or is it that JVM creates a pool of that static method and allow threads to accees one from the pool leaving theading headache to the user. The more I think I get confused about the static methods. I started thinking that static method can be a performance killer .. what do you think...
  9. All static methods and variables are present in stack unlinke instance methods and variables which are present in heap. Hence calling static methods is faster since there is no extra level of indirection. There is never a pool of static methods . A single copy is executed by all threads and hence it updates the same set of static variables concurrently.

    Cheers
    Debashish
  10. Thanks for the update.

    Now related to that I have a question. A kind of singleton approach. I have a manger class that caches objects in a static HashMap (should sit in stack right?) .

    At init of the class, I add one object each of other classes to the HashMap. Like
    map.put("x", new Y());

    Now many threads call this manger to get the object associated with 'x' and the same object is returned everytime. My assumption is that since the object is associated with a static collection, the object method (only one method- thread safe) will be treated as a static one right ?
  11. Sorry for delay in reverting back .. Got too much stuck up with work.

    No even though the objects are retrieved from static HashMap they are still instances and the actual instance still lies in the heap. It behaves exactly like any normal instance . The static hashmap just stores the reference of that object in the heap. Hope that answers your question.

    Cheers
  12. Thanks for the reply. So you mean to say that when many threads call the method on the manger class, it returns the same object all the time? That means we have only one object to handle all the threads? That's a performace kill right? I thought, when many threads call the manager method, it returns the object and since the object reference is associated with a static hashmap, the object is treated as static and the method on the instance is invoked in a static fashion.. But you suggest that the instance is not treated as a static one so the instance method is not a static method right? That means each thread has to wait for the other to finish working on the object before it gets a handle to it. That's not what I wanted...It will kill the performance. (The method is pretty light weight this time so it is not noticed I guess)
  13. Assertation that variables used by static methods all are allocated on stack is incorrect. If the static method uses static variables of the class they are not on the stack and you need a concurrent object for synchronization to avoid the racing conditions.

  14. This singleinstance class ytsingleinstance.dll post  helps you to find your solution...