Following is a Java version of the train
example.
This is a multi threaded version of the train
example. In this
mode several threads can access the SICStus runtime via a Prolog
interface
. The static method Jasper.newProlog()
returns an
object that implements a Prolog interface
. A thread can make
queries by calling the query-methods of the Prolog object.
The calls will be sent to a separate server thread that does the actual
call to SICStus runtime.
// MultiSimple.javaimport se.sics.jasper.Jasper; import se.sics.jasper.Query; import se.sics.jasper.Prolog; import java.util.HashMap; public class MultiSimple { class Client extends Thread { Prolog jp; String qs; Client(Prolog p,String queryString) { jp = p; qs = queryString; } public void run() { HashMap WayMap = new HashMap(); try { synchronized(jp) { Query query = jp.openPrologQuery(qs, WayMap); try { while (query.nextSolution()) { System.out.println(WayMap); } } finally { query.close(); } } } catch ( Exception e ) { e.printStackTrace(); } } } { try { Prolog jp = Jasper.newProlog(argv,null,"train.sav"); Client c1 = new Client(jp,"connected('Örebro', 'Hallsberg', Way1, Way1)."); c1.start(); // The prolog variable names are different from above // so we can tell which query gives what solution. Client c2 = new Client(jp,"connected('Stockholm', 'Hallsberg', Way2, Way2)."); c2.start(); } catch ( Exception e ) { e.printStackTrace(); } } public static void main(String argv[]) { new MultiSimple(argv); } }
Prolog
object jp
is the interface to SICStus. It
implements the methods of interface Prolog
, making it possible
to write quite similar code for single threaded and multi threaded
usage of Jasper.
The static method Jasper.newProlog()
returns such an object.
Jasper.newProlog
is the
.sav file to restore. Two threads are then started, which will make
different queries with the connected
predicate.
openPrologQuery
is not recommended in multi threaded mode, but
if you must use it from more than one Java thread, you should enclose
the call to openPrologQuery
and the closing of the query
in a single synchronized block, synchronizing on the Prolog object.
See SPTerm and Memory, for details on one of the reasons why this
is necessary.