Java Senior Engineer --- multi-thread concurrency

Source: Internet
Author: User
    • Thread Pool (in Java 5)

Executorservice threadpool = executors. newfixedthreadpool (3); // create a fixed thread pool

Executorservice threadpool = executors. newcachedthreadpool (); // create a cache thread pool, dynamically change the number of threads, and destroy unused threads after a period of time

Executorservice threadpool = executors. newsinglethreadexecutor (); // create a single thread. When the thread dies, immediately start the backup thread.

    • Lock condition for Synchronous thread Communication

Lock is similar to synchronized, but more object-oriented than synchronize

Use: lock = new reentranlock ();

Lock. Lock (); lock. Unlock ();

    • Readwritelock RWL = new reentrantreadwritelock ();

Implementation of the cache system -------

Public class cachedemo {

Private Map <string, Object> cache = new hashmap <string, Object> ();

Private readwritelock RWL = new reentrantreadwritelock ();

Public object getdata (string key ){

RWL. readlock (). Lock (); // No locks can be applied between reads. If there is no value in the memory, read the database and write data to the cache.

Object value = NULL;

Try {

Value = cache. Get (key );

If (value = NULL ){

RWL. readlock (). Unlock (); // if no data exists, you must unlock the read and enable the write lock.

RWL. writelock (). Lock ();

Try {

If (value = NULL) {// multiple threads are routed to rml. writelock (). lock (), after a thread is successfully written, the following thread determines whether there is data in the cache when it comes to this step.

Value = "AAA ";


}

}

Finally {

RWL. writelock (). Lock ();

}

RWL. readlock (). Lock ();

}

 


}

 

Finally {

RWL. readlock (). Unlock ();

}

Return value;

}

}

 

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.