Java multithreading concurrency to invoke static method security of a class

Source: Internet
Author: User
Tags instance method stub

Java multithreading concurrency to invoke static method security of a classtransferred from: http://blog.csdn.net/weibin_6388/article/details/50750035

This article mainly discusses the data security of multithreading to static method access

Summarized as follows:

1,java in the execution of static methods, will be copied in memory, if the static method is inside the class there is no static variables, then thread access is safe, such as in Java EE in the server must be multi-threaded processing requests at this time if the design of the global need to call the static method, this design can be used.

2,java when executing a static method, if a static variable is used, while the class's function is designed with static data, it is best to use the Synchronized keyword when calling the function, or it will result in inconsistent rows of the data.

3, add static global variables, in multi-threaded access to the data inconsistent rows, it is best to use the Synchronized keyword, to ensure consistency of data, the typical representative is a singleton mode.

General conclusion: Java is thread-safe, that is, any method (including static methods) can be regardless of the thread conflict, but there is a premise that there can be no global variables. If there are global variables, you need to use the synchronization mechanism.

This is explained from the beginning by a set of comparison examples:
What happens when you use static methods in multiple threads? That is, what happens when multithreading accesses static static methods of the same class? Is there a thread safety issue?
public class Test {
public static void operation () {
... do something
}
}
It turns out that as long as there is no multi-threaded shared data in the static function, there is no problem of resource conflict for multi-threaded access to the same static method. Let's look at an example:
public class Staticthread implements Runnable {
@Override
public void Run () {
TODO auto-generated Method Stub
Staticaction.print ();
}
public static void Main (string[] args) {
for (int i = 0; i <; i++) {
New Thread (New Staticthread ()). Start ();
}
}
}
public class Staticaction {
public static int i = 0;
public static void print () {
int sum = 0;
for (int i = 0; i < i++) {
System.out.print ("step" + i + "is running.");
sum + = i;
}
if (sum! = 45) {
System.out.println ("Thread error!");
System.exit (0);
}
System.out.println ("sum is" + sum);
}
}
The actual execution results show that each thread's access to the static method is cross-executed, but this does not affect the calculation of the sum value in the static method print () for each thread. In other words, static methods that do not use global variables in this process are safe in multi-threading, and whether static methods cause thread-safety problems mainly depends on whether the static method modifies the global variables (static variable member).
When using the same static method in multi-threading, each thread uses a copy of its own instance field (instance field) and shares a static field. So, if the static method does not manipulate a static member, only the instance fields (instance field) are used inside the method, which does not cause security problems.
However, if the static method operates on a static variable, it needs to be handled securely in a static method with mutually exclusive access. Let's take a look at what's wrong with not using mutually exclusive access: public class Staticaction {
public static int i = 0;
public static void Incvalue () {
int temp = STATICACTION.I;
try {
Thread.Sleep (1);
} catch (Exception e) {
E.printstacktrace ();
}
temp++;
staticaction.i = temp;
}
}
public class Staticthread implements Runnable {
@Override
public void Run () {
TODO auto-generated Method Stub
Staticaction.incvalue ();
}
public static void Main (string[] args) {
for (int i = 0; i <; i++) {
New Thread (New Staticthread ()). Start ();
}
try {
Thread.Sleep (1000); Set aside enough time for the above thread to run out
} catch (Exception e) {
E.printstacktrace ();
}
System.out.println (STATICACTION.I);
}
}
The actual running result shows that the I value is a random number. In order to achieve mutually exclusive access, we need to add a synchronized keyword. The code is modified as follows:
public class Staticaction {
public static int i = 0;
Public synchronized static void Incvalue () {
int temp = STATICACTION.I;
try {
Thread.Sleep (1);
} catch (Exception e) {
E.printstacktrace ();
}
temp++;
staticaction.i = temp;
}
}
public class Staticthread implements Runnable {
@Override
public void Run () {
TODO auto-generated Method Stub
Staticaction.incvalue ();
}
public static void Main (string[] args) {
for (int i = 0; i <; i++) {
New Thread (New Staticthread ()). Start ();
}
try {
Thread.Sleep (1000);
} catch (Exception e) {
E.printstacktrace ();
}
System.out.println (STATICACTION.I);
}
}
The result of the operation must be 100.
A static method that joins the Synchronized keyword is called a synchronous static method.
When accessing a synchronous static method, the class's "Class" object is obtained, so when a thread enters a synchronous static method, the thread monitor acquires the object lock of the class itself, and other threads cannot enter any static synchronization methods for the class. It is not like an instance method, because multiple threads can access different instance synchronization instance methods at the same time. This is actually the operating system with the signal to achieve the process of mutual exclusion and synchronization problem, if involved in the same class with multiple static methods to deal with multi-threaded shared data, it becomes a signal to solve the producer-consumer problem. In other words, the static method is a critical resource, the access to the static method belongs to the critical section, and the modification of the static variable is a critical resource, and the modification of the static variable belongs to the critical section.

Java multithreading concurrency to invoke static method security of a class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.