A two-level scheduling model for executor framework
In the model of the hotspot VM, the Java thread is mapped one-to-one to the local operating system thread. When the Java thread starts, a local operating system thread is created, and when the Java thread terminates, the corresponding operating system thread is also destroyed for recycling, and the operating system dispatches all the threads and assigns them to the available CPUs.
On the upper level, the Java program decomposes the application into multiple tasks, and then uses the application-level scheduler (Executor) to map these tasks to a fixed number of threads, and at the bottom, the operating system kernel maps these threads to the hardware processor.
Executor Frame class diagram
The Java thread described earlier is both a unit of work and an execution mechanism. In the executor framework, we separate the unit of work from the execution mechanism. Runnable and callable are units of work (commonly known as tasks), while execution mechanisms are provided by executor. In this way executor is based on the producer-consumer model, where the action of submitting the task equals the generator and the thread executing the task is the consumer.
1, from the class diagram, the executor interface is the basis of the asynchronous task execution framework, which can support many different types of task execution strategies.
public interface Executor {
void execute(Runnable command);
}
The executor interface provides an execution method, the task is the Runnbale type, and the callable type is not supported.
2, Executorservice interface realizes the executor interface, mainly provides the close thread pool and the Submit method:
public interface ExecutorService extends Executor {
List<Runnable> shutdownNow();
boolean isTerminated();
<T> Future<T> submit(Callable<T> task);
}
In addition, the interface has two important implementation classes: Threadpoolexecutor and Scheduledthreadpoolexecutor.
Where Threadpoolexecutor is the core implementation class of the thread pool, used to perform the task being committed, and Scheduledthreadpoolexecutor is an implementation class that can run a task after a given delay, or execute commands on a regular basis.
In the previous article, I used threadpoolexecutor to create my own thread pool by giving different parameters, but this was not recommended in later work, and it is recommended that you use the Exectuors factory method to create a thread pool.
Here are the two concepts that distinguish the thread pool and thread group (Threadgroup and Threadpoolexecutor):
A, a thread group represents a collection of threads.
B. The thread pool provides a solution to the thread's life cycle overhead and resource-poor issues, primarily for managing threads.
Executors can create 3 types of Threadpoolexecutor:
-
Singlethreadexecutor
-
Fixedthreadexecutor
-
Cachedthreadpool
A, Singlethreadexecutor: Single thread thread pool
ExecutorService threadPool = Executors.newSingleThreadExecutor();
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
From the source, we can see that the creation of a single thread pool is also through Threadpoolexecutor, the number of core threads and the number of threads is 1, and the work queue uses an unbounded queue. Because it is a single-threaded operation, only one task can be processed at a time, so all subsequent tasks are blocked in the work queue and can only be performed on a per-task schedule.
B, fixedthreadexecutor: Fixed size thread pool
ExecutorService threadPool = Executors.newFixedThreadPool(5);
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
This is similar to a single thread, and only creates a fixed-size number of threads.
C, Cachedthreadpool: no boundary pool
ExecutorService threadPool = Executors.newCachedThreadPool();
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
The no-boundary pool means that there is no work queue, the task comes in and executes, the number of threads is not enough to create, and the difference from the previous two is that the idle thread is recycled and the idle time is 60s. This applies to small programs that perform many short-term asynchrony or servers with less load.
Callable, future, Futuretash detailed
Callable and the future are introduced in subsequent versions of Java, callable similar to runnable interfaces, classes that implement callable interfaces, and classes that implement runnable, are tasks that can be performed by threads.
The relationship between three people:
-
The callable is a runnable encapsulated asynchronous operation task.
-
The future is used to save the results of callable asynchronous operations
-
Futuretask Package the future entity class
1. The difference between callable and Runnbale
The method defined by a, callable is call, and the method defined by Runnable is run.
B, the call method has a return value, and the Run method has no return value.
C, the call method can throw an exception, and the Run method cannot throw an exception.
2. Future
The future represents the result of asynchronous computation, and provides the following methods, mainly to determine whether the task is complete, interrupt the task, and get the result of the task execution.
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
3, Futuretask
An asynchronous computation that can be canceled, which provides a basic implementation of the future, only gets the results when the calculation is complete, and blocks the Get method if the calculation has not yet completed.
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>
Futuretask not only realizes the future interface, but also implements the Runnable interface, so it can not only futuretask as a task to executor to execute, but also through thread to create a thread.
Callable and Futuretask
Define a callable task:
public class MyCallableTask implements Callable<Integer>
{
@Override
public Integer call()
throws Exception
{
System.out.println("callable do somothing");
Thread.sleep(5000);
return new Random().nextInt(100);
}
}
public class Callabletest
{
public static void Main (string[] args) throws Exception
{
callable<integer> callable = new Mycallabletask ();
futuretask<integer> future = new futuretask<integer> (callable);
Thread thread = new thread (future);
Thread.Start ();
Thread.Sleep (100);
Attempt to cancel execution of this task
Future.cancel (TRUE);
Decide whether to cancel before the task is completed properly
System.out.println ("Future is cancel:" + future.iscancelled ());
if (!future.iscancelled ())
{
System.out.println ("cancelled");
}
To determine if a task has been completed
System.out.println ("Future was done:" + future.isdone ());
if (!future.isdone ())
{
System.out.println ("Future get=" + future.get ());
}
Else
{
Task is complete
SYSTEM.OUT.PRINTLN ("task is done");
}
}
}
Execution Result:
callable do somothing
future is cancel:true
future is done:true
task is done
This demo mainly demonstrates the change of state by invoking the Futuretask state setting method.
A, line 11th, attempts to cancel the execution of the task, the method if the task is completed, canceled returns FALSE, if you can cancel a task that has not yet completed, then return True, the demo because the task is still in hibernation, it can be canceled successfully.
future.cancel(true);
b, line 13th, determine whether the task was canceled successfully: Returns True if the task is canceled before it is completed properly
System.out.println("future is cancel:" + future.isCancelled());
C, line 19th, determine whether the task is complete: if the task is completed, returns True, and the following are the tasks completed: normal termination, exception, or cancellation.
In our demo, the task is done due to cancellation.
System.out.println("future is done:" + future.isDone());
D, in line 22nd, get the results of the asynchronous thread execution, I did not do this in this demo, it is important to note that the Future.get method blocks the current thread until the task execution finishes returning results.
System.out.println("future get=" + future.get());
Callable and future
public class Callablethread implements Callable<string>
{
@Override
Public String Call ()
Throws Exception
{
System.out.println ("Enter the call method, start hibernation, sleep time:" + system.currenttimemillis ());
Thread.Sleep (10000);
Return "Blackout Today";
}
public static void Main (string[] args) throws Exception
{
Executorservice es = Executors.newsinglethreadexecutor ();
Callable<string> call = new Callablethread ();
Future<string> fu = es.submit (call);
Es.shutdown ();
Thread.Sleep (5000);
System.out.println ("Main thread sleeps 5 seconds, Current time" + System.currenttimemillis ());
String str = Fu.get ();
System.out.println ("The future has received data, str=" + str + "; The current time is:" + system.currenttimemillis ());
}
}
Execution Result:
进入Call方法,开始休眠,休眠时间为:1478606602676
主线程休眠5秒,当前时间1478606608676
Future已拿到数据,str=今天停电;当前时间为:1478606612677
The future here is thrown directly into the thread pool to execute. Since the execution of the task is to be printed, the main thread, though dormant, is 5s, but from the call method to the result of the task, the time difference is exactly 10s, indicating that the Get method blocks the current thread until the task is completed.
The same effect can be achieved by Futuretask:
public static void main(String[] args) throws Exception
{
ExecutorService es = Executors.newSingleThreadExecutor();
Callable<String> call = new CallableThread();
FutureTask<String> task = new FutureTask<String>(call);
es.submit(task);
es.shutdown();
Thread.sleep(5000);
System.out.println("主线程等待5秒,当前时间为:" + System.currentTimeMillis());
String str = task.get();
System.out.println("Future已拿到数据,str=" + str + ";当前时间为:" + System.currentTimeMillis());
}
The above combination can bring us some changes:
If there is a scenario where method a returns a data that requires 20s for the code to run after the 10s,a method is executed, only the back 10s is dependent on the result of method a execution during this 20s execution. If in the same way as in the past, there is bound to be a 10s of time wasted, if the first two combinations, the efficiency will increase:
-
First, put the content of the A method into the call () method of the callable implementation class
-
Perform a task through the thread pool in the main threads
-
Executes code in the following method that does not rely on method A to run the result for 10 seconds
-
Gets the result of the run of method A, executing the code for 10 second dependency method A running result in the following method
This improves the efficiency of code execution, and the program does not have to be stuck in a method.
Java thread pool rationale (2)