Logo AND Algorithmique Numérique Distribuée

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