SOA---java multi-threaded---Lock

Source: Internet
Author: User

Today SOA and distributed computing have become the standard of internet company technology

The knowledge that he includes should be familiar with the understanding. And on this basis, to apply, tuning the framework of various SOA.

Includes four points such as the following. Is the basis of distribution.

A Java multithreading to undertake high throughput.

b Java NIO to undertake high concurrency, with the customization of interactive protocols.

C Java Reflection complete serialization and deserialization.

The application of D design pattern ensures the extensibility of the application.

Pick up the article


because the principle of the lock is more boring, you have to take the problem scene to say. Ability to look down. The ability to study down.

What is the advantage of the lock interface over the synchronized block in Java? You need to implement an efficient cache. It agrees with multiple users to read, but only agrees that a user writes to preserve its integrity, how will you implement it?

The main point here is to examine the difference between lock and synchronized.

1 using the CPU underlying mechanism lock has a distinction between read and write locks.

2 lies in the context of the switching with the optimization of the lock competition.

3 about the avoidance of deadlocks


Synchronized is only an agreement within the JVM itself;

And on this lock his bottom is a hardware-supported atomic operation, various CPUs are supported, various platforms are supported. Assumptions need to be specifically understood. Can look inside the source code, there is an important class is Abstractqueuedsynchronizer, it is polling processing.


Synchronized when the lock is not being taken. Sleeps for some time. It's a very expensive thing to say.

Of course such synchronized inside is the later version number can be optimized.


1 using the CPU underlying mechanism lock has a distinction between read and write locks.

There are two ways to do the above, such as the following

synchronized Sample Example

Code such as the following

