Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

In the J/Link User Guide there is no example on how to use java.lang.Thread, from inside Mathematica.

I'd like to know if is possible to start a thread from a JavaNew object which has a Runnable interface implemented.

If I run this code from a java main class everything works fine. The Thread will run sampling bid/ask from a tcp/ip data stream and every time I need to know the bid/ask data I call the method that get me the value.

t3OpenT job01 = new t3OpenT("192.168.0.78",5333,500000,200);
        job01.openConnection();
        job01.setRequest("function=subscribe|item=MI.EQCON.1|schema=best_bsiz1;best_bid1;best_ask1;best_asiz1;symbol");
        job01.subscribeData();

System.out.println("now start the thread 01");
        Thread ntJob01 = new Thread(job01);
        ntJob01.setDaemon(true);
        ntJob01.setName("GENERALI");
        ntJob01.start();

But if I create the objects inside the notebook using JavaNew[....] and then start the thread it will execute but it is interrupted immediately.

Here is the mathematica code I use:

In[33]:= generaliGRT = t3OpenObjectT[{generaliG}]

Out[33]= {{"1", "G", JLink`Objects`vm1`JavaObject27681839799861249}}

(*Now we setup T3OpenObject to subscription:*)

In[34]:= generaliGRT[[1, 3]]@
 setRequest[
  "function=subscribe|item=MI.EQCON.1|schema=best_bsiz1;best_bid1;best_ask1;\
best_asiz1;symbol"]

(*subscribe the data on GENERALI stock*)

In[35]:= generaliGRT[[1, 3]]@subscribeData[];
generaliGRT[[1, 3]]@getResponse[]

Out[36]= "outcome=OK|item=MI.EQCON.1"

(*the response is OK so now we are redy to start the thread *)

In[37]:= th = JavaNew["java.lang.Thread", generaliGRT[[1, 3]]]

Out[37]= JLink`Objects`vm1`JavaObject8825827030466561

th@setDaemon[True]

In[39]:= th@setName["GENERALI"]

In[40]:= th@getName[]

Out[40]= "GENERALI"

In[41]:= th@start[]

In[42]:= th@getId[]

Out[42]= 14

(*the thread is immediately terminated *)
In[43]:= th@getState[]@toString[]

Out[43]= "TERMINATED"

(*but I can read the pusched stock date*) 
In[45]:= generaliGRT[[1, 3]]@getInfo[]

Out[45]= {"MI.EQCON.1", "18387", "17.19", "17.21", "14300", "G"}

and here is the run() method of T3OpenT class:

@Override
    public void run(){

        thExtSignal = false;
        refThread = Thread.currentThread();

        try{

            while (true){

                try{
                    //check if thread must be terminated
                    if(thExtSignal == true){
                        Thread.currentThread().interrupt();
                    }
                    if(Thread.interrupted()){
                         throw new InterruptedException();
                    }
                    //read data from buffer
                    this.pushedData = this.refBufReader.readLine();
                    //get the time stamp
                    dateTimeSample = dateFormat.format(cal.getTime()).toString();
                    //split the response end move data in a string vector
                    String responseBidAsk[] = pushedData.split("\\|", 6);
                    //update only elements tha are changed
                    for(int i=0 ; i<=responseBidAsk.length-1;i++){
                        if(responseBidAsk[i].length()>0){
                            info[i]=responseBidAsk[i];
                        }else{
                            info[i]=info[i];
                        }
                    }
                }catch (InterruptedException e) {
                    //if the thread is interrupted then unsubscribe
                    this.unsubscribe();
                    // We've been interrupted: no more messages.
                    return;        
                }
            }
        }   
        catch(SocketTimeoutException e){
            //if timeout unsubscribe
            response = "timeOut";
            unsubscribe();
        }
        catch (IOException e) {
            pushedData = "error";

        }

    }
share|improve this question
    
I don't know the first thing about Java, but I don't see why it shouldn't be possible. J/Link is just an interface to Java code running in the JVM, so if you can do it in Java, I suspect you should also be able to do it using J/Link. Have you tried? If so, what problems did you encounter? –  Oleksandr R. Oct 21 '13 at 18:52
    
Yes I've tried, seems that mathematica interrupts the thread as soon as it start. I'm trying to start the Thread inside the notebook. –  msalese Oct 21 '13 at 19:01
add comment

2 Answers

up vote 6 down vote accepted

Massimo, I have no problem with creating/starting/running/destroying threads explicitly using JLink:

Needs["JLink`"]

ReinstallJava[]

Do[
thread=JavaNew["java.lang.Thread"];
thread@start[];
Print@thread@getId[];
thread@sleep[10];
thread@stop[];
,{10}]

I've also shown several examples using explicit Java thread management with M code on the 2007 conference (programming a drum computer using sound samples. Every track runs in its own thread).

And you can use explicit Java code (as well as Scala, C#, and F# code, by the way) with my commercial product JVMTools. Here is the code compilation page. You can either a) put your Java, Scala, C#, or F# code into a string and get it compiled (if it doesn't compile, JVMTools exposes you the exact error messages that the compiler generates), and execute, or b) create a special cell in the M f/e specific to the type of the language you are using (again, Java, Scala, C#, or F#), and then just type your code away. It also features syntax highlighting, using the syntax highlighter from Leonid (which was included in JVMTools with his permission). Just look at the product page, there are many simple examples that show how it's working.

Disclaimer: JVMTools is a commercial product for M sold by Lauschke Consulting. I am the owner of Lauschke Consulting.

share|improve this answer
    
Thanks Andreas, so now I try to close the thread creation inside a Do block. But the strange think is that if I write a main-Class and run the code everything works fine. So I think that I'm missing somethink on mathematica side. –  msalese Oct 22 '13 at 7:18
    
Now I know the problem is SocketTimeoutException. Outside mathematica (using a java main class) this exception is never rised, but using J/Link is always raisen. –  msalese Oct 22 '13 at 7:37
add comment

Solved. The problem was with socketTimeOut, the value I used in mathematica was too low, but it was rigth in java main class. If I use a value of 500000 the TimeOut is never raised and the buffer has enough time waiting new data from tcp data server.

I modified the mathematica wrapper to java class costructor and added the Option soTimeOut:

In[21]:= generaliGRT = t3OpenObjectT[{generaliG}, SoTimeOut -> 500000]

Out[21]= {{"1", "G", JLink`Objects`vm1`JavaObject24868164546330625}}

In[72]:= generaliGRT[[1, 3]]@getRefSocket[]@getSoTimeout[]

Out[72]= 500000

Now when I start the thread it runs in background and let the notebook ready to do other stuffs:

In[73]:= generaliGRT[[1, 3]]@getInfo[]

Out[73]= {"MI.EQCON.1", "29819", "17.11", "17.13", "22493", "G"}

In[74]:= generaliGRT[[1, 3]]@getInfo[]

Out[74]= {"MI.EQCON.1", "29771", "17.11", "17.13", "20191", "G"}

In[75]:= generaliGRT[[1, 3]]@getInfo[]

Out[75]= {"MI.EQCON.1", "28924", "17.11", "17.13", "20191", "G"}

In[76]:= generaliGRT[[1, 3]]@getInfo[]

Out[76]= {"MI.EQCON.1", "29781", "17.11", "17.13", "20191", "G"}  

Thank you very much, some times one written word is enough to put someone on the rigth way

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.