Java multithreading concurrency to invoke a class of static method security discussion

Source: Internet
Author: User
Tags instance method mutex


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

Summarized as follows:

1,java when executing a static method, the will be copied in memory, if the static method is in the class there is no static variables, then thread access is safe, such as in Java EE in the server will be a multithreaded processing request at this time if the design of the global need to call static method, you can use this design.

2,java when executing static methods, if static variables are used, and static data is used in the function design of a class, it is best to use the Synchronized keyword when calling a function, otherwise the inconsistent rows of the data are caused.

3, add static global variables, in multithreaded access will appear inconsistent rows of data, it is best to use synchronized keyword to ensure the consistency of data, typical representative is a single example mode.


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

The following is a set of contrasting examples to explain from the beginning:
What happens when you use static methods in multiple threads. That is, what happens to multithreading accessing static static methods of the same class. Whether thread safety issues occur.
public class Test {
public static void operation () {
.. do something
}
}
It turns out that as long as there is no multithreading shared data in static functions, there is no problem of multithreading accessing the same static method with resource conflicts. 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 results show that each thread's access to the static method is executed across the board, but this does not affect the calculation of the sum value in the individual thread static method print (). That is, static methods that do not use global variables in this procedure are safe in multiple threads, and whether static methods cause thread-safety problems depends primarily on whether the static method modifies the global variable (static variable member).
When using the same static method in multiple threads, each thread uses a copy of its own instance field (instance field) and shares a static field (static field). So, if the static method does not manipulate a static member, using the instance field only within the method (instance field) does not cause a security issue.
However, if the static method operates on a static variable, it requires a secure handling in a static method using mutually exclusive access. Let's take a look at the problem with not using mutex 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 run results show that the I value is a random number. In order to achieve mutex 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 you access a synchronous static method, you get the class object of that type, so when one thread enters a synchronized static method, the thread monitor gets the object lock of the class itself, and no other thread can enter any of the static synchronization methods for that 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 in the signal to achieve the process of mutual exclusion and synchronization problems, if it involves multiple static methods in the same class to handle multithreaded shared data, it becomes the use of semaphores to solve producer-consumer problems. In other words, the static method is a critical resource, and the access to the static method belongs to the critical area; the modification to the static variable is a critical resource, and the modification of the static variable belongs to the entry critical section.

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.