Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr/gitroot/simgrid/simgrid
[simgrid.git] / src / bindings / java / JavaContext.cpp
1 /* context_java - implementation of context switching for java threads */
2
3 /* Copyright (c) 2009-2010, 2012-2014. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include <functional>
10 #include <utility>
11
12 #include <xbt/function_types.h>
13 #include <simgrid/simix.h>
14 #include <xbt/ex.h>
15 #include "JavaContext.hpp"
16 #include "jxbt_utilities.h"
17 #include "xbt/dynar.h"
18 #include "../../simix/smx_private.h"
19 extern JavaVM *__java_vm;
20
21 XBT_LOG_NEW_DEFAULT_CATEGORY(jmsg, "MSG for Java(TM)");
22
23 namespace simgrid {
24 namespace java {
25
26 simgrid::simix::ContextFactory* java_factory()
27 {
28   XBT_INFO("Using regular java threads.");
29   return new JavaContextFactory();
30 }
31
32 JavaContextFactory::JavaContextFactory(): ContextFactory("JavaContextFactory")
33 {
34 }
35
36 JavaContextFactory::~JavaContextFactory()=default;
37
38 JavaContext* JavaContextFactory::self()
39 {
40   return static_cast<JavaContext*>(xbt_os_thread_get_extra_data());
41 }
42
43 JavaContext* JavaContextFactory::create_context(
44   std::function<void()> code,
45   void_pfn_smxprocess_t cleanup, smx_process_t process)
46 {
47   return this->new_context<JavaContext>(std::move(code), cleanup, process);
48 }
49
50 void JavaContextFactory::run_all()
51 {
52   xbt_dynar_t processes = SIMIX_process_get_runnable();
53   smx_process_t process;
54   unsigned int cursor;
55   xbt_dynar_foreach(processes, cursor, process) {
56     static_cast<JavaContext*>(SIMIX_process_get_context(process))->resume();
57   }
58 }
59
60 JavaContext::JavaContext(std::function<void()> code,
61         void_pfn_smxprocess_t cleanup_func,
62         smx_process_t process)
63   : Context(std::move(code), cleanup_func, process)
64 {
65   static int thread_amount=0;
66   thread_amount++;
67
68   /* If the user provided a function for the process then use it otherwise is the context for maestro */
69   if (has_code()) {
70     this->jprocess = nullptr;
71     this->begin = xbt_os_sem_init(0);
72     this->end = xbt_os_sem_init(0);
73
74     try {
75        this->thread = xbt_os_thread_create(
76          nullptr, JavaContext::wrapper, this, nullptr);
77     }
78     catch (xbt_ex& ex) {
79       char* str = bprintf(
80         "Failed to create context #%d. You may want to switch to Java coroutines to increase your limits (error: %s)."
81         "See the Install section of simgrid-java documentation (in doc/install.html) for more on coroutines.",
82         thread_amount, ex.what());
83       xbt_ex new_exception(str);
84       new_exception.category = ex.category;
85       new_exception.value = ex.value;
86       new_exception.file = __FILE__;
87       new_exception.line = __LINE__;
88       new_exception.func = __func__;
89       std::throw_with_nested(std::move(new_exception));
90     }
91   } else {
92     this->thread = nullptr;
93     xbt_os_thread_set_extra_data(this);
94   }
95 }
96
97 JavaContext::~JavaContext()
98 {
99   if (this->thread) {
100     // We are not in maestro context
101     xbt_os_thread_join(this->thread, nullptr);
102     xbt_os_sem_destroy(this->begin);
103     xbt_os_sem_destroy(this->end);
104   }
105 }
106
107 void* JavaContext::wrapper(void *data)
108 {
109   JavaContext* context = static_cast<JavaContext*>(data);
110   xbt_os_thread_set_extra_data(context);
111   //Attach the thread to the JVM
112
113   JNIEnv *env;
114   XBT_ATTRIB_UNUSED jint error =
115     __java_vm->AttachCurrentThread((void **)&env, nullptr);
116   xbt_assert((error == JNI_OK), "The thread could not be attached to the JVM");
117   context->jenv = get_current_thread_env();
118   //Wait for the first scheduling round to happen.
119   xbt_os_sem_acquire(context->begin);
120   //Create the "Process" object if needed.
121   (*context)();
122   context->stop();
123   return nullptr;
124 }
125
126 void JavaContext::stop()
127 {
128   /* I am the current process and I am dying */
129   if (this->iwannadie) {
130     this->iwannadie = 0;
131     JNIEnv *env = get_current_thread_env();
132     XBT_DEBUG("Gonna launch Killed Error");
133     // TODO Adrien, if the process has not been created at the java layer, why should we raise the exception/error at the java level (this happens
134     // for instance during the migration process that creates at the C level two processes: one on the SRC node and one on the DST node, if the DST process is killed.
135     // it is not required to raise an exception at the JAVA level, the low level should be able to manage such an issue correctly but this is not the case right now unfortunately ...
136     // TODO it will be nice to have the name of the process to help the end-user to know which Process has been killed
137    // jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError", bprintf("Process %s killed :) (file smx_context_java.c)", MSG_process_get_name( (msg_process_t)context) ));
138     jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError",
139       bprintf("Process %s killed :) (file JavaContext.cpp)",
140       simcall_process_get_name(this->process()) ));
141     XBT_DEBUG("Trigger a cancel error at the C level");
142     THROWF(cancel_error, 0, "process cancelled");
143   } else {
144     Context::stop();
145     /* detach the thread and kills it */
146     JNIEnv *env = this->jenv;
147     env->DeleteGlobalRef(this->jprocess);
148     XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
149     xbt_assert((error == JNI_OK), "The thread couldn't be detached.");
150     xbt_os_sem_release(this->end);
151     xbt_os_thread_exit(nullptr);
152   }
153 }
154
155 void JavaContext::suspend()
156 {
157   xbt_os_sem_release(this->end);
158   xbt_os_sem_acquire(this->begin);
159 }
160
161 // FIXME: inline those functions
162 void JavaContext::resume()
163 {
164   xbt_os_sem_release(this->begin);
165   xbt_os_sem_acquire(this->end);
166 }
167
168 }
169 }