Java memory region

Press Share or Not

  • Threads share data areas: heap, method areas
  • Thread-isolated data area: program counters, local method stacks, virtual machine stacks

Program counter: A line number indicator that can be understood as bytecode executed by the current thread. If the thread is executing a Java method, this counter records the address of the virtual machine bytecode instruction being executed. If you are executing a Native method, this counter value should be null.

Virtual machine stack vs. local method stack: Each Java method creates a stack frame to store information about local variables, operand stacks, dynamic links, and so on. It’s just that the virtual machine stack performs Java methods (that is, bytecode) for the virtual machine, whereas the Native method stack serves the Native methods used by the virtual machine.

Heap: Stores object instances

Method area 1: It is used to store the type information that has been loaded by the virtual machine, constants 2, static variables 3, code cache compiled by the just-in-time compiler, etc.

Runtime constant pool: Part of the method area that holds the various literal and symbolic references generated after compilation (this is also the content of the class file constant pool)

Concurrency issues

① When a singleton object has member variables, multithreaded access will have data problems. ② Threads are safe when the method accessing a singleton object has local variables.

The first explanation:

    class c {
        public int num;
        public void method(int i){
            if(i == 1){
                num = 10;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }                
                System.out.println("a is " + num);
            }else {
                num = 20;
                System.out.println("b is "+ num); }}}Copy the code

If thread A and thread B both access method(I) of instance C, thread A’s I =1, thread B’s I =2, thread A’s num=20, thread B’s num= 13, thread A’s num was 10, the result was changed. (Nuggets don’t support line numbers yet, starting with class C {count the first line)

Second explanation:

    class c {
        
        public void method(int i){
            int num = 0;
            if(i == 1){
                num = 10;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }                
                System.out.println("a is " + num);
            }else {
                num = 20;
                System.out.println("b is "+ num); }}}Copy the code

You need to know about the Java memory area, which we covered in the last section.

  • Object instances are stored in the heap, local variables are stored in the virtual stack, the heap is a shared memory area, and the virtual stack is an isolated area, so there is no impact between threads.
  • Variables inside a method are private to the method and their lifetime ends with the end of the method.

Spring MVC bean scoping and concurrency issues

scope

There are five scopes for beans in Spring 3

Scope explain
singleton In the singleton pattern, only one shared Bean instance exists in the Spring IoC container, always pointing to the same object no matter how many beans reference it. This mode is not secure in multithreading. The Singleton scope is the default scope in Spring
prototype In prototype mode, each time a Prototype-defined bean is fetched through the Spring container, the container creates a new bean instance, each with its own properties and state, while the Singleton global has only one object. As a rule of thumb for stateful beans4Use the Prototype scope instead for stateless beans5Use the Singleton scope
request In an Http request, the container returns the same instance of the Bean. A new Bean is generated for different Http requests and is valid only within the current Http Request. The Bean instance is destroyed when the current Http Request ends.
session In an Http Session, the container returns the same instance of the Bean. New instances are created for different Session requests, and the bean instance is valid only for the current Session. As with Http requests, a new instance is created for each session request, but no attributes are shared between different instances, and the instance is valid only for its own session request. When the request ends, the instance is destroyed.
global Session In a global Http Session, the container returns the same instance of the Bean, valid only if the portlet Context is used.

Thread safety issues with Spring concurrent access

  1. Because Spring MVC is Singleton by default, there is a potential security risk. At its core is the issue of instance variable state retention. This means that for each request, the system will process the original instance, which results in two results:

    • We don’t have to create a Controller every time
    • Reduced object creation and garbage collection time
  2. Since there is only one instance of a Controller, when multiple threads call it at the same time, the instance variable in it is not thread-safe, and there will be data migration problems.

Solutions:

  1. Instance variables are not used in the controller
  2. Change the scope of the controller from singleton to prototype
  3. Use the ThreadLocal variable 6 in the Controller

A deadlock

Due to multithreaded access, there are some unexpected problems, common data problems. Locking is usually done. A different kind of problem occurs with locking – deadlocks

Definition: The phenomenon of multiple concurrent processes waiting for each other because they compete for system resources.

A necessary condition for

Mutual exclusion, hold and wait, non-preemption, circular wait

References:

  1. Java Multithreading 5: Method internal variable is thread-safe
  2. SpringMVC has a Controller that handles concurrency for all user requests
  3. Four necessary conditions and solutions for deadlocks

  1. Jdk1.7 and previous hotspot virtual machines implement the method area as a permanent generation. Jdk1.7 removes string constant pools, static variables, and so on from the method area. Jdk1.8 removes the permanent generation and replaces it with a local memory implementation of the meta space, that is, the method area implementation as the meta space ↩
  2. Method area constants prior to jdk1.7 include string constant pool, runtime constant pool,; Jdk1.7 moves the string constant pool to the heap. ↩
  3. Static variables are removed from the method area ↩ after JDk1.7
  4. Stateful beans are objects that have instance variables, which can hold data and are non-thread-safe. Prototype scope. ↩
  5. Stateless beans are objects that have no instance variables, cannot store data, are immutable classes, and are thread-safe. Generally singleton scope. ↩
  6. Thread-local variable ↩