I know the basics of how memory allocation in Java works - that most of the memory the application takes is allocated on the heap, and the heap is shared by all threads, and therefore there is no concept of objects owned by a thread, and you cannot easily calculate how much memory a thread is taking with all the objects it owns.
But I wondered if there is any way to count and sum allocations triggered from a specific thread? The memory allocation is happening on the heap, but it's always triggered by a thread wanting to create an object, so I was wondering if this relationship could be profiled somehow?
My thought is that a typical Spring Boot application will boot, allocate a bunch of objects from the main thread, then start a webserver that spawns threads for handling the HTTP requests and each time a request is received, a thread is assigned to it, and it's handled in that thread. The webserver thread have a specific point where they accept the requests, process them and then send the response. If we could somehow "reset" the allocation stats at the point where the request is accepted and then submit the stats to some collector after the response is sent, we could have very nice statistics about individual endpoints and see how much memory they allocate.
I know this wouldn't be perfect, but with this approach, you'd at least gain some visibility into how much memory is allocated per HTTP request, and you'd be able to see that for example some request is loading half the database into memory and that might be a problem.