RingJavafor Ring

Callbacks and threads

Ring code that Java runs#

Where a Java method wants an interface (Runnable, Comparator, Function, Predicate, ActionListener, your own interface), pass the text: the name of a Ring function or Ring code. As in RingDotNet, there is nothing to wrap:

Ring
oList.sort("byLength")

func byLength aArgs
	return len(aArgs[1]) - len(aArgs[2])

The text "byLength" names a Ring function. Java calls it with one list: the arguments of the Java method. The value it returns is the Java result (converted to the return type; for a void method it is ignored). The global cJavaMethod has the name of the Java method that was called (an interface with several methods calls the same function, one call for each method).

A text that is Ring code (not a function name) runs the code with aJavaArgs, cJavaMethod and xJavaResult:

Ring
oList.sort("xJavaResult = aJavaArgs[2] - aJavaArgs[1]")

Objects that Java passes (an ActionEvent...) arrive as Ring objects of their classes. A Ring error in a callback becomes a Java RuntimeException (the message has the text of the Ring error), so it reaches the Ring program as a Java exception. A text becomes a callback only where the parameter is an interface that Ring can implement: a functional interface (Runnable, Comparator, Predicate ...) or a listener whose methods return nothing (ActionListener, MouseListener ...). Where a method also has a String parameter that fits, the text is a String: new Thread("work") names a thread, so for a thread write new Thread(jCallback("work")). jCallback(text) is the explicit form: use it there, and to keep a callback in a variable or to pass it inside a list. Default methods of the interface (Comparator.reversed) run in Java; use jCallbackAll to route them to the Ring function too.

Threads#

The Ring program runs on one thread and Ring is not thread safe. When Java calls a Ring callback:

Ring
oThread = new Thread(jCallback("work"))        # a Thread also has a String constructor (the name): jCallback says that it is code
oThread.start()
jJoin(oThread)                       # not oThread.join(): that blocks the Ring program and the callback could never run

oFuture = oPool.submit("compute")
jWaitUntil("futureDone",5000)        # a Ring function that returns true when it is done
? oFuture.@get()

Blocking calls of Java (Thread.join, Future.get, CountDownLatch.await, Thread.sleep) block the Ring program. When no thread needs a callback they are fine; when one does, use the helpers above or poll (isDone(), isAlive(), getCount()).

Windows and event handlers of Swing run on the event thread of Java (another thread): the Ring program keeps the application alive with a loop that pumps, while oFrame.isVisible() jPump(20) end (see Windows and events for jMainLoop).

RingJava - use Java classes and methods from Ring programs.