How does the singleton Bean serve the concurrent request?

https://stackoverflow.com/questions/25617962/how-does-the-singleton-bean-serve-the-concurrent-request

Saravan Kumar,

I understand the motivation behind your question. Before I started working on compilers, I also had a very similar wanting to know the internals of the Java Virtual Machine.

First of all, I'm impressed by your question. There needs to be a couple of points of distinctions and understanding in order to solve your question. Firstly: A Singleton pattern, or sometimes even called an anti-pattern, ensures that there is only one instance of this class available to the JVM. This means we're essentially introducing a global state into an application. I know you understand this, but it is just a point of clarification.

Now the internals.

When we create an instance of a class, we are creating an object that is residing in JVM's shared memory. Now these threads are independently executing code that operates on these instances. Each thread has a working memory, in which it keeps data from the main memory that are shared between all threads. This is where the reference to the Singleton object you have create resides. Essentially what is happening is that the byte code which was generated and is representative of the singleton object you created is being executed on each one of these threads.

Now the internals of how this happens is as follows:

Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. Now, The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated. The heap is created on virtual machine start-up. When you're thread requests the singleton instance, it is going to point to a reference in the heap where the byte code for this Singleton resides. It is going to execute the appropriate code, in your case it's going to execute the first method for the first request and the second method for the second request. It's able to do this because there are no locks or restriction preventing the compiler from pointing the program counter to the area in the heap where this instance is allocated. The only restriction that the Singleton class puts on the Java Virtual Machine is that it can have only one instance in the heap of this class. That's simply it. Other than that, you can refer to it 100x times from your method, the compiler is going to point to the same byte code and simply execute it. This is why we typically want the Singleton class to be stateless, because if we any thread access it, we don't want internal variables to be mutated because of the lack of concurrency control.

Please let me know if you have any questions!


猜你喜欢

转载自blog.csdn.net/liduanwh/article/details/80905078