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("",5333,500000,200);

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

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]]@

(*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


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[]


(*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:

    public void run(){

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


            while (true){

                    //check if thread must be terminated
                    if(thExtSignal == true){
                         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++){
                }catch (InterruptedException e) {
                    //if the thread is interrupted then unsubscribe
                    // We've been interrupted: no more messages.
        catch(SocketTimeoutException e){
            //if timeout unsubscribe
            response = "timeOut";
        catch (IOException e) {
            pushedData = "error";


  • $\begingroup$ 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? $\endgroup$ Oct 21, 2013 at 18:52
  • $\begingroup$ 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. $\endgroup$
    – msalese
    Oct 21, 2013 at 19:01

2 Answers 2


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




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.

  • $\begingroup$ 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. $\endgroup$
    – msalese
    Oct 22, 2013 at 7:18
  • $\begingroup$ 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. $\endgroup$
    – msalese
    Oct 22, 2013 at 7:37

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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