1 /* Context switching within the JVM. */
3 /* Copyright (c) 2009-2022. The SimGrid Team. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include "JavaContext.hpp"
9 #include "jxbt_utilities.hpp"
10 #include "simgrid/Exception.hpp"
11 #include "src/kernel/actor/ActorImpl.hpp"
16 extern JavaVM* __java_vm;
18 XBT_LOG_NEW_DEFAULT_CATEGORY(java, "MSG for Java(TM)");
24 JavaContextFactory::JavaContextFactory() : ContextFactory()
26 xbt_assert(xbt::binary_name == "java");
29 JavaContextFactory::~JavaContextFactory()=default;
31 Context* JavaContextFactory::create_context(std::function<void()>&& code, actor::ActorImpl* actor)
33 return this->new_context<JavaContext>(std::move(code), actor);
36 void JavaContextFactory::run_all(std::vector<actor::ActorImpl*> const& actors)
38 SerialThreadContext::run_all(actors);
41 JavaContext::JavaContext(std::function<void()>&& code, actor::ActorImpl* actor)
42 : SerialThreadContext(std::move(code), actor, false /* not maestro */)
44 /* ThreadContext already does all we need */
47 void JavaContext::start_hook()
49 Context::set_current(this); // We need to attach it also for maestro, in contrary to our ancestor
51 //Attach the thread to the JVM
53 xbt_assert(__java_vm->AttachCurrentThread((void**)&env, nullptr) == JNI_OK,
54 "The thread could not be attached to the JVM");
58 void JavaContext::stop()
60 this->get_actor()->cleanup_from_self();
62 /* Unregister the thread from the JVM */
63 JNIEnv* env = this->jenv_;
64 env->DeleteGlobalRef(this->jprocess_);
65 jint error = __java_vm->DetachCurrentThread();
66 if (error != JNI_OK) {
67 /* This is probably a Java thread, ie an actor not created from the XML (and thus from the C++),
68 * but from Java with something like new Process().start().
70 * We should not even try to detach such threads. Instead, we throw a Java exception that will raise up
71 * until run_jprocess(), IIUC.
73 jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError", "Process killed");
74 XBT_DEBUG("Cannot detach the current thread");
77 simgrid::ForcefulKillException::do_throw(); // clean RAII variables with the dedicated exception
80 }}} // namespace simgrid::kernel::context