public class Synchronizedmap<k,v> {private final map<k,v> map=new hashmap<k, v> ();     Public synchronized void put (K k,v v) {    map.put (k, v);   }    Public synchronized V get (k k) {    return map.get (k);   }

such a rejection of write/write, read/write read/read.

For lock, the relevant code such as the following.

public class Lockmap<k, v> {private final map<k, v> map=new hashmap<k, v> (); private final Readwriteloc K lock=new Reentrantreadwritelock (); Private final Lock r=lock.readlock (); Private final Lock W=lock.writelock ();    public void put (K key,v value) {  w.lock ();  try {   map.put (key, value),  } catch (Exception e) {   e.printstacktrace ();  } finally{   W.unlock ();  }  }  Public V get (K key) {  r.lock ();  try {   return Map.get (key),  } catch (Exception e) {   e.printstacktrace ();  } finally{   R.unlock ();  }  return null; }  }
Such a rejection of write/write read/write.


But reading/reading is not exclusive.


It is also said that read and read are multiple threads can read at the same time. ----can be used as a read-write-less application.


2 lies in the context of the switching with the optimization of the lock competition.

For synchronized.

He had only one condition in the queue. There are threads that correspond to different types (and can be said to handle different types of business). That's when. You can only Notifyall
。 To ensure that the program is correct, all threads are called up, whether it is the thread of the business type you want. This has a significant impact on performance. For example, 10 threads are waiting on a conditional queue, so calling Notifyall will wake up all the threads
This time the thread produces such as the following:
A they will compete on the lock.
b Most of them wait after they're done.
These two steps. Causes a large number of thread context switches.

And a lot of lock-up competition.

But this lock is no problem. He was able to create wait-set for different conditions, such as the producer consumer model. Producers produce an object. Then you want to wake up the consumer. Only a single is required on the wait set above the corresponding condition.

For thread-safe lock queues, the synchronized stack code with thread-safe

Synchronized code such as the following

public class Productstack {private product[] products=new product[10];p rivate int index;public synchronized void Addprodu CT (product product) {try {while (index>= (products.length-1)) {//need to be checked again. Conditional Inference SSYSTEM.OUT.PRINTLN ("The product array is full;") +thread.currentthread (). GetName () + "is Waiting"); Wait ();} Products[index]=product;index++;notifyall ();//In order to start the consumer thread of course also awakened the production line. } catch (Exception e) {e.printstacktrace ();}} Public synchronized Product POPs () {product Product=null;try {while (index<=0) {//need to be checked again. Conditional Inference SYSTEM.OUT.PRINTLN ("The product array is empty;") +thread.currentthread (). GetName () + "is Waiting"); Wait ();}       index--;     Product=products[index];notifyall ();   In order to be able to start the join thread. Of course, it also wakes up consumer threads. } catch (Exception e) {e.printstacktrace ();} return product;}}


For lock

Import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class Productqueue<v> {private final static int defaultsize=10; Private final v[] queue;private int total;private int tail;private int head;private Lock lock=new reentrantlock ();p rivate Condition notempty=lock.newcondition ();p rivate Condition notfull= lock.newcondition ();p ublic productqueue () {This ( DefaultSize);} Public productqueue (int initialcapacity) {super (); this.queue = (v[]) new object[initialcapacity];} public void push (V V) throws Interruptedexception{lock.lock (), try {while (Isfull ()) {notfull.await ();} Queue[tail] = v;++tail;if (tail = = queue.length) tail = 0;total++;notempty.signal ();//Wake up the same type of thread, not wasted. } finally{lock.unlock ();}} Public V Pop () throws Interruptedexception{lock.lock (), try {while (IsEmpty ()) {notempty.await ();} V v=queue[head];head++;if (head==queue.length) head=0;total--;notfull.signal ();//Wake up the same type of thread, not wasted. return v;} Finally{lock.Unlock ();}} public Boolean isEmpty () {return total==0;}  public Boolean isfull () {return total==queue.length;} }

The note explains the root of the problem.

Notifyall When all the threads, producers, and consumers are awakened. And at this point you just want to wake up the producer, or just want to wake up the consumer and make your beard eyebrows Cluth


3 about the avoidance of deadlocks

the nature of the deadlock: there are at least two more locks, and each thread acquires a lock in the same way. In practical applications, there are 3 scenarios, such as the following: deadlock
a same class of objects
The first method
synchronized (locka) {
synchronized (lockb) {
                       }
         }
                                  
a second method
synchronized (lockb) {
synchronized (locka) {
dosomething .....
                  }
             }
the solution to the above situation is as follows. The order is not the same. Make the same order.
b for method public void A (Sameobject a,sameobject b) {
synchronized (a) {
synchronized (b) {
DoSomething .....
                                                        }
                                                            }

                        }
There is a possibility of a deadlock , because the order of the parameters can be locked. at this time can be used and the Trylock is the simplest . the above is in the same class.


b  in this case, it is in two classes. Be able to imagine being two of resources.
                        there is a method in Class A that is synchronous.
                        There is a B method in class B that is synchronous.
                        a inside tune B method.


B inside tune a method.
Deadlocks are generated here, because the order in which locks are acquired is different. the solution to this situation is to remove all synchronized on the method and replace it with a synchronous block. But the synchronization block is the same as the resources that will pass through. Make a copy. Some of the collections within the contract are available for reference.

Globally, the number of locks is analyzed. Gets the order. How do you analyze the order?
How to analyze the deadlock?
A try to use synchronous block, put the method can not be synchronized. Guaranteed open-mode invocation from a business perspective.


b uses the thread stack information to analyze (kill-3) the way.
C for the disassembly of the business.

Theoretically there is no deadlock, but the resource of lock management. When the thread is processed, it takes too long and the business is going to be refactored.

D plus a function code code such as the following

Threadmxbean TMX = Managementfactory.getthreadmxbean ();  long[] ids = Tmx.finddeadlockedthreads ();  if (ids! = null) {     threadinfo[] infos = Tmx.getthreadinfo (IDs, True, true);     System.out.println ("The following threads is deadlocked:");     for (Threadinfo Ti:infos) {        System.out.println (TI);     }    }





SOA---java multi-threaded---Lock

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.