New Features of JDK5: thread synchronization tools (III) and new features of jdk5

Source: Internet
Author: User
Tags svn update server hosting

New Features of JDK5: thread synchronization tools (III) and new features of jdk5

I. Semaphore

Semaphore can control the number of threads simultaneously accessing resources. For example, it can control the number of concurrent threads allowed by a file.

The functions implemented by Semaphore are similar to five pits in the restroom. If ten people are added to the restroom, only five people can occupy the toilet. When any of the five people leaves, one of the other five persons waiting can be occupied. in addition, among the five waiting persons, the opportunity can be obtained randomly or in the order of first-in-last-in. This depends on the parameter options passed in when the Semaphore object is constructed.

Public class SemaphoreTest {public static void main (String [] args) {// create a thread pool ExecutorService service = Executors. newCachedThreadPool (); final Semaphore sp = new Semaphore (3); // indicates that there are currently three lights (three concurrent threads are allowed) // start five threads for (int I = 0; I <5; I ++) using service.exe cute (new Runnable () {public void run () {try {sp. acquire (); // light up a lamp // availablePermits: indicates the available lamp System. out. println ("Thread" + Thread. currentThread (). getName () + "Enter, current" + (3-sp. availablePermits () + "concurrent"); Thread. sleep (long) (Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "coming soon"); sp. release (); // turn off a lamp (release) System. out. println ("Thread" + Thread. currentThread (). getName () + "Left, current" + (3-sp. availablePermits () + "concurrent");} catch (InterruptedException e) {e. printStackTrace ();}}});}}}
A single Semaphore object can implement the mutex lock function, and it can be obtained by one thread, and then released by another thread. This can be applied to deadlock recovery.

Thread pool-1-thread-1 enters. Currently, one concurrent thread pool-1-thread-2 enters. Currently, two concurrent threads pool-1-thread-4 enter, three concurrent threads, pool-1-thread-4, are about to leave thread pool-1-thread-4, two concurrent threads are currently in pool-1-thread-3, three concurrent threads, pool-1-thread-2, are about to leave the thread pool-1-thread-2, two concurrent threads are currently in pool-1-thread-5, three concurrent threads, pool-1-thread-5, are about to leave the thread pool-1-thread-5, two concurrent threads, pool-1-thread-1, are about to leave the thread pool-1-thread-1, currently, one concurrent thread pool-1-thread-3 is about to leave the thread pool-1-thread-3. Currently, there are 0 concurrent threads.


Ii. CyclicBarrier

It indicates that everyone waits for each other and starts to set up after gathering. After the scattered activities, they will meet at the designated place.

This is like the whole company's staff taking advantage of the weekend group outing. They first set up their own homes to the company, and then set up to visit the park at the same time, after gathering at the specified location, start dining at the same time.

Public class javasicbarriertest {public static void main (String [] args) {// enable a thread pool ExecutorService executorService = Executors. newCachedThreadPool (); // parameter 3: It indicates that three of them are in the correct state before they can go down. Otherwise, they will remain in the waiting state final CyclicBarrier cb = new CyclicBarrier (3 ); // create 3 threads for (int I = 0; I <3; I ++) {executorService.exe cute (new Runnable () {@ Overridepublic void run () {try {Thread. sleep (long) (Math. random () * 1000); // each thread has a different "rest" Time M. out. println ("Thread" + Thread. currentThread (). getName () + "coming to collection location 1, current" + (cb. getNumberWaiting () + 1) + "arrived," + (cb. getNumberWaiting () = 2? "It's all done, continue": "Waiting"); cb. await (); // after the first arrival, the Thread will continue to be executed when all three arrive. sleep (long) (Math. random () * 1000); // each thread has a different "rest" Time System. out. println ("Thread" + Thread. currentThread (). getName () + "coming to collection Location 2, current" + (cb. getNumberWaiting () + 1) + "arrived," + (cb. getNumberWaiting () = 2? "It's all done, continue": "Waiting"); cb. await (); Thread. sleep (long) (Math. random () * 1000); // each thread has a different "rest" Time System. out. println ("Thread" + Thread. currentThread (). getName () + "coming to collection location 3, current" + (cb. getNumberWaiting () + 1) + "arrived," + (cb. getNumberWaiting () = 2? "It's all done, continue": "Waiting"); cb. await ();} catch (Exception e) {e. printStackTrace () ;}}) ;}executorservice. shutdown ();}}
After the three threads finish their respective tasks and arrive at the collection location at different times, they can continue to do their jobs, arrive at the new collection point, and then go to their respective jobs.

Thread pool-1-thread-2 is about to arrive at collection location 1. Currently one has arrived, waiting for thread pool-1-thread-3 to arrive at collection location 1, currently, two have arrived, and are waiting for the thread pool-1-thread-1 to arrive at collection location 1. Currently, three have arrived, all of which have arrived, the thread pool-1-thread-2 is about to arrive at the collection site 2. Currently, one has arrived and is waiting for the thread pool-1-thread-3 to arrive at the collection site 2, currently, two have arrived, and are waiting for the thread pool-1-thread-1 to arrive at the collection site 2. Currently, three have arrived, all of which have arrived, the thread pool-1-thread-3 is about to arrive at the collection site 3. Currently, one has arrived and is waiting for the thread pool-1-thread-2 to arrive at the collection site 3, currently, two have arrived, waiting for thread pool-1-thread-1 to arrive at collection location 3. Currently, three have arrived and are all there. Proceed.

Iii. CountDownLatch

As if a countDown counter, the CountDownLatch object's countDown method is called to reduce the counter by one. When the Count reaches 0, all the waiting persons or individual waiting persons start to execute.

Application: the referee starts to run with a password. When all the athletes run to the end, the referee announces the results. in addition, a plan can be implemented only when multiple leaders sign the plan.

Public class CountDownLatchTest {public static void main (String [] args) throws Exception {ExecutorService service = Executors. newCachedThreadPool (); // subCounter, count is 1 final CountDownLatch subCounter = new CountDownLatch (1); // main counter, count is 3 final CountDownLatch mainCounter = new CountDownLatch (3 ); for (int I = 0; I <3; I ++) {service.exe cute (new Runnable () {@ Override public void run () {try {Syst Em. out. println ("Thread" + Thread. currentThread (). getName () + "is preparing to accept the command! "); SubCounter. await (); // The Sub-Thread waits for System. out. println (" Thread "+ Thread. currentThread (). getName () +" commands accepted! "); Thread. sleep (long) Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "response command processing result! "); MainCounter. countDown (); // reduce the count on the counter by 1. When the count is 0, the main thread starts to execute} catch (Exception e) {e. printStackTrace () ;}});} Thread. sleep (long) Math. random () * 1000); System. out. println ("Thread" + Thread. currentThread (). getName () + "command to be released soon! "); SubCounter. countDown (); // reduce the count on the counter by 1. When the count is 0, the sub-thread starts to execute System. out. println ("Thread" + Thread. currentThread (). getName () + "sent command, waiting for result! "); MainCounter. await (); // The main thread waits for System. out. println ("Thread" + Thread. currentThread (). getName () + "all response results have been received! "); Service. shutdown ();}}
Thread pool-1-thread-1 is preparing to accept the command! Thread pool-1-thread-3 is preparing to accept the command! Thread pool-1-thread-2 is preparing to accept the command! Thread main is about to release the command! The main thread has sent a command and is waiting for the result! Thread pool-1-thread-2 commands accepted! Thread pool-1-thread-3 commands accepted! Thread pool-1-thread-1 Command accepted! Thread pool-1-thread-3 responds to the command processing result! Thread pool-1-thread-2 responds to the command processing result! Thread pool-1-thread-1 responds to the command processing result! Thread main has received all response results!

Iv. Exchanger

It is used to exchange data between two people. After a transaction is completed, each person wants to exchange data with the other party. The first person who obtains the data will wait until the second person receives the data, to exchange data with each other:

Public class ExchangerTest {public static void main (String [] args) {ExecutorService service = Executors. newCachedThreadPool (); final Exchanger exchanger = new exchanger(registry.service.exe cute (new Runnable () {@ Overridepublic void run () {try {String data1 = "aaa"; System. out. println ("Thread" + Thread. currentThread (). getName () + "changing data:" + data1 +! "); Thread. sleep (long) Math. random () * 10000); String data2 = (String) exchanger. exchange (data1); System. out. println ("Thread" + Thread. currentThread (). getName () + "the returned data is:" + data2);} catch (Exception e) contains invalid values when using service.exe cute (new Runnable () {@ Overridepublic void run () {try {String data1 = "bbb"; System. out. println ("Thread" + Thread. currentThread (). getName () + "changing data:" + data1 +! "); Thread. sleep (long) Math. random () * 10000); String data2 = (String) exchanger. exchange (data1); System. out. println ("Thread" + Thread. currentThread (). getName () + "the returned data is:" + data2) ;}catch (Exception e ){}}});}}
Thread pool-1-thread-1 is switching data: aaa! Thread pool-1-thread-2 is switching data: bbb! The data returned by the thread pool-1-thread-1 is: The data returned by the bbb thread pool-1-thread-2 is aaa.





SVN operation instructions and backup policies

Technical preparations for websites with millions of visits
In today's pure website technology, because of the development of the open source model, building a small website is now very simple and cheap, so many people are positioning their entrepreneurial orientation in Internet applications. Most of these people are not very technical or proficient, and the knowledge about website development and maintenance is scattered and the learning cost is too high. Therefore, this article combines these knowledge points, in terms of the system, what problems may occur between a small website with thousands of visits per day and a small website with 1 millions or 2 millions visits per day, and how to avoid these problems at the beginning.

Your website's access traffic is gradually increasing due to your efforts. problems may also begin to emerge during the process of increasing traffic volume. The increase in bandwidth, hardware, and staff costs are obvious, and a considerable part of the cost is due to code restructuring and architecture restructuring, even the underlying development language is changed, the worst case is data loss, and all efforts are torch. Most of these costs can be avoided in the first place. lay a good foundation and save a lot of energy and focus less on them.

The technical route varies with initial investment costs. Here we assume that the website is just an idea. We plan to invest about 50 thousand in server hardware bandwidth in the first year. There are many options for this amount of funds, such as renting a virtual host, renting a separate server, popular private cloud, or hosting a server. In the first two options, the website needs to be migrated when it develops to a certain scale. At that time, the re-planning will obviously have a greater impact. Because server hosting is self-configured and completely controllable, this mode is basically used for websites of a certain scale. When using a website hosted on your own server, pay attention to the following points at the beginning --

I. development language
In general, technicians (programmers) choose the most familiar language based on their own technical background, but it is impossible to write a program by a person forever. Therefore, it is necessary to make a careful effort to choose a language. First of all, it is clear that no matter what language is used, the final code quality is to look at management, so we analyze the development cost from the early stage. Currently, the popular Website Languages in China include java, php,. net, python, and ruby. Since python and ruby are popular in China, it is still relatively difficult to recruit people .. There are a large number of people on the net platform. However, when performance problems need to be solved in the future, the requirements for personnel skills are relatively high. The remaining java and php users are the most common. Java and php cannot be compared in terms of language. However, in the early stage, almost all applications rely on front-end support websites. php is easy to get started and fast to write, with a relatively higher advantage. As for backend such as behavior analysis, bank interface, asynchronous message processing, and so on, you need to select different languages based on different business needs.

Ii. Code Version Management
Code version management is required for a slightly larger website. Code version management has two major advantages: one is to facilitate collaborative work, and the other is to query and compare historical records. There are a lot of code version management software, such as vss/cvs/svn/hg, which are currently popular in China, among which svn is still very popular.

If svn is selected, several considerations are taken. First, what tree structure is used. In the initial stage, there may be only one trunk, and branches need to be established in the future, for example, one Development Branch and one online branch. In the future, each group may have one branch. We recommend that you select two branches for development and production when there are few people at the beginning. Each function can be tested locally and then submitted to the Development Branch for unified testing. This function can be merged to the Production Branch when it is released. If each person builds his/her own branch, it will waste a lot of effort in merging. For WEB applications that need to be modified several times every day, it takes too much time.

Deploy code to the server, which can be manually or automatically deployed. Manual deployment is relatively simple. Generally, svn update can be directly performed on the server, or a new directory svn checkout can be found, and then the web root is sent to ln-s. The more complex the application, the more complicated the deployment, and there is no unified standard, just do not use the ftp upload format. First, the file reference inconsistency error rate increases during the upload, second, it is easy to see the developer's version and online ...... remaining full text>


Related Article

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.