"Java concurrent Programming Combat" reading notes--__java foundation of concurrent application

Source: Internet
Author: User
Tags volatile
1. Using a thread poolWhen an application needs to handle multiple tasks, such as a Web server processing the requests it receives, you can use the thread pool. By reusing existing threads rather than creating new ones, you can apportion the huge overhead of thread creation and destruction as you process multiple requests. Another advantage is that when a request arrives, the worker thread usually already exists, so it will not delay the execution of the task because of waiting for the thread to be created, thereby increasing responsiveness. By adjusting the size of the thread pool appropriately, you can create enough threads to keep the processor busy, while also preventing too many threads competing with each other for resources to deplete memory or fail the application. More thread pool content reference Java thread pool
2. Cancellation of MissionJava does not currently provide any mechanism to safely terminate threads (although methods such as Thread.stop and suspend provide such a mechanism, they should be avoided because of some serious flaws) but it provides interrupts (interruption), a collaborative mechanism that The ability to enable one thread to terminate the current work of another thread. There's a way to do it. Cancellation mechanism: Sets a volatile object as a token of whether a task is canceled. Check that the task is canceled before each task is executed.
public class Test {
	private volatile Boolean iscancle = false;
	Private blockingqueue<string> Blockingqueue = new arrayblockingqueue<string> (3);
	public void put () {while
		(!iscancle) {
			blockingqueue.add (' result ');
		}
	public void Cancle () {
		iscancle = true;
	}
}
But such a design can have serious problems, in the above example the depth of Blockingqueue is 3. If there are 3 objects already stored in the queue. Now I'm going to put a 4th object inside, and the thread will block the add operation while waiting for the queue to be empty. If you execute cancle at this time, set the iscancle to true. But if the queue is always full, then the thread will not check if (!iscancle), then the task will always block down and not quit.
The right thing to do is to use the thread interrupt mechanism that Java threads provide for us. Each thread has a Boolean type of interrupt state. When a thread is interrupted, the interrupt state of this thread is set to true. A method of interrupting a thread and querying a thread's interrupt state is provided in thread interrupt () method--Middle thread isinterrupted () method--to determine whether the threads are interrupted
Then we usually use some of the blocking methods, such as Thread.Sleep object.wait. The blockingqueue we used above also provide us with blocking methods put () These blocking methods check when the thread is interrupted and return early when the interrupt is found. So the key thing to understand here is that it doesn't really immediately interrupt a running thread, it just makes a interrupt request, sets the interrupt state to ture, and interrupts itself at the right time by the running thread (check the interrupt status at the right time)
public class Test extends Thread {
	
	private blockingqueue<string> blockingqueue = new arrayblockingqueue< String> (3);
	public void Run () {while
		(true) {
			try {
				blockingqueue.put (' result ');
			} catch (Interruptedexception e) {
				System.out.println ("cancle!");
	}} public void Cancle () {
		interrupt ();
	}
	
}

3. Handle an interruptible blocking operation Synchronous Socket I/O in the java.io package。 In a server application, the most common form of blocking IO is the reading and writing of sockets. Although methods such as read and write in InputStream and OutputStream do not respond to interrupts, by shutting down the underlying sockets, you can make a thread that is blocked by executing methods such as read and write to throw a socketexception. synchronous I/O in the java.io package。 When a thread that is waiting on the Interruptiblechannel is interrupted, the closedbyinterruptexception is thrown and the link is closed. Most standard channel are implemented Interruptiblechannel. selector Asynchronous IO。 If a thread is blocked when calling the Selector.select method, calling the close or wakeup method causes the thread to throw the Closedselectorexception and return early. Get a lock。 If a thread is blocked by waiting for a built-in lock, it will not be able to respond to the interrupt because the thread thinks it is sure to get the lock, so it will ignore the interruption. However, the lock class provides a lockinterruptibly method that allows you to still respond to interrupts while waiting for a lock.

4. Stop a thread-based service
One way to shut down producer consumer services is to use "poison pill" objects. "Poison pill" refers to putting an object on a queue and stopping it as soon as the consumer gets to the object. In the first-in first out queue, the poison pill object ensures that the consumer completes all the work in the queue before closing. Available only if the number of producers and consumers is known. 1. There is a need to stop multiple producers: Each producer puts a "poison pill" in the queue, and only stops when the consumer receives an n (producer number) "Poison pill" object. 2. The need to stop the situation of multiple consumers: producers to the queue into the N (consumer number) a "poison pill" object. Only when the number of producer consumers is not very large, and to be used in unbounded queues (if bounded, the operation of the poison pill is blocked, then the service will not be withdrawn)

5. Save the unfinished task after stopping the service. When you forcibly close the Executorservice by Shutdownnow, it attempts to cancel the task that is being performed and returns all tasks that have not been committed but have not yet started. What we need to do is: 1.shutdownNow returns the unfinished task saved. 2. Save the task being performed but canceled: One way is to define a Executorservice wrapper class A. It contains a Executorservice object. Exec executes a method such as executor () by delegating it to exec. The specific actions are as follows:
public class Trackingexecutor extends Abstractexecutorservice {
	//The Trackingexecutor method is delegated to exec to execute
	private Final Executorservice exec = Executors.newcachedthreadpool ();
	Private final set<runnable> Taskscancelledatshutdown = (set<runnable>) Collections.synchronizedcollection (New hashset<runnable> ());
	@Override public
	Void execute (Final Runnable command) {
		Exec.execute-new Runnable () {public
			void run () {
				//Key step, if the task is interrupted by Midway can intercept
				try{
					command.run ();
				} finally{
					if (IsShutDown () && Thread.CurrentThread (). isinterrupted ())
						taskscancelledatshutdown.add (command);}}
		);
	..
	Delegate all other methods of Trackingexecutor to exec to execute
	...
}

Summary: The lifecycle end issues in modules such as tasks, threads, services, and applications can increase the complexity of their design and implementation. Java does not provide some kind of steals mechanism to cancel an operation or terminate a thread. Instead, it provides a collaborative interrupt mechanism for canceling operations, but it depends on how the cancellation protocol is built and whether these protocols are followed. By using the Futuretask and executor frameworks, you can help us build tasks that can be canceled.

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.