1 /* Context switching within the JVM. */
3 /* Copyright (c) 2009-2019. 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/simix/smx_private.hpp"
16 extern JavaVM* __java_vm;
18 XBT_LOG_NEW_DEFAULT_CATEGORY(java, "MSG for Java(TM)");
24 ContextFactory* java_factory()
26 XBT_INFO("Using regular java threads.");
27 return new JavaContextFactory();
30 JavaContextFactory::JavaContextFactory() : ContextFactory()
32 xbt_assert(xbt_binary_name && strcmp(xbt_binary_name, "java") == 0); // Set by Java_org_simgrid_msg_Msg_init
35 JavaContextFactory::~JavaContextFactory()=default;
37 JavaContext* JavaContextFactory::create_context(std::function<void()>&& code, smx_actor_t actor)
39 return this->new_context<JavaContext>(std::move(code), actor);
42 void JavaContextFactory::run_all()
44 SerialThreadContext::run_all();
47 JavaContext::JavaContext(std::function<void()>&& code, smx_actor_t actor)
48 : SerialThreadContext(std::move(code), actor, false /* not maestro */)
50 /* ThreadContext already does all we need */
53 void JavaContext::start_hook()
55 Context::set_current(this); // We need to attach it also for maestro, in contrary to our ancestor
57 //Attach the thread to the JVM
59 XBT_ATTRIB_UNUSED jint error = __java_vm->AttachCurrentThread((void**)&env, nullptr);
60 xbt_assert((error == JNI_OK), "The thread could not be attached to the JVM");
64 void JavaContext::stop_hook()
66 JNIEnv* env = this->jenv_;
67 env->DeleteGlobalRef(this->jprocess_);
68 XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
69 if (error != JNI_OK) {
70 /* This is probably a Java thread, ie an actor not created from the XML (and thus from the C++),
71 * but from Java with something like new Process().start().
73 * We should not even try to detach such threads. Instead, we throw a Java exception that will raise up
74 * until run_jprocess(), IIUC.
76 jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError", "Process killed");
77 XBT_DEBUG("Cannot detach the current thread");
81 }}} // namespace simgrid::kernel::context