JNI communiction using a Java and a C++ Thread

Hi,
My purpose is to run a Java and a C++ thread parallel.
The C++ thread receives events from a hardware. Getting an event it should put this (for testing it is just a String ) to a Java method (there the events will be collected in a vector).
The Java thread should compute these vector step by step when it is scheduled.
Therefore I have a Java Thread that invokes a native method.
This C++ method
1. stores a refernece to the JavaVM in a global var (using env->getJavaVM ),
2. stores the object (given by JNICall) in a global var (reference to the calling java object),
3. creates an object dynamically (this implements a Runnable C++ Interface needed for my Thread structure)
4. and creates (dynamically) and starts a C++ Thread ( that uses the Win API ) giving it the former created object as parameter.
Following the C++ thread uses the former stored global JavaVM to get a JNIEnv. It also uses the global stored object.
After this I prepare for executing a callback to Java, e.g. AttachCurrentThread, GetObjectClass, GetMethodID and so on. Finally I sucessfully start some callbacks to Java (in the while loop of the thread).
Now here is my Problem:
The described way only works for a few calls and then raises an error. "java.exe hat ein Problem festgestellt und muss beendet werden." (german os) (In english it should be: "java.exe has detected a problem and has to be determined").
What is wrong with my idea. It is something with the scope of my dynammically created objects? If have no idea anymore.
Here the source code (C++ part):
#include <jni.h>
#include "benchmark.h"
#include "bench.h"
#include "canMessage.h"
JavaVM *jvm;
jobject javaObject;
JNIEXPORT void JNICALL Java_Benchmark_startBench(JNIEnv *env, jobject obj, jobject obj2){
     env->GetJavaVM(&jvm);
     javaObject = obj2;
     cout << "\n C++ Starting benchmark\n\n";
     Benchmark *bm = new Benchmark();
     Thread *thread = new Thread(bm);
     thread->start();
     //thread->join(); //uncomment this there will be no error but also
                                     // no java thread doing it's job
Benchmark::Benchmark(): _continue(false) {
Benchmark::~Benchmark(){
unsigned long Benchmark::run(){
     _continue = true;
     JNIEnv *jniEnv;
        jvm->AttachCurrentThread((void **)&jniEnv, NULL);
        jclass javaClass = jniEnv->GetObjectClass(javaObject);
     if(javaClass == NULL){
          cout << "--> Error: javaClass is null";
     jmethodID methodId = jniEnv->GetMethodID(javaClass, "addMessage", "(Ljava/lang/String;)V");
     if(methodId == NULL){
          cout << "--> Error: methodId is null";
     string str ("This is a test text.");
     const char *cStr = str.c_str();
     jstring javaString = jniEnv->NewStringUTF(cStr);
     jniEnv->CallVoidMethod(javaObject, methodId, javaString );
     int i_loopCount = 0;
     while(_continue){
          i_loopCount++;
          cout << i_loopCount << " C++ runing\n";
          jniEnv->MonitorEnter(javaObject);
          jniEnv->CallVoidMethod(javaObject, methodId, javaString );
          jniEnv->MonitorExit(javaObject);
          canMessage = new CANMessage();
          delete canMessage;
          canMessage = NULL;
     return 0;
void Benchmark::stop(){
     _continue = false;
}Is there a better and more elegant way to solve my problem?
Thanks!

At
http://codeproject.com/cpp/OOJNIUse.asp
http://www.simtel.net/product.php[id]93174[sekid]0[SiteID]simtel.net
http://www.simtel.net/product.php[id]94368[sekid]0[SiteID]simtel.net
you will find examples how to implement Java Interface in JNI C++ without Java coding.
At
http://www.simtel.net/product.php[id]95126[sekid]0[SiteID]simtel.net
you can get pure JNI interface for DOTNET.

Similar Messages

  • Wrong use of Java and Mysql?

    I currently have a dedicated database server which runs MySQL. On the MySQL server I have 15 tables with the InnoDB engine.
    These tables all have a column called "last_sync". Whenever a tablerow is updated by a java client, the "last_sync" column is refreshed.
    Other java clients will query these tables with a query that looks something like this
    "Select count(*) from table where last_sync > (currenttime-5 seconds) and last_sync <= (currenttime)"
    So much for the background info. To stresstest my server, and see how much queries per second he can handle,
    I installed Super Smack (http://vegan.net/tony/supersmack/). Super smack is a stresstest tool which can be given 2 start-up parameters.
    These parameters say how many clients/threads should connect and how many times the query should be ran. When installed it
    is possible to alter the stress query by editting the "select-key.smack" file. I did so and placed a query that is equal to the above statement.
    Super-smack (as well as MySQL Administrator and Innotop) tells me that it can execute 50K queries per second when I use a single connection.
    When I use two connections I get roughly 88K. This is logical since my server is a dual-core machine. I run super smack on my DB server.
    Now, whenever I try to stresstest my server with a java written test, I can barely get to 10k queries per second on a single connection.
    The app is being runned on the DB server as well. Furthermore when I add another connection, the limit stays at 10k queries.
    When monitoring the connection threads with MySQL Administrator the connection threads
    are often "sleeping" while, when I run the SuperSmack test they are constantly in use.
    Another detail, the connection threads also gives info what it's doing ("Executing query", "Writing to net" etc.). I occasionally see "Rollback", which is strange
    since my stress query is not failing in my stress application.
    To make this complete, I've uploaded my little test along with the SQL creation code to the following URL: HERE
    It should work straight out of the box. Naturally the table creation query should be ran and the connection settings specified in the java file.
    Basically the one thing I cannot understand is why supersmack runs a factor 5-8 faster than my java test while they are
    using the exact same table and are executed on the exact same machine. This however limits out the possibility of it being a database config setting.
    Im personally guessing im incorrectly using transactions or the MySQL connector/j is giving problems.
    I understand this might take some effort, so i'll try to add more dukes than a regular post.
    -Edit. Was under the assumption that you could add more than 10 duke points.
    Thanks in advance
    Edited by: killingdjef on Mar 25, 2009 6:52 AM
    Edited by: killingdjef on Mar 25, 2009 10:28 AM

    killingdjef wrote:
    10K can be perfect, however, when I run Supersmack and see that my database server can handle 8 times more queries per second on the exact same table with the exact same query,
    I'm beginning to wonder if im doing something incorrect or if i'm missing something crucial.
    I have no clue whats a reasonable amount of queries per second is for a dedicated innodb server
    but based on the benchmark test im thinking I can squeeze out more.
    The stresstest isnt representational for a single client. Its merely a simulation how many clients could be served.
    The higher the queries per second, the more clients that can be served. Im trying to find out what the limit would be.I am quite aware of what impact means in terms of client processing. That however isn't the point. The point is that you intend to serve a market of some sort and support some reasonable growth. It is pointless to try to do more than that.
    If you have enough "clients" running directly against that database to generate 10k queries a second then your architecture (and thus design and implementation) is very likely flawed.
    For example
    1. What happens to all of those clients when the database goes down either accidently or on purpose?
    2. Those clients are hitting the database direct, and I don't see how you are going to get enough clients like that without internet consumers. And you absolutely do not want to expose the database that way.
    3. Conversely say you have a call center with 2000 support people, which is a huge call center. There is no way that number could generate even close to 10k a second.
    4. A comparable txn business model is credit card processing and a sustained speed like that would be sufficient to handle all of the credit card transaction business in the US during the peak xmas season. With extra left over.
    Not to mention that you didn't address the network problem at all. Note that the numbers I outlines above doesn't allow any bandwidth for the data to get into the server in the first place.
    And inserts will take more time than queries.
    But as I already said, if you are using transaction then that will have an impact. Connections/threads will as well.

  • Anyone Update Date/Timestamp using CachedRowSets, Java and Oracle 10g

    How to do this...
    a very small, direct snippet of code would be great..
    or direct me to a CURRENT document.
    Thanks

    What will I get back from Oracle with TO_CHAR?
    I am using a quoted string and supplying parameters.
    In other words, when I do the date comparison with a TO_DATE I already know that I am getting 12:00:00 AM back and the paramter I can manipulate.
    Example:
    TO_DATE(datefield) = formattedDateParameter
    The "TO_DATE(datefield)" is part of my prepared sql statement.
    I am not sure how much manipulation of the where clause I can do.
    My querystring would look like the following.
    sql = "SELECT " + REPORTTRANSDATE + REPORTRETURNCODE + " FROM " + REPORTTABLE + " WHERE " + REPORTD + "=?" + " AND " + "TO_DATE(" + REPORTTRANSDATE + ")" + ">=?" + " AND " + "TO_DATE(" + REPORTTRANSDATE + ")" + "<=?" + " ORDER BY " + REPORTTRANSDATE;
    Thanks.

  • Using Safari & Java from Spain

    To anyone who may have knowledge of Java/Safari in Spain or Europe.
    I am currently studying abroad in Spain and i have noticed that my computer and others have been having troubles using the Java Script for Facebook, Yahoo, Pogo.com and other sources. We currently run a slightly out of date wireless network based off PCs; However, PCs are having the same issues.
    Does anyone know if Spain or Europe doesn't use Java as much. And does anyone know if Proxies are affect the use of Java and if so, where can i enter proxy information to fix the issue.
    Thank you to anyone who replies.

    I was thinking about my problem some more and i was
    wondering if you or anyone knew how to set proxies
    for Java. For example, yes, you can set proxies under
    settings/network and you can set proxies in Firefox,
    iChat, and more. Is there a way for Java?
    Java is not a protocol, it's an application framework. It communicates using protocols in your ip stack. You can set proxies for those protocols. I suspect you mean javascript, but the same applies there, except that it's all http. I don't want to get into rudimentary aspects of networking, I'm sure you can find very good references.
    What's really interesting is that you seem to be implying that there is some sort of censorship of web sites in Spain - just like in China. And that you're looking for a what's known as a circumventor. I know that there was a recent ruling in the Spanish counrts that judges could block web sites they found to be a threat to national defense. Is this perhaps what you're seeing?

  • What are these and what are they useful for?: and

    I have seen these symbols being used in Java: << and >>, what are they and what do they do?
    Thank you.

    As DrQuincy asks how is this of use over multiplying
    and dividing?In your processor there are often different instructions for shifting, multiplying, and deleteing. Typically the shifting instructions take less time to execute and so using the shifting operator will be faster than multiplying. This assumes the compiler doesn't recognize the situation and optimize it out though.
    The >>,<<,>>>, &,|,and ^ operators are mainly useful when you need to deal with individual bits of data. For instance if you are talking to another system (thats not java) that uses a different method of storing numbers (little endian/big endian etc.), or doing something such as creating parity data for error correction. There are lots of things to do, but most a low level and its rare when you need to use them.

  • File name that exports enlarges itself using   dmexpimpdemo.java

    Hi everyone,
    When I use dmexpimpdemo.java and I send to export putting him a name file this is kept me with the name enlarged 001, my question is like I can do so that be kept me with the name that I put him without 001
    Example ----------> FileName
    it is kept like ------->     FileName001
    I appreciate your aids.

    Export uses the user supplied file name as prefix and appends suffixes to those files. As the exported content can be in multiple-files it does this way.
    Hope this helps
    Sunil

  • Personal Java and Jeode??

    Once there is no Personal Profile available for Windows platforms, one solution I've heard about is using Personal Java and Jeode VM.
    As I can see, Jeode is a very good VM and supports some versions of standards Java versions..and Personal Java is no longer supported by Sun, but it's functional.
    Is there anybody who knows wich versions are usable? Looks like jdk 1.1.8..is there one newer?
    Any help appreciated.
    Thanks
    Ricardo

    There is a certified Win32 (and PocketPC) version of Personal Profile available with IBM's WSDD 5.6 Tech Preview. See:
    http://www-3.ibm.com/software/wireless/wsdd/upgrades_migrations.html

  • How not to use Cold Fusion and Java

    Overview
    This write up is intended to give java developers that are
    developing ColdFusion applications some beneficial information:
    things that are not documented.
    Scenario
    The company builds enterprise class web application software
    for fortune 500 companies. It had purchased a CF 7 based product,
    had and existing proprietary J2EE based product, and needed to
    integrate the two while meeting a host of new requirements. These
    requirements were based on delivering a better user experience,
    faster / cheaper integration, increased flexibility /
    configuration, useablily, decreasing maintenance costs, the ability
    to deploy in either install or ASP models. An initiative was
    started to create a new framework that integrated the best of each
    technologies. Tactically, this meant that we were to build a hybrid
    CF and java application: one that used building blocks (decoupled /
    cohesive components) that would allow applications to be rapidly
    assembled, configured and deployed. This made sense on several
    levels, the team was composed of Java and CF developers, the CF
    rapid application development was very productive, there is great
    functionality delivered in the CF platform and initial performance
    tests showed no cause for alarm
    The agreed upon design, based on requirements, and analysis
    by both the CF and Java staff has us using CF in the presentation
    layer, using a CF based MVC, use of CF based web services. The MVC
    was deployed using CFC inheritance for model objects and views made
    use of CF custom tags. The internals of the application, used a
    rules engine, some proprietary java, ORM, and other J2EE
    technology. The initial performance of the system was reasonable.
    We pushed on with product implementation.
    Then it was time to load test the application, and tune it.
    Under load the response times were orders of magnitude slower,
    sometimes the pages even timed out.
    Armed with our profiler, oracle execution plans and we
    charged ahead addressing issue after issue. Note that we took
    meticulous care in tweaking the active thread pool and ensuring
    that our CF setup was tuned for our application. None of the
    observations here are a condemnation of the language; rather they
    are aspects that, when considered together, not conducive for
    building integrated java and CF frameworks that use a structured /
    OO programming practices. Further detail can be provided on
    request.
    CFC inheritance should be avoided - resolution of variable
    scope is expensive even if properly declared.
    Since CF creates a class per method under the covers call
    stacks become very large, especially if used in a loop. This is
    nominally exacerbated by CF calls necessary to set up for the
    method call (String.toUpper()).
    Nesting of loops and if statements should be kept to a
    minimum - the conditional for each lookup of logical operator like
    LT, GT are synchronized. Under load this results in thread waits.
    Jrun has as single thread pool - both http and web service
    requests use the same pool. Under load this leads to thread
    deadlock. There are work arounds, but they are painful.
    Recursion should be avoided - we had a few recursive routines
    and these had to be rewritten.
    Custom Tags - should be used sparingly - each custom tag
    makes a synchronized call to the license server - (This may be
    fixed in CF 8)
    Summary
    In the end we got the performance to reasonable numbers, but
    we ended up moving some code to java (Custom Tags) and getting rid
    of 'good programming' practices (Inheritance, loops, etc), mandated
    proper variable scoping for those things left over. We prototyped a
    sans cold fusion implementation and had an order of magnitude
    improvement in performance and number of requests served per
    second.
    The lesson? Use Coldfusion in its sweet spot: make a query,
    iterate over the results and format for display. Extensive use of
    structure programming techniques or OO CFCs should be avoided: they
    will work but under load - but are better as a prototype. Building
    frameworks in CF? Think twice, no three times, and, if you must, be
    minimalist.
    Text

    interesting aslbert123,
    Not that I doubt you, but could you answer some questions
    about your implementation that was so slow:
    1.) Did you put your CFCs in the application or server scope?
    2.) Were you initializing your CFCs, via CreateObject or
    <cfinvoke>, on every request?
    3.) Are you sure that you were properly Var'ing every
    variable in your methods? (people typically forget about query
    names and loop iterator variables)
    4.) Could you give examples of how your inheritence was set
    up?
    5.) For CustomTags, did you call them the old <cf_tag>
    way or the newer, better-performing <cfimport> way?
    6.) How did you connect CF to Java exactly?
    Thanks,
    Aaron

  • Use of Java Swing +Applescript to move and resize Mac OS X windows using

    Here is an interesting use of Java on Mac OS X and Applescript to
    enable moving and resizing of windows using mouse and keyboard:
    [MoveResize tool|http://code.google.com/p/sandipchitalesmacosxstuff/#Move_and_resize_windows_on_Mac_OS_X]
    How it works:
    The implementation uses Applescript to get the front most window and
    it's bounds. It sends the bounds rectangle to a server implemented in
    Java over a socket connection. The Java server takes the screen shot
    of the full Desktop and uses it as the Image label (a JLabel with
    ImageIcon) as the content pane of an undecorated JFrame which has the
    same bounds as the Desktop. A JPanel with semitransparent background
    and a dark rounded rectangular border is given the same bounds that
    were received over the socket. This JPanel is added to the
    PALETTE_LAYER of the JFrame's layered pane - which makes it appear
    floating in front of the front window. A Mouse and a Key listener
    added to the JPanel allow moving and resizing of the JPanel. When the
    user types the ENTER key the JFrame is hidden and the new bounds of
    the JPanel are sent back to the Applescript over the socket connection
    which moves and resizes the front most window.
    Enjoy!
    Sandip
    Edited by: chitale on May 14, 2009 4:12 AM

    Copy the /Home/Documents/ folder to the NAS drive. That drive needs to support AFP or you may run into filename problems and/or other file related problems due to filesystem differences.
    Once the folder has been moved to the NAS select the folder on the NAS and CTRL- or RIGHT-click. Select Make Alias from the drop down menu. You should now have an alias named "Documents alias." On the Mac put the /Home/Documents/ folder in the Trash but don't delete it. Copy the alias file from the NAS to the /Home/ folder. Rename it to simply "Documents." Double-click on it to be sure it opens the folder on the NAS. If so you can empty the Trash. You're done.

  • Why can't I use WebCT chat with my computer?  I get the 'spiral of death' every time I try to type in my chat.  I have a feeling it has to do with compatibility issues between Java and Tiger.

    Why can't I use WebCT chat with my computer?  I get the 'spiral of death' every time I try to type in my chat.  I have a feeling it has to do with compatibility issues between Java and Tiger.

    Hi Elizabeth,
    Do your Mac meet any of these requirements?
    http://www.wvnet.edu/services/webct/requirements.html
    From this it appears to be PC only!???
    http://sourceforge.net/projects/awebctcclient/files/Pancake%20%28it%20own%20proj ect%20now%29/Pancake%20Console%20V1.0.0/PancakeConsole-1.0.0-src.zip/download
    Can you provide any more info on which bersion or file you have?
    Can you tell us why you need this for your use?

  • What is the use vss in java and how to use it?

    can i know what is vss in java and how to use it and also can you tell me related vss like svs?
    and what are tools for configuration in real we will use?
    am i student i want to know these all?

    jduprez wrote:
    You do not need to know them all, but one for sure, since it is a must for multi-developer team.8o( ?????
    It is a must. Period.
    OK, let's tone down: it is a must for any job related to software production. Not only development.That begsl the question, What does it mean to "know" one of these systems? I would expect Product Management, Documentation, QA, and Support staff to be conversant with the fundamentals of such a tool--check in, check out, version/revision numbers--but not much more than that. Developers, on the other hand, I would generally expect "know" the system with a much higher level of expertise--query language, branching, merging, and so on.

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • How to change the parameter 'Default Servers To Use For Viewing And Modification' using java api dynamically.

    Hi,
    I need to change the Crystal Reports setting 'Default Servers To Use For Viewing And Modification' to a particular server.this i need to do using java api.
    could you pls provide me the sample code for this.
    Regards
    Srinivas

    The IReport interface extends IViewingServerGroupInfo interface, that allows you to specify the server group. 
    The choice selection for that interface is as follows:  0 = first available, 1 = prefer the selected server group, and 2 =  only use the selected server group.
    The server group selection is by the SI_ID for that server group InfoObject.
    Sincerely,
    Ted Ueda - Developer Support

  • How to create two level dynamic list using JSP , Java Script and Oracle

    I am new in JSP. And i am facing problem in creating two level dynamic list using JSP ,Java Script where the listdata will come from Oracle 10g express edition database. Is there any easy way in JSP that is available on in ASP.NET.
    Plz response with details.

    1) Learn JDBC API [http://java.sun.com/docs/books/tutorial/jdbc/index.html].
    2) Create DAO class which contains JDBC code and do all SQL queries and returns or takes ID's or DTO objects.
    3) Learn Servlet API [http://java.sun.com/javaee/5/docs/tutorial/doc/].
    4) Create Servlet class which calls the DAO class, gets the list of DTO's as result, puts it as a request attribute and forwards the request to a JSP page.
    5) Learn JSP and JSTL [http://java.sun.com/javaee/5/docs/tutorial/doc/]. Also learn HTML if you even don't know it.
    6) Create JSP page which uses the JSTL c:forEach tag to access the list of DTO's and iterate over it and prints a HTML list out.
    You don't need Javascript for this.

  • Devloping graphs using pure java without applets and swings

    Hi Guys
    i want to devlop bar graphs,pie charts,line graphs using pure java.i don't want to use applets and swings..does any body help on this asap..
    IT'S VERY URGENT
    cheers
    ANAND

    Go to
    http://java.sun.com/docs/books/tutorial/information/download.html#OLDui
    and get: Creating a User Interface (AWT Only) Archive (tut-OLDui.zip)

Maybe you are looking for

  • My Bill Payment became so high all of a sudden after renewing!

    Around November 3 I reneweg my account for another 2 years getting some upgrade and discounts in the process. Before I renewed was paying about $165 per month for my three fios services. Around late November my upgrades and discounts would take affec

  • No sound in PE 7

    I have no sound while working with video or .wma files. My audio meter shows sounds, but noting out my speakers. I search the forums and tried everything that I can find in them to no success. I have also tried reinstalling and that didn't correct th

  • Dynamic LoadVars expression

    HI All, I am writing actionscript to get variables from a database using php. I have used the LoadVars object and can set a variable using the following line of code which works _root.show1=myLoadVar.display1 In this case myLoadVar is an instance of

  • Problems with cropping in Raw editor- Photoshop CS6. Help!

    When I use raw editor in Photoshop CS-6 and I wish to crop the image. When doing this the crop box is at a fixed aspect ratio. How to I change it so my crop box is unconstrained? Just make sure this is in raw editor not Photoshop. My photos were take

  • Adobe CS2 uninstall (as administrator, no antivirus) fails on Windows with "Missing or Invalid Personalization Information", "Missing resources library"

    My previously fully functional Adobe CS2 install on Windows 7 x64 stopped working when the activation service for CS2 was shut down. I tried to follow the re-installation instructions at the following web page which first require a complete uninstall