J/Link for Developers

Todd Gayley
Directory of Java Technology, Wolfram Research, Inc.

What is J/Link?

J/Link is a toolkit that integrates Mathematica and Java. It lets you call Java from Mathematica in a completely transparent way, and it lets you call Mathematica from Java using a high-level API that is easier to use than the C MathLink API.

What is J/Link?

J/Link is a toolkit that integrates Mathematica and Java. It lets you call Java from Mathematica in a completely transparent way, and it lets you call Mathematica from Java using a high-level API that is easier to use than the C MathLink API.

J/Link and a Java runtime are preinstalled with Mathematica starting in version 4.2. Neither you nor your users need to install anything to use it.

What is J/Link?

J/Link is a toolkit that integrates Mathematica and Java. It lets you call Java from Mathematica in a completely transparent way, and it lets you call Mathematica from Java using a high-level API that is easier to use than the C MathLink API.

J/Link and a Java runtime are preinstalled with Mathematica starting in version 4.2. Neither you nor your users need to install anything to use it.

J/Link comes with extensive documentation and the complete source code.

Why You Want to Use J/Link

Because J/Link lets you load arbitrary Java classes into Mathematica, create objects, and call methods, it makes all of Java an immediate extension to the Mathematica environment.
There is a staggering amount of software development going on in Java. Having access to all that work directly in Mathematica is a tremendous benefit.

Why You Want to Use J/Link

Because J/Link lets you load arbitrary Java classes into Mathematica, create objects, and call methods, it makes all of Java an immediate extension to the Mathematica environment.
There is a staggering amount of software development going on in Java. Having access to all that work directly in Mathematica is a tremendous benefit.

Any time you find yourself asking the question "Can Mathematica do X", and the answer appears to be no, ask "Can Java do X". The answer is probably yes, and if so, then you can do it in Mathematica.
	Examples:
		Can Mathematica import file format XYZ?
		Can Mathematica read and write directly to TCP sockets?
		Can Mathematica control external hardware?
		Can Mathematica talk to my database?

Why You Want to Use J/Link

Because J/Link lets you load arbitrary Java classes into Mathematica, create objects, and call methods, it makes all of Java an immediate extension to the Mathematica environment.
There is a staggering amount of software development going on in Java. Having access to all that work directly in Mathematica is a tremendous benefit.

Any time you find yourself asking the question "Can Mathematica do X", and the answer appears to be no, ask "Can Java do X". The answer is probably yes, and if so, then you can do it in Mathematica.
	Examples:
		Can Mathematica import file format XYZ?
		Can Mathematica read and write directly to TCP sockets?
		Can Mathematica control external hardware?
		Can Mathematica talk to my database?

If you want to write a program that uses Mathematica for computations, the J/Link API is much easier to use than the MathLink C API, but with no loss in power or expressiveness.

What is J/Link?

Simple Example

