Package com.stata.sfi

Annotation Type SynchronizedOnMain


@Documented @Retention(SOURCE) public @interface SynchronizedOnMain
Indicates that a method or class is thread-safe and that thread safety has been provided using the Java keyword synchronized; execution may be forced back on the main thread, so care must be taken to prevent deadlocks. For example, if a worker thread calls a SynchronizedOnMain method while the main thread has been blocked, a deadlock will occur.

Example:

This example shows how to handle and prevent a potential deadlock when using a method marked with SynchronizedOnMain in a parallel stream.


	public static int simpleExample(String args[]) {
		final int count = Integer.parseInt(args[0]);
		String label = args[1];
		Thread t1 = new Thread(() -> {
			IntStream.range(1, count).parallel().forEach(n -> {
				// IMPORTANT: A WORKER THREAD IS NEEDED BECAUSE 
				// SFIToolkit.displayln() runs on the main thread
				// (SynchronizedOnMain) and since the stream 
				// waits/blocks the main thread a deadlock would
				// otherwise occur. 
				SFIToolkit.displayln(label + n);
			});
		});

		// start the thread; wait for thread to finish before we exit plugin
		t1.start();
		while (t1.isAlive()) {
			try {
				Thread.sleep(10);
				SFIToolkit.pollnow();
			} catch (InterruptedException e) {}
		}
		SFIToolkit.displayln(" ... done");
		return 0;
	}

From Stata...

. javacall Examples simpleExample, args(100 "counting: ") jar(examples.jar)