其实分两部分,我们从一部分进入看下整个jit线程的建立的过程。
JNI_CreateJavaVM --》runtime->Start()
start函数里有这么一段代码。
if (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) {
std::string error_msg;
if (!IsZygote()) {
// If we are the zygote then we need to wait until after forking to create the code cache
// due to SELinux restrictions on r/w/x memory regions.
CreateJit();
} else if (jit_options_->UseJitCompilation()) {
if (!jit::Jit::LoadCompilerLibrary(&error_msg)) {
// Try to load compiler pre zygote to reduce PSS. b/27744947
LOG(WARNING) << "Failed to load JIT compiler with error " << error_msg;
}
}
}
如果不是zygote就启动jit。
void Runtime::CreateJit() {
CHECK(!IsAotCompiler());
if (kIsDebugBuild && GetInstrumentation()->IsForcedInterpretOnly()) {
DCHECK(!jit_options_->UseJitCompilation());
}
std::string error_msg;
jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg));
if (jit_.get() == nullptr) {
LOG(WARNING) << "Failed to create JIT " << error_msg;
}
}
调用Jit的Create函数。
Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
....
jit->hot_method_threshold_ = options->GetCompileThreshold();
jit->warm_method_threshold_ = options->GetWarmupThreshold();
jit->osr_method_threshold_ = options->GetOsrThreshold();
jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
jit->invoke_transition_weight_ = options->GetInvokeTransitionWeight();
jit->CreateThreadPool();
// Notify native debugger about the classes already loaded before the creation of the jit.
jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
return jit.release();
}
前面进行一些jit编译环境的参数和其他的操作,最终会调用jit->CreateThreadPool();进行创建jit线程。
void Jit::CreateThreadPool() {
...
thread_pool_.reset(new ThreadPool("Jit thread pool", 1));
thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
thread_pool_->StartWorkers(Thread::Current());
}
进行jit的建立。 其实还有第二部分,在Runtime::Start函数的另外一段代码:
if (is_zygote_) {
if (!InitZygote()) {
return false;
}
} else {
InitNonZygoteOrPostFork(self->GetJniEnv(),
/* is_system_server */ false,
action,
GetInstructionSetString(kRuntimeISA));
}
我们看下如果不是zygote也就是if 的下半部分。
void Runtime::InitNonZygoteOrPostFork(
JNIEnv* env, bool is_system_server, NativeBridgeAction action, const char* isa) {
if (!is_system_server &&
!safe_mode_ &&
(jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) &&
jit_.get() == nullptr) {
// Note that when running ART standalone (not zygote, nor zygote fork),
// the jit may have already been created.
CreateJit();
}
StartSignalCatcher();
Dbg::StartJdwp();
}
这里也会CreateJit ,这里说的是什么, 说的是一个进程可能不是由于zygote创建的,那么这里单独去创建jit。另外启动这个Jdwp调试线程。
到这里jit的建立就完成了。后面有时间和需求的话会对整个线程的工作原理做一个大篇幅的讲解。