Java concurrent programming through the thread door

Source: Internet
Author: User

The thread gate mode is an effective tool for controlling thread concurrency, but many developers are not familiar with it. Similar to a traffic signal that allows an automobile to pass in an orderly manner at a crossroads, a thread door can be blocked or permitted by a thread based on a given condition. Obi Ezechukwu introduces the concept of a thread door in this article, and then tells us how to use it through a multi-threaded prime number generator.

Multithreading and concurrent programming were used to be involved by programming experts. However, with the emergence of multi-core processors and the complexity of application requirements, javax also exists. util. the appearance of the concurrent package has changed. Enterprise Application developers need to understand different concurrency mechanisms and ideas in Java. This demand is even more urgent when it comes to problems that can be solved only by a highly innovative and non-textbook concurrent conception. In this case, simply understanding the Java language and the standard SDK concurrency mechanism can no longer meet your needs. You must be able to use these tools to write programs and implement customized concurrency control.

In this article, we will understand a concurrency mode that is rarely discussed, usually called a thread gate. Like in the real world, a door instance can be opened or closed to allow or prevent thread execution. It implements this operation based on the true values of Some deterministic statements.

Next I will give a general introduction to the thread door based on the communication stream model, and then explain how to build a development environment for the example application (a multi-thread prime number generator. The rest of the article will show you the thread-door mode through examples.

Thread door Overview

A very similar example of a thread door is a traffic signal system running at many intersections. When the red light is on, the car must stop and wait until the signal changes. When the green light is on, the car can pass freely. Traffic signals are designed to achieve cross-traffic. They are useless in areas where cross-traffic is not required. For programmers, You can regard traffic signals as controllers, which allow two-way traffic sharing to use a small part of the same road. Without them, the intersection of traffic lines will be a very dangerous place.

Similarly, the thread door is usually the most suitable situation: When a thread set is activated, other threads cannot be executed. In other words, competing thread sets depend on some true value deterministic values. Each different value of the deterministic statement triggers only one thread set and forces others to be suspended. Note that the focus here is on a series or a group of threads rather than a single thread. In fact, we focus on the situation where multiple threads share access to a single underlying resource, and these threads are divided into different sets based on the operations performed on the resource.

A good example is the producer-consumer process. Some threads are responsible for manufacturing the data used by another set of threads; shared resources are most likely the switching mechanism (Data Bus) used by different thread sets. The true value criterion for determining thread processing is the data volume. If the data is used as a part of a process similar to the production process, and then the data is used or queued in different processes, a memory request queue may sometimes be suitable for this mode.

The producer-consumer model is a good example of describing the concept of a thread. For most programmers, a sample program may be easier to understand a concept. In this article, the question should also be how to easily implement task decomposition and parallel operations, because the focus is to create a multi-threaded solution for it. The example application in this article will achieve the above objectives
Multi-thread Prime Number Generator

The example application in this article will solve a classic old problem, that is, finding all possible prime numbers in the specified range of numbers (for example, from 1 to 1 million. Specifically, our task is to implement a software component and use a method to obtain all prime numbers within a specified range. Assume that the client of this component requires this method to return a thread-safe handle. Once it is called, the result can be accessed and tasks of prime number identification are completed in the background or asynchronously. Another condition is that the operation must provide a blocking method to allow the prime number to be accessed or returned as soon as possible, so that the client does not have to wait for the search to complete before the access result. To simplify this task, there is no restriction on the order in which the handle returns results.

Before continuing to read this article, you should download the code file (http://www.javaworld.com/javaworld/jw-03-2009/threadgates-src.zip) for this article, and then create a development project in your favorite IDE. The file contains ten source files with the following structure:

1-src
2
3-main
4
5-java
6
7-com
8
9-javaworld
10
11-primefinder
12
13 PrimeNumberSearcher. java
14
15 PrimeNumberSource. java
16
17 PrimeUtil. java
18
19 ThreadGate. java
20
21 PrimeSearchThread. java
22
23 PartitionInfo. java
24
25 PrimeNumberReader. java
26
27 GatedPrimeNumberSearcher. java
28
29 ConcurrentPrimeNumberSource. java
30
31-src
32
33-test
34
35-java
36
37-com
38
39-javaworld
40
41-primefinder
42
43 PrimeFinderTest. java

 


PrimeFinderTest. java is a JUnit 4 test package. to test and verify the sample program, you need to use the JUnit tool. To comply with the naming conventions of Maven 2, the source file of the application is under src/main/java, and the JUnit 4 test package that verifies the solution is under src/test/java. Next we will introduce the key contents of these folders.
Prime Number discovered

The com. javaworld. primefinder. PrimeNumberSearcher interface defines the contract that the component must follow. The function of this contract can be specified using findPrimeNumbers (), as shown in List 1.

List 1. Search for contracts

1 PrimeNumberSource findPrimeNumbers (BigInteger lowerBound,
2 BigInteger upperBound );


Com. javaworld. primefinder. PrimeNumberSource is the interface that the result handle must follow. It defines a method BigInteger nextPrime (). When called, it should return the next element in the search result buffer. If the result buffer has been used up, null must be returned to indicate that no result is available. As mentioned above, the execution of this method must be thread-safe.

It should be noted that the focus of this example application task is to find the prime number within the specified search range; therefore, we can use the nextProbablePrime () method from the java. math. BigInteger class. You can encapsulate and call this method in a static method of Utility Class com. javaworld. primefinder. PrimeUtil, as shown in List 2.

List 2. utility method for discovering the first prime number within a specified range

1 public static BigInteger findFirstPrime (long lowerBound, long upperBound)
2
3 {
4
5 BigInteger result;
6
7 BigInteger startPos = BigInteger. valueOf (lowerBound );
8
9 BigInteger nextProbablePrime;
10
11 if (startPos. isProbablePrime (...) // some reasonable accuracy
12
13 nextProbablePrime = startPos;
14
15 else nextProbablePrime = startPos. nextProbablePrime ();
16
17 if (nextProbablePrime. longValue ()> = upperBound)
18
19 result = null;
20
21 else result = nextProbablePrime;
22
23 return result;
24
25}

 


Now you have defined public interfaces and tools for creating the solution. Now you can refine the task. We will first define the implementation of the thread door, which specifies the method for controlling the access result buffer.

Thread implementation

The goal of the thread door is to ensure that multiple readers can access the prime number buffer without blocking the search thread to increase the result.

A reader thread should be able to access any available results without waiting. But if no results are available, it must wait in queue until at least one result is available. This example uses a fair design principle, so the results are provided roughly in the order of arrival of threads. In this example, the focus of the application is not to distribute the results in strict queue order, but to request the prime number of threads within a certain interval, and their data can be obtained before the next batch of threads arrive.

In the real world, similar things that illustrate this design concept are coffee shops. To satisfy customers, coffee orders are processed in batches during prime time. After the waiter removes the customer's order, the user who chooses the same type of coffee will be divided into one group, and the coffee will make the coffee in batches, so that the group of customers can basically enjoy their own coffee at the same time; then the coffee maker creates the next batch of coffee from the customer and repeats the process accordingly. According to this design scheme, customers entering the coffee production queue at a specified interval can get their own coffee at the same time. Of course, they may not install the order strictly to provide coffee. Imagine how inefficient it would be if the coffee had only one cup of coffee at a time.

Return to the task of generating and buffering prime numbers, and use a door with a binary lock like function, this simple application can control access to the result Buffer: When this door is opened, A thread can pass through. When it is closed, the thread must wait in queue until it is re-opened. In a sense, it is more intelligent than a door lock. It can wait for the thread to batch process and ensure that all threads in the same batch can simultaneously pass through this door; the priority of earlier threads is higher than that of later ones. The implementation has its innovative features, that is, no matter how many threads are waiting, the results can always be written into the result buffer. If a traffic signal is used as a metaphor, the thread category may be more like a railway intersection signal, and the train can always get the first permission.

The implementation process is included in com. javaworld. primefinder. ThreadGate, as shown in list 3.

List 3. Door implementation

1 package com. javaworld. primefinder;
2
3 class ThreadGate
4
5 {
6
7 private int waitPosition;
8
9 private int generationSize;
10
11 private int openAttempts;
12
13 private int activeSearchThreads;
14
15 private boolean open;
16
17 public ThreadGate (int searchThre

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.