Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2023.
[simgrid.git] / src / bindings / java / JavaContext.cpp
1 /* Context switching within the JVM.                                        */
2
3 /* Copyright (c) 2009-2023. The SimGrid Team. All rights reserved.          */
4
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. */
7
8 #include "JavaContext.hpp"
9 #include "jxbt_utilities.hpp"
10 #include "simgrid/Exception.hpp"
11 #include "src/kernel/actor/ActorImpl.hpp"
12
13 #include <functional>
14 #include <utility>
15
16 extern JavaVM* __java_vm;
17
18 XBT_LOG_NEW_DEFAULT_CATEGORY(java, "MSG for Java(TM)");
19
20 namespace simgrid::kernel::context {
21
22 JavaContextFactory::JavaContextFactory() : ContextFactory()
23 {
24   xbt_assert(xbt::binary_name == "java");
25 }
26
27 JavaContextFactory::~JavaContextFactory()=default;
28
29 Context* JavaContextFactory::create_context(std::function<void()>&& code, actor::ActorImpl* actor)
30 {
31   return this->new_context<JavaContext>(std::move(code), actor);
32 }
33
34 void JavaContextFactory::run_all(std::vector<actor::ActorImpl*> const& actors)
35 {
36   SerialThreadContext::run_all(actors);
37 }
38
39 JavaContext::JavaContext(std::function<void()>&& code, actor::ActorImpl* actor)
40     : SerialThreadContext(std::move(code), actor, false /* not maestro */)
41 {
42   /* ThreadContext already does all we need */
43 }
44
45 void JavaContext::start_hook()
46 {
47   Context::set_current(this); // We need to attach it also for maestro, in contrary to our ancestor
48
49   //Attach the thread to the JVM
50   JNIEnv *env;
51   xbt_assert(__java_vm->AttachCurrentThread((void**)&env, nullptr) == JNI_OK,
52              "The thread could not be attached to the JVM");
53   this->jenv_ = env;
54 }
55
56 void JavaContext::stop()
57 {
58   this->get_actor()->cleanup_from_self();
59
60   /* Unregister the thread from the JVM */
61   JNIEnv* env = this->jenv_;
62   env->DeleteGlobalRef(this->jprocess_);
63   jint error = __java_vm->DetachCurrentThread();
64   if (error != JNI_OK) {
65     /* This is probably a Java thread, ie an actor not created from the XML (and thus from the C++),
66      * but from Java with something like new Process().start().
67      *
68      * We should not even try to detach such threads. Instead, we throw a Java exception that will raise up
69      * until run_jprocess(), IIUC.
70      */
71     jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError", "Process killed");
72     XBT_DEBUG("Cannot detach the current thread");
73   }
74
75   simgrid::ForcefulKillException::do_throw(); // clean RAII variables with the dedicated exception
76 }
77
78 } // namespace simgrid::kernel::context