Hy, I am using threads in my application. I know the objects that are created inside the thread are stored in the heap space and this is for all the threads, right?
So in the heap space are stored all the objects created for the threads. Is there a way to know the amount of heap memory is occupied by the objects created for a single thread ?
I know I cant limit the stack memory for a thread but this memory is for the variables and not for the objects, right?
Not really. The "size" of an object is a very complicated thing to compute, as it involves not only knowing the size of primitive objects and the size of references, but also a recursive calculation involving the size of objects referred to by the original object, taking into account that the object references form a directed graph and not necessarily a tree.
That's probably more work than you want to do for whatever prompted this requirement, so I would suggest finding some simpler proxy calculation.
It seems a bit counter-productive to want to go to this length also. I'd say you want to prevent your application from eating up too much memory, not defensively work around it when it happens. There are plenty of documented strategies for bringing down resource consumption, wanting to do what you want is basically going against what Java is built for - to take resource management away from you so you can focus on the business logic. In stead you want to do it yourself anyway.