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

Source: Internet
Author: User

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

The knowledge points that he contains should be familiar and based on which to apply and tune the framework of various SOA.

Contains the following four points, which is the basis of the distribution.

A Java multithreading to undertake high throughput.

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

C Java Reflection completes 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 with the scene to say, in order to look down, to study.

What is the advantage of the lock interface over the synchronized block in Java? You need to implement an efficient cache that allows multiple users to read, but only one user is allowed to write in order to maintain 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 just a protocol within the JVM itself;

And on this lock his bottom is a hardware-supported atomic operation, various CPUs are supported, various platforms are supported. If you need a detailed understanding, you can look inside the source code, there is an important class is Abstractqueuedsynchronizer, it is polling processing.


Synchronized will sleep for a period of time when the lock is not taken, so it is expensive to say. Of course, this synchronized inside is the later version can be optimized.


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

The two ways to achieve the above problem are as follows

Synchronized Example

The code is as follows

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);   }

this rejection of write/write, read/write read/read.

For lock, the relevant code is as follows.

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; }  }
This rejection of write/write read/write.
But reading/reading is not exclusive.

It is also said that reading and reading are multiple threads that can be 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 has only one conditional queue, which has a thread that corresponds to different types (and can be said to handle different types of business), then you can only Notifyall
, in order to ensure that the program is correct, all the threads are called up, regardless of the type of thread you want the business to be. This is very significant for the performance impact. For example, if 10 threads are waiting on a conditional queue, calling Notifyall will wake up all the threads
This time the thread produces the following:
A they will compete on the lock.
b Most of them wait after they're done.
These two steps will result in a lot of thread context switching. And a lot of lock-up competition.

But this lock is no problem. He can create wait-set for different conditions, such as the producer consumer model, where the producer produces an object, and then wants to awaken the consumer by simply having the wait set on the corresponding condition.

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

The synchronized code is as follows

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, the condition is judged 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 re-examined, the condition is judged 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 adding threads. 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 the actual application, there will be 3 cases, there are 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 scenario is that the order is different and the order is made.
b for method public void A (Sameobject a,sameobject b) {
synchronized (a) {
synchronized (b) {
DoSomething .....
                                                        }
                                                            }

                        }
There is a possibility of a deadlock here, because the order of the parameters is possible to be locked. at this time can be used and the Trylock is the simplest. the above is in the same class.
b This case, in two classes, can be imagined as two resources,
there is a method in the class A that is synchronous.
in Class B There is a B method 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 the synchronized on the method and replace it with a synchronous block, but the synchronization block is the same as the one that will pass through the resources and make a copy. This is a collection of some of the collections within the contract. Global, analyze the number of locks, get the order. How do you analyze the order?
How to analyze the deadlock?
A strive to use synchronous blocks, the inability to synchronize the method, from the business perspective to ensure open mode invocation.
b uses the thread stack information to analyze (kill-3) the way.
C for the disassembly of the business. In theory there is no deadlock, but the resource of lock management, when the thread is processed, takes too long to reconstruct the business.

D plus a function code code as follows

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.