Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
cleanups to the java actors
[simgrid.git] / src / bindings / java / JavaContext.cpp
1 /* Context switching within the JVM.                                        */
2
3 /* Copyright (c) 2009-2017. 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 <functional>
9 #include <utility>
10
11 #include "JavaContext.hpp"
12 #include "jxbt_utilities.h"
13 #include "src/simix/smx_private.h"
14 #include "xbt/ex.hpp"
15
16 extern "C" JavaVM* __java_vm;
17
18 XBT_LOG_NEW_DEFAULT_CATEGORY(jmsg, "MSG for Java(TM)");
19
20 namespace simgrid {
21 namespace kernel {
22 namespace context {
23
24 ContextFactory* java_factory()
25 {
26   XBT_INFO("Using regular java threads.");
27   return new JavaContextFactory();
28 }
29
30 JavaContextFactory::JavaContextFactory(): ContextFactory("JavaContextFactory")
31 {
32 }
33
34 JavaContextFactory::~JavaContextFactory()=default;
35
36 JavaContext* JavaContextFactory::self()
37 {
38   return static_cast<JavaContext*>(xbt_os_thread_get_extra_data());
39 }
40
41 JavaContext* JavaContextFactory::create_context(
42   std::function<void()> code,
43   void_pfn_smxprocess_t cleanup, smx_actor_t process)
44 {
45   return this->new_context<JavaContext>(std::move(code), cleanup, process);
46 }
47
48 void JavaContextFactory::run_all()
49 {
50   xbt_dynar_t processes = SIMIX_process_get_runnable();
51   smx_actor_t process;
52   unsigned int cursor;
53   xbt_dynar_foreach(processes, cursor, process) {
54     static_cast<JavaContext*>(SIMIX_process_get_context(process))->resume();
55   }
56 }
57
58 JavaContext::JavaContext(std::function<void()> code,
59         void_pfn_smxprocess_t cleanup_func,
60         smx_actor_t process)
61   : Context(std::move(code), cleanup_func, process)
62 {
63   static int thread_amount=0;
64   thread_amount++;
65
66   /* If the user provided a function for the process then use it otherwise is the context for maestro */
67   if (has_code()) {
68     this->jprocess = nullptr;
69     this->begin = xbt_os_sem_init(0);
70     this->end = xbt_os_sem_init(0);
71
72     try {
73        this->thread = xbt_os_thread_create(
74          nullptr, JavaContext::wrapper, this, nullptr);
75     }
76     catch (xbt_ex& ex) {
77       char* str = bprintf(
78         "Failed to create context #%d. You may want to switch to Java coroutines to increase your limits (error: %s)."
79         "See the Install section of simgrid-java documentation (in doc/install.html) for more on coroutines.",
80         thread_amount, ex.what());
81       xbt_ex new_exception(XBT_THROW_POINT, str);
82       new_exception.category = ex.category;
83       new_exception.value = ex.value;
84       std::throw_with_nested(std::move(new_exception));
85     }
86   } else {
87     this->thread = nullptr;
88     xbt_os_thread_set_extra_data(this);
89   }
90 }
91
92 JavaContext::~JavaContext()
93 {
94   if (this->thread) {
95     // We are not in maestro context
96     xbt_os_thread_join(this->thread, nullptr);
97     xbt_os_sem_destroy(this->begin);
98     xbt_os_sem_destroy(this->end);
99   }
100 }
101
102 void* JavaContext::wrapper(void *data)
103 {
104   JavaContext* context = static_cast<JavaContext*>(data);
105   xbt_os_thread_set_extra_data(context);
106   //Attach the thread to the JVM
107
108   JNIEnv *env;
109   XBT_ATTRIB_UNUSED jint error =
110     __java_vm->AttachCurrentThread((void **)&env, nullptr);
111   xbt_assert((error == JNI_OK), "The thread could not be attached to the JVM");
112   context->jenv = get_current_thread_env();
113   //Wait for the first scheduling round to happen.
114   xbt_os_sem_acquire(context->begin);
115   //Create the "Process" object if needed.
116   (*context)();
117   context->stop();
118   return nullptr;
119 }
120
121 void JavaContext::stop()
122 {
123   /* I was asked to die (either with kill() or because of a failed element) */
124   if (this->iwannadie) {
125     this->iwannadie = 0;
126     JNIEnv *env = get_current_thread_env();
127     XBT_DEBUG("Gonna launch Killed Error");
128     // When the process wants to stop before its regular end, we should cut its call stack quickly.
129     // The easiest way to do so is to raise an exception that will be catched in its top calling level.
130     //
131     // For that, we raise a ProcessKilledError that is catched in Process::run() (in msg/Process.java)
132     //
133     // Throwing a Java exception to stop the actor may be an issue for pure C actors
134     // (as the ones created for the VM migration). The Java exception will not be catched anywhere.
135     // Bad things happen currently if these actors get killed, unfortunately.
136     jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError",
137                        bprintf("Process %s killed from file JavaContext.cpp)", this->process()->name.c_str()));
138
139     // (remember that throwing a java exception from C does not break the C execution path.
140     //  Instead, it marks the exception to be raised when returning to the Java world and
141     //  continues to execute the C function until it ends or returns).
142
143     // Once the Java stack is marked to be unrolled, a C cancel_error is raised to kill the simcall
144     //  on which the killed actor is blocked (if any).
145     // Not doing so would prevent the actor to notice that it's dead, leading to segfaults when it wakes up.
146     // This is dangerous: if the killed actor is not actually blocked, the cancel_error will not get catched.
147     // But it should be OK in most cases:
148     //  - If I kill myself, I must do so with Process.kill().
149     //    The binding of this function in jmsg_process.cpp adds a try/catch around the MSG_process_kill() leading to us
150     //  - If I kill someone else that is blocked, the cancel_error will unblock it.
151     //
152     // A problem remains probably if I kill a process that is ready_to_run in the same scheduling round.
153     // I guess that this will kill the whole simulation because the victim does not catch the exception.
154     // The only solution I see to that problem would be to completely rewrite the process killing sequence
155     // (also in C) so that it's based on regular C++ exceptions that would be catched anyway.
156     // In other words, we need to do in C++ what we do in Java for sake of uniformity.
157     //
158     // Plus, C++ RAII would work in that case, too.
159
160     XBT_DEBUG("Trigger a cancel error at the C level");
161     THROWF(cancel_error, 0, "process cancelled");
162   } else {
163     Context::stop();
164     /* detach the thread and kills it */
165     JNIEnv *env = this->jenv;
166     env->DeleteGlobalRef(this->jprocess);
167     XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
168     xbt_assert((error == JNI_OK), "The thread couldn't be detached.");
169     xbt_os_sem_release(this->end);
170     xbt_os_thread_exit(nullptr);
171   }
172 }
173
174 void JavaContext::suspend()
175 {
176   xbt_os_sem_release(this->end);
177   xbt_os_sem_acquire(this->begin);
178 }
179
180 // FIXME: inline those functions
181 void JavaContext::resume()
182 {
183   xbt_os_sem_release(this->begin);
184   xbt_os_sem_acquire(this->end);
185 }
186
187 }}} // namespace simgrid::kernel::context