I think concurrency is broadly divided into two situations
1, multiple threads or processes accessing public resources, such as 12306
2, multiple threads access the same instance variable, such as Tomcat multiple request threads access the same singleton bean, concurrency problems can occur if the bean is stateful
For the first case, the Java Synchronization keyword synchronized can be resolved under the same JVM. But in the distributed situation, it should be solved in other ways, such as database optimistic lock, zookeeper.
Take a ticket for example, like ID 111 and 10 tickets, now with a lot of requests to update the data
The pseudo-code resembles the following:
intnum=10;//SELECT * from DB D while(true){ intResult=updatedbbynum (num);//Update db D set d.num=d.num-1 where d.num=10 if(result==1){ Break; }Else { Try{Thread.Sleep (3000); } Catch(interruptedexception e) {System.out.println (E.getmessage ()); } } }
For the second case, if the bean is simply not changed to stateless, it can be resolved by threadlocal
Public classThreadlocaltest {//Create an integer thread-local variable Public Static FinalThreadlocal<integer> local =NewThreadlocal<integer>() {@OverrideprotectedInteger InitialValue () {return0; } }; Public Static voidMain (string[] args)throwsinterruptedexception {thread[] threads=NewThread[5]; for(intj = 0; J < 5; J + +) {Threads[j]=NewThread (NewRunnable () {@Override Public voidrun () {//gets the local variable of the current thread and then accumulates 5 times intnum =Local.get (); for(inti = 0; I < 5; i++) {num++; } //reset the accumulated local variableslocal.set (num); System.out.println (Thread.CurrentThread (). GetName ()+ " : "+local.get ()); } }, "Thread-" +j); } for(Thread thread:threads) {Thread.Start (); } }}
Threalocal is the addition of variables into thread variables, so that each thread accesses its own variables, and other threads do not affect each other. Equivalent to a copy of the variable.
-------be grateful if you have any mistakes.
Understanding of Java Concurrency