Synchronous processing in Java

Source: Internet
Author: User
The synchronization here is only for a single Java application. Database Synchronization and file synchronization are not discussed here. Relationship between synchronization and Multithreading
1. synchronization is not required in a multi-threaded environment.
2. synchronization is not required even in multi-threaded environments. Why synchronization:
To prevent multiple threads from modifying the same data, you must synchronize the data. Otherwise, data inconsistency may occur.
Java provides very convenient multi-thread support, so synchronization problems are common, especially Servlet and
The thread security issue of JSP is particularly obvious.
Http://blog.csdn.net/treeroot/archive/2004/09/03/93881.aspx synchronization of the essence:
Java synchronization is actually to get the synchronization lock of the object, and other threads can only wait. Most of our programs are not thread-safe, because there is no synchronization, and we don't need it, because in most cases there is no multi-threaded environment at all.

Here is only one example to illustrate the essence of synchronization.

Code 1:
Class syntest {
Synchronized static method (){
// This method is synchronous. Only one thread can come in at a time.
System. Out. println ("begin ");
Try {thread. Sleep (2000 );}
System. Out. println ("end ");
}
Public static void main (string [] ARGs ){
// Start 10 threads. The Anonymous class is used here, because it is really convenient.
For (INT I = 0; I <10; I ++ ){
New thread (){
Public void run (){
Method ();
}
}. Start ();
}
}
}
It is easy to see that each thread can enter only after the previous thread exits the method.
The above synchronization method can have two other equivalent methods: Code 2:
Class syntest {
Static Method (){
Synchronized (syntest. Class ){
// This method is not a synchronous method, but only one thread can enter the synchronization block at a time.
System. Out. println ("begin ");
Try {thread. Sleep (2000 );}
System. Out. println ("end ");
}
}
Public static void main (string [] ARGs ){
// Start 10 threads. The Anonymous class is used here, because it is really convenient.
For (INT I = 0; I <10; I ++ ){
New thread (){
Public void run (){
Method ();
}
}. Start ();
}
}
} Code 3:
Class syntest {
Private Static object lock = new object ();
Static Method (){
Synchronized (LOCK ){
// This method uses a special object as the lock.
System. Out. println ("begin ");
Try {thread. Sleep (2000 );}
System. Out. println ("end ");
}
}
Public static void main (string [] ARGs ){
// Start 10 threads. The Anonymous class is used here, because it is really convenient.
For (INT I = 0; I <10; I ++ ){
New thread (){
Public void run (){
Method ();
}
}. Start ();
}
}
} In fact, the above three cases are basically equivalent, but the third method is very common. It is estimated that there will be performance improvement. After all, locking a small object seems easier than locking a large object. The above static method is used. If it is not static, code 2 is synchronized (this ).
Here, we will first describe that there is no relationship between synchronization and thread security and whether the method is static. What if I want to determine whether a class or method is thread-safe?
Assume that a class does not provide operations to directly modify member variables, that is, it can only be modified through methods.
Object. We can easily conclude that only all methods are thread-safe, and this class is the thread.
Secure. To determine whether a method is thread-safe, you only need to read the instruction document or the source code. However, most of the statements are not thread-safe, but cannot be seen from the method declaration.
Class math {
Public static int safepow (int x, int y) {// assume that Y is greater than 0
Int res = X;
For (INT I = 1; I <Y; I ++) RES * = X;
Return res;
}
Public static int unsafepow (int x, int y ){
Pow = y;
Return POW (X );
}
Private Static int POW;
Private Static int POW (int x ){
Int res = X;
For (INT I = 1; I <POW; I ++) RES * = X;
Return res;
}
}
I don't know how to give back such a boring example. I found this problem clearly in my mind, but it is difficult to express it clearly. Let's take a look at the example of two threads calling unsafepow.
Thread1: unsafepow (3, 3 );
Thread2: unsafepow (2, 2 );
Suppose thread1 is executed to POW = y; enter the method POW (int x );
Pow = 3;
Then thread2 executes POW = y; enters the method POW (int x );
Pow = 2;
Then thread 1 executes the POW (int x) method and waits until the power of 3 is 2, leading to errors.
This method is not thread-safe. The key to thread security is to modify the member variables (class variables or instance variables, both of which are
), And there are also thread security issues with access methods.
We know that hashtable is thread-safe, because all methods are synchronized. That is to say, at most one thread can operate on hashtable at the same time, so we think it is thread-safe. Assume that its size () method is not synchronized,
Then it is possible that you have not returned the size method call, and a thread has added another data. At this time, the value you read should be the correct value, however, this size method has not yet returned, and another thread has deleted a data. At this time, you returned an error. Hashtable also needs to be synchronized. Of course, hashtable is thread-safe, and Java documentation also describes it. But if it is not equal to thread security, do not sync pressure.
Public class synhashtable {
Public static void main (string [] ARGs)
{
Final hashtable ht = new hashtable ();
Ht. Put (new object (), "Quick to death ");

New thread (){
Public void run (){
While (true ){
If (HT. Size () <10 ){
Ht. Put (new object (), "object ");
}
Else {
Ht. Clear ();
}
}
}
}. Start ();

New thread (){
Public void run (){
Unsafe (HT );
}
}. Start ();


} Static void unsafe (hashtable HT ){
While (true ){
// Synchronized (HT ){
Iterator it = Ht. Values (). iterator ();
While (it. hasnext ())
System. Out. println (it. Next ());
}
//}
}
}
If it is not synchronized, it will crash soon.

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.