<<JLink`

InstallJava[]

bigint = JavaNew["java.math.BigInteger", 3^4^4]

Constructors["java.math.BigInteger"]

bigint = JavaNew["java.math.BigInteger", ToString[3^4^4]]

bigint@flipBit[30]

What is J/Link?

Whimsical Example: Turning Mathematica into a Web Server

$ServerSocket = JavaNew["java.net.ServerSocket", 80];

HTTPServer[] :=
   JavaBlock[
      Block[{sock, is, os, buf, numRead, input,
                 result, $JavaExceptionHandler = Null&},
          $ServerSocket@setSoTimeout[200];
          sock = $ServerSocket@accept[];
          If[JavaObjectQ[sock],
              is = sock@getInputStream[];
              buf = JavaNew["[B", 2000];
              numRead = is@read[buf];
              input = FromCharacterCode[Take[Val[buf], numRead]];
              input = StringTake[input,
                     {First[Flatten[StringPosition[input, "?"]]] + 1,
                      First[Flatten[StringPosition[input, "HTTP"]]] - 1}
				     ];
              os = sock@getOutputStream[];
              os@write[ToCharacterCode["HTTP/1.0 200 OK\n\n"]];
              os@write[ToCharacterCode["<pre>"]];
              result = ToExpression[input];
              os@write[ToCharacterCode[ToString[result]]];
              sock@close[]
          ];
          result
       ]
    ]

p = AddPeriodical[HTTPServer[], 1];

RemovePeriodical[p]

Block[{x},
	For[x = 0, x < 1000, x++,
		(* Do one loop step ... *)
		HTTPServer[]
	]
]

History of J/Link

Version 1.0 released in December 1999.

History of J/Link

Version 1.0 released in December 1999.

"Maturity" at version 2.0, released with Mathematica 4.2.

The State of J/Link

Widespread adoption.

The State of J/Link

Widespread adoption.

Numerous commercial applications.

The State of J/Link

Widespread adoption.

Numerous commercial applications.

Used in some way by more than one-fourth of the technical talks at this conference.

The State of J/Link

Widespread adoption.

Numerous commercial applications.

Used in some way by more than one-fourth of the technical talks at this conference.

Version 2.1 in Mathematica 5.0.

Current Java-Related Projects

Web services client package (Chris Williamson talk on Friday).

Current Java-Related Projects

Web services client package (Chris Williamson talk on Friday).

Major new release of webMathematica (version 2.0).

Current Java-Related Projects

Web services client package (Chris Williamson talk on Friday).

Major new release of webMathematica (version 2.0).

Interface Framework (Jeff Adams talk today at 11:00)

Current Java-Related Projects

Web services client package (Chris Williamson talk on Friday).

Major new release of webMathematica (version 2.0).

Interface Framework (Jeff Adams talk today at 11:00)

Java cells in the Front End

Current Java-Related Projects

Web services client package (Chris Williamson talk on Friday).

Major new release of webMathematica (version 2.0).

Interface Framework (Jeff Adams talk today at 11:00)

Java cells in the Front End

Java in the kernel ?

New in J/Link 2.1

Version 2.1 is bundled in Mathematica 5.0.

New in J/Link 2.1

Version 2.1 is bundled in Mathematica 5.0.

A minor but significant update that includes several new features and a few bug fixes.

New in J/Link 2.1

Version 2.1 is bundled in Mathematica 5.0.

A minor but significant update that includes several new features and a few bug fixes.

Required for .NET/Link users.

New in J/Link 2.1

Version 2.1 is bundled in Mathematica 5.0.

A minor but significant update that includes several new features and a few bug fixes.

Required for .NET/Link users.

Drops support for Mac OS Classic and the Microsoft Java runtime.

New in J/Link 2.1

New Features

Chaining calls after a field access now works:

obj@field@method[]

Previously you had to do this:

(obj@field)@method[]

New in J/Link 2.1

New Features

There is a new KeepObject function that lets an object "escape" from the nearest enclosing JavaBlock.

Old style:

f[args__] :=
	(
		frm = JavaNew["java.awt.Frame"];
		button = JavaNew["java.awt.Button"];
		JavaBlock[
			...
		]
	)

New style:

f[args__] :=
	JavaBlock[
		frm = JavaNew["java.awt.Frame"];
		button = JavaNew["java.awt.Button"];
		...
		KeepObject[frm, button]
	]

New in J/Link 2.1

New Features

There is a new mechanism for handling exceptions thrown in Java code.

In the past, all exceptions thrown by calls into Java were reported as messages in Mathematica. Now you can define your own handler function.

javaArray = MakeJavaObject[{1,2,3,4}]

LoadJavaClass["java.lang.reflect.Array"];
Array`getInt[javaArray, 4]

Here is a way to prevent the message from appearing:

Block[{$JavaExceptionHandler = Null&},
	Array`getInt[javaArray, 4]
]

Here we propagate Java's throw/catch style of exception handling up into Mathematica:

Catch[
	Print["before"];
	Block[{$JavaExceptionHandler = Throw[GetJavaException[]]&},
		Array`getInt[javaArray, 4]
	];
	Print["after"]
]

The Future of J/Link

A simpler system for adding event handlers.

Old style:

mml = JavaNew["com.wolfram.jlink.MathMouseMotionListener"];
mml@setHandler["mouseDragged", "mouseDraggedFunc"];
myWindow@addMouseMotionListener[mml]

New style:

AddEventHandler[myWindow, "mouseDragged", mouseDraggedFunc]

The Future of J/Link

Add a high-level JavaBean for Java programmers calling Mathematica, even higher than the KernelLink interface.

Especially designed for visual programming environments, where most programming is done by setting and retrieving the values of properties (for example, Input, Result, Messages, Graphics, PageWidth, etc.)

See the .NET/Link MathKernel object for an example.

The Future of J/Link

Further tweaks to function names as we move toward a unification with .NET/Link and other OOP initiatives.

An example of a past name change is LoadClass changing to LoadJavaClass.

A likely future change is:

Constructors[x]
Methods[x]              ------>      JavaClassInfo[x, "Methods"]
Fields[x]

The Future of J/Link

More than one Java runtime ?

J/Link Best Practices

Bad:

InstallJava[MicrosoftJava->True, ClassPath->"c:\\myclasses"]

Good:

InstallJava[];
AddToClassPath["c:\\myclasses"]

Moral:

Don't use options to InstallJava. Don't assume you have the ability to control how the user's Java runtime will be launched.
Don't use Microsoft's Java. Use .NET/Link instead if you want to call COM.

J/Link Best Practices

Bad:

SuperDuperFunc[] :=
	Module[{...},
		InstallJava[];
		...
		UninstallJava[]
	]

Good:

SuperDuperFunc[] :=
	Module[{...},
		InstallJava[];
		...
	]

Moral:

Don't call UninstallJava. The Java runtime is a shared resource and you have no right to shut it down.

J/Link Best Practices

Bad:

SuperDuperModalDialog[] :=
	Module[{...},
		frm = JavaNew["java.awt.Frame"];
		...
		frm@setModal[True];
		DoModal[]
	]

Good:

SuperDuperModalDialog[] :=
	JavaBlock[
		Module[{...},
			frm = JavaNew["java.awt.Frame"];
			...
			frm@setModal[True];
			DoModal[]
		]
	]

Moral:

Use JavaBlock to avoid "leaking" unnecessary objects.

J/Link Best Practices

Bad:

SuperDuperFunction[] :=
	Module[{...},
		LoadClass["java.awt.Frame"];
		...
	]

Good:

SuperDuperFunction[] :=
	Module[{...},
		LoadJavaClass["java.awt.Frame"];
		...
	]

Moral:

Don't use deprecated names.

?LoadClass

J/Link Best Practices

Bad:

SuperDuperFunction[] :=
	Module[{...},
		ShareKernel[];
		...
		UnshareKernel[]
	]

Good:

SuperDuperFunction[] :=
	Module[{tok},
		tok = ShareKernel[];
		...
		UnshareKernel[tok]
	]

Moral:

Never call UnshareKernel or UnshareFrontEnd with zero arguments. Always pass the token returned by the matching call to ShareKernel or ShareFrontEnd. Other J/Link programs might be relying on sharing.

J/Link Best Practices

Bad:

From the manual:

Place the MySuperDuperApplication directory onto your c: drive. Add the file c:\MySuperDuperApplication\SuperDuper.jar to your system CLASSPATH. Reboot. Then load the package like this:

<<c:\MySuperDuperApplication\SuperDuper.m

Good:

From the manual:

Place the MySuperDuperApplication directory into your Mathematica installation's AddOns\Applications directory. Load the application like this:

Needs["MySuperDuperApplication`"]

Moral:

Mathematica supports a convenient deployment model for applications. Use it. J/Link integrates with this by automatically finding Java classes in an application's Java subdirectory. No CLASSPATH changes are needed. See section 1.2.19 of the J/Link User Guide.