Index: main/trunk/gli/src/org/greenstone/gatherer/util/Readme_Using_SafeProcess.txt
===================================================================
--- main/trunk/gli/src/org/greenstone/gatherer/util/Readme_Using_SafeProcess.txt	(revision 31716)
+++ main/trunk/gli/src/org/greenstone/gatherer/util/Readme_Using_SafeProcess.txt	(revision 31717)
@@ -1,3 +1,8 @@
-SAFEPROCESS README
+First drafts of this document
+ak19, 30 May 2017
+
+=========================================
+	SAFEPROCESS.JAVA README
+=========================================
 
 GS Java developers should use SafeProcess.java in place of directly using Java's Process class, unless any issues are discovered with SafeProcess.java hereafter.
@@ -8,6 +13,24 @@
 - greenstone3/src/java/org/greenstone/util/SafeProcess.java
 
+
+This document contains the following sections
+	A. WHY WE SHOULD GO THROUGH SAFEPROCESS INSTEAD OF USING JAVA'S PROCESS DIRECTLY
+	B. MODEL OF SAFEPROCESS THREADS AND INTERRUPT BEHAVIOUR
+	C. USAGE: DEBUGGING
+	D. USAGE: INSTANTIATION & DEFAULT RUNPROCESS VARIANTS
+	E. INTERNAL IMPLEMENTATION DETAILS - USEFUL IF CUSTOMISING SAFEPROCESS' BEHAVIOUR OR CALLING CANCEL ON SAFEPROCESS
+	F. USAGE: CUSTOMISING
+	G. USAGE: CANCELLING
+	H. USAGE: IMPLEMENTING HOOKS AROUND CANCELLING OR PROCESS' END
+	I. USEFUL STATIC METHODS AND STATIC INNER CLASSES
+	J. OTHER USEFUL INSTANCE METHODS
+	K. LINKS AND NOTES ON PROCESSES, PROCESS STREAMS, INTERRUPTING AND DESTROYING PROCESSES
+	L. USEFUL SYNCHRONISATION NOTES AND SUGGESTED READING ON THREADS AND THREAD SAFETY
+	M. TICKETS, COMMITS, TAGS
+	N. GLI vs GS3 CODE's SAFEPROCESS.JAVA - THE DIFFERENCES
+	O. FUTURE WORK, IMPROVEMENTS
+
 _______________________________________________________________________________
-WHY WE SHOULD GO THROUGH SAFEPROCESS INSTEAD OF USING JAVA'S PROCESS DIRECTLY
+A. WHY WE SHOULD GO THROUGH SAFEPROCESS INSTEAD OF USING JAVA'S PROCESS DIRECTLY
 _______________________________________________________________________________
 
@@ -20,7 +43,7 @@
 
 
-_____________________________________________________
-MODEL OF SAFEPROCESS THREADS AND INTERRUPT BEHAVIOUR
-_____________________________________________________
+_________________________________________________________
+B. MODEL OF SAFEPROCESS THREADS AND INTERRUPT BEHAVIOUR
+_________________________________________________________
 
 This section is especially IMPORTANT TO READ IF you're thinking of customising SafeProcess' handling of the internal Process' iostreams, since each of them are always handled in their own distinct worker threads, and you need to remember to deal with ThreadSafety issues.
@@ -52,10 +75,10 @@
 
 __________________________________________________
-USAGE: DEBUGGING
-__________________________________________________
-
-There's a lot of info that a SafeProcess instance will log during its execution and termination phases, including Exceptions but also very basic things, such as the command that the SafeProcess instance is running.
-
-By default, such debugging-related logging is turned off. You can turn it on by adjusting the static SafeProcess.DEBUG = 1 and recompiling.
+C. USAGE: DEBUGGING
+__________________________________________________
+
+There's a lot of info that a SafeProcess instance will log during its execution and termination phases, including Exceptions but also very basic things, such as the command that the SafeProcess instance is running and other messages.
+
+Exceptions are always logged, but debugging related messages can be turned off or on. By default, it's turned off. You can turn it on by adjusting the static SafeProcess.DEBUG = 1 and recompiling.
 
 For GS3, the log output uses log4j.
@@ -64,7 +87,23 @@
 If you're using SafeProcess yourself and wish to log debug statements that are related to how well you're using SafeProcess, you can call one of the static SafeProcess.log() functions yourself. Remember to set the static SafeProcess.DEBUG = 1.
 
-__________________________________________________
-USAGE: INSTANTIATION & DEFAULT RUNPROCESS VARIANTS
-__________________________________________________
+
+There are 4 variants of the log() function:
+
+	- public static void log(String msg)
+	logs the message if debugging is on, DEBUG = 1
+
+	- public static void log(Exception e)
+	logs the stacktrace for the exception, regardless of if debugging is on
+
+	- public static void log(String msg, Exception e)
+	logs the message and logs the stacktrace for the exception, regardless of if debugging is on
+
+	- public static void log(String msg, Exception e, boolean printStackTrace)
+	if debugging is on or if the printStackTrace parameter is true, both the message and the stacktrace for the exception are logged.
+	if debugging is off and the printStackTrace parameter is false, nothing is logged. Call this variant if an exception is expected and you only want to log it in debugging mode. An example of an expected exception are some InterruptedExceptions that may occur over the course of SafeProcess
+
+_______________________________________________________
+D. USAGE: INSTANTIATION & DEFAULT RUNPROCESS VARIANTS
+_______________________________________________________
 
 Usage of the SafeProcess class generally follows the following sequence:
@@ -156,7 +195,7 @@
 The exit value will also be -1 if you call getExitValue() before setting off the SafeProcess via any of the runProcess() variants.
 
-_________________________________________________________________________________________________________________
-INTERNAL IMPLEMENTATION DETAILS - USEFUL IF CUSTOMISING SAFEPROCESS' BEHAVIOUR OR CALLING CANCEL ON SAFEPROCESS
-_________________________________________________________________________________________________________________
+_____________________________________________________________________________________________________________________
+E. INTERNAL IMPLEMENTATION DETAILS - USEFUL IF CUSTOMISING SAFEPROCESS' BEHAVIOUR OR CALLING CANCEL ON SAFEPROCESS
+_____________________________________________________________________________________________________________________
 
 This section is for understanding how SafeProcess runs a Java Process internally. These methods are not public and their details are hidden away in the code.
@@ -239,5 +278,5 @@
 
 __________________________________________________
-USAGE: CUSTOMISING
+F. USAGE: CUSTOMISING
 __________________________________________________
 
@@ -318,5 +357,5 @@
 
 If, during the execution of the primary thread, you want to do some complex things during a cancel operation, such as or before and after a process is destroyed, then 
-- implement SafeProcess.MainProcessHandler (see below)
+- implement SafeProcess.MainProcessHandler. See the Interface definition below. For further details, refer to the sections "CANCELLING" and "IMPLEMENTING HOOKS AROUND CANCELLING OR PROCESS' END".
 - configure your SafeProcess instance by calling setMainHandler(MainProcessHandler mph) on it *before* calling a runProcess() method on that instance.
 - For EXAMPLES OF USE, see GLI's DownloadJob.java.
@@ -370,28 +409,103 @@
 	}
 
-
-__________________________________________________
-USAGE: CANCELLING
-__________________________________________________
+__________________________________________________
+G. USAGE: CANCELLING
+__________________________________________________
+
+SafeProcess provides a way to cancel an internal Process that is run by SafeProcess, and which will ensure that the internal process and worker threads all safely terminate and tidily clean up after themselves. 
+
+As explained, SafeProcess internally accomplishes this by sending an InterruptedException on the primary thread that's running the internal Process. An InterruptedException is sent only when SafeProcess is in an "interruptible" phase, as no interruption is necessary at any other time such as cleanup.
+
+Only a thread *external* to the SafeProcess' primary thread, such as a GUI thread, can call cancelRunningProcess() on a reference to the SafeProcess instance. Two variants are available:
+
+- boolean cancelRunningProcess()
+- boolean cancelRunningProcess(boolean forceWaitUntilInterruptible)
+
+The boolean value returned is true if an interrupt had to be sent, or false if one didn't need to be sent. An interrupt does not need to be sent if
+	- the process was never yet run by the time cancel was called or
+	- the internal Process has already naturally terminated and the SafeProcess has moved on to some stage of the cleanup phase by the time cancel was called.
+
+If you want to inspect the return value, a good variable name is sentInterrupt. For example,
+	boolean sentInterrupt = mySafeProc.cancelRunningProcess();
+
+
+Programming pattern:
+A graphical interface may have a Cancel button associated with an actionPerformed() method, which will be run from a GUI/EventDispatchThread when the user presses cancel. Either directly or indirectly, actionPerfomed() during a cancel action needs to lead to one of the cancelRunningProcess() method variants being called on the SafeProcess instance.
+
+The variant you choose depends on whether the thread that invokes cancel on the SafeProcess is an EventDispatchThread (a GUI thread), or else, whether you are willing to wait until SafeProcess is interruptible. If you're calling the cancel method from a GUI thread or otherwise don't care to wait, call the zero-argument variant. Otherwise, you can call the single argument version and pass in true for forceWaitUntilInterruptible. 
+
+
+Usage:
+- Usually, there is no need to bother waiting for the uninterruptible phase to finish, so you can call the zero-argument version of cancelRunningProcess(), and continue as before.
+
+- If you're calling from a GUI thread and want to disable your cancel button during the uninterruptible phase, however short this may be, in order to give proper feedback to the user, then you can implement the hooks of the SafeProcess.MainHandler interface as explained in the next section.
+
+- Call the cancelRunningProcess(forceWaitUntilInterruptible=true) variant if you're not calling from a GUI thread and you want to wait until SafeProcess becomes interruptible again (if you happened to have invoked the cancel method during an uninterruptible phase).
+
+
+Further details:
+Calling cancelRunningProcess(forceWaitUntilInterruptible=true) forces the method to only return when the SafeProcess has internally become "interruptible". There is a very brief phase at the start of a SafeProcess' cleanup period that blocks until the worker threads have cleanly terminated. This phase should not be interrupted (as would have happened upon an InterruptedException being sent just then), as the uninterruptible phase happens after the internal process has finished and the process is properly terminating.
+
+If the cancel method happened to be called during this "blocking" phase and if this phase were to theoretically take long and if cancelRunningProcess() were not to return immediately if the calling thread is a GUI thread, then your graphical interface, or at least the cancel button, would have been unresponsive until the cancelRunningProcess() method finally returned. But this uninterruptible phase is short, and it always terminates, so calling cancelRunningProcess() is sufficient. And it always returns immediately if the caller is a GUI thread. The zero-argument variant of cancelRunningProecss() internally calls cancelRunningProcess(forceWaitUntilInterruptible=false) and causes the method to return immediately: either cancelRunningProcess was called when SafeProcess was interruptible and it sends an InterruptedException to the primary thread and returns, or cancelRunningProcess got called when SafeProcess was in an uninterruptible phase. And if the caller was a GUI thread (or if forceWaitUntilInterruptible was set to false), the cancelRunningProcess() method would also return immediately.
+
 
 For EXAMPLES OF USE, see GLI's GShell.java and DownloadJob.java.
 
-__________________________________________________
-USAGE: IMPLEMENTING HOOKS AROUND CANCELLING
-__________________________________________________
-
-For EXAMPLES OF USE, see GLI's DownloadJob.java.
-
-__________________________________________________
-USEFUL STATIC METHODS AND STATIC INNER CLASSES
-__________________________________________________
+_________________________________________________________________
+H. USAGE: IMPLEMENTING HOOKS AROUND CANCELLING OR PROCESS' END
+_________________________________________________________________
+
+- Implement the SafeProcess.MainProcessHandler Interface, see the decription below and the section CUSTOMISING.
+- Write the hooks you want.
+- If you don't really intend to override beforeWaitingForStreamsToEnd(boolean forciblyTerminating) or afterStreamsEnded(boolean forciblyTerminating), then return the boolean parameter forciblyTerminating.
+- For EXAMPLES OF USE, see GLI's DownloadJob.java.
+
+
+The SafeProcess.MainProcessHandler provides hooks into various key stages of the SafeProcess instance's life cycle. Specifically, the clean up and termination stages of its life cycle. Currently, all stages that you can write hooks for come after the internal process has come to an end either naturally or prematurely.
+
+
+If your code needs to do some special processes during any of these stages, override them.
+
+The stages are:
+
+	1. boolean beforeWaitingForStreamsToEnd(boolean forciblyTerminating)
+
+	Called after Process.waitFor() (when the internal Process has naturally or prematurely ended) and before the worker threads are join()ed (when the cleanup phase has begun, which always occurs, regardless of whether the Process had ended naturally or was cancelled). The parameter forciblyTerminating is true if the Process had been cancelled during an interruptible phase, or if an unexpected exception had occurred. In both cases, the internal Process object may need to be destroy()ed. But if the Process had only been cancelled during an uninterruptible phase, it means it had already naturally terminated and has started cleaning up. In such cases, the internal Process object does not need to be destroy()ed and forciblyTerminating will be false.
+
+	If not overriding, return the parameter. If overriding, even if the parameter is true, you may determine the process has come to a natural end after all. In that case, the process need not be destroyed, so you'd return false. For an example, see GLI's DownloadJob.java.
+
+	If you want to disable your cancel button temporarily while the join() is taking place, this is the method to do it.
+
+
+	2. boolean afterStreamsEnded(boolean forciblyTerminating)
+
+	Called after the worker threads are join()ed, which is the start of the clean up phase. This method is also always called and the parameter indicates whether it's so far been determined that the process needs to be destroyed or not. If not overriding, return the parameter.
+
+	If you want to re-enable your cancel button since the join() have by now taken place, this is the method to do so.
+
+
+	3. void beforeProcessDestroy()
+	4. void afterProcessDestroy()
+
+	These two methods are only called if destroy() needed to be called on the internal Process object (if the Process did not come to a natural end for any reason, including being cancelled during an interruptible phase or if an unexpected exception occurred).
+
+
+	5. void doneCleanup(boolean wasForciblyTerminated)
+
+	This method is always called at the very end of the SafeProcess' lifecycle, regardless of whether the internal Process naturally terminated or needed to be destroyed as happens upon premature termination. If the process needed to be destroyed, then the parameter wasForciblyTerminated would be true.
+
+
+___________________________________________________
+I. USEFUL STATIC METHODS AND STATIC INNER CLASSES
+___________________________________________________
 
 public static boolean isAvailable(String programName)
 	- Runs the `which` cmd over the program and returns true or false
-	`which` is included in winbin for Windows, and is part of unix systems
+	- `which` is included in winbin for Windows, and is part of unix systems
 
 static public boolean processRunning(Process process)
-	- returns true if the Process is currently running and hasn't come to an end.
-	- It does not 
+	- returns true if the internal Process is currently running and hasn't come to an end. That is, this method returns true if Process.waitFor() is still blocking
+	- If the SafeProcess is in its cleanup/termination phase, then this method will return false, even though SafeProcess is still doing stuff.
+	- If you want to know when SafeProcess has finished in its entirety, call the instance method processRunning() on the SafeProcess object.
 
 public static long getProcessID(Process p)
@@ -411,6 +525,6 @@
 
 public static boolean closeSocket(Socket resourceHandle)
-	- will attempt to cleanly close your Socket, logging on Exception. In Java 6, Sockets didn't yet implement Closeable,
-	so this method is to ensure backwards compatibility
+	- will attempt to cleanly close your Socket, logging on Exception.
+	- From Java 7 onwards, calling closeResource() would suffice on Sockets too. But in Java 6, Sockets didn't yet implement Closeable, so this method is to ensure backwards compatibility.
 
 public static class OutputStreamGobbler extends Thread
@@ -423,12 +537,14 @@
 
 
-Package access:
-static methods to prematurely terminate any process denoted by processID and any subprocesses it may have launched:
-	static boolean killUnixProcessWithID(long processID)
-	static void killWinProcessWithID(long processID)
-
-
-__________________________________________________
-OTHER USEFUL INSTANCE METHODS
+Package access: static methods to prematurely terminate any process denoted by processID and any subprocesses it may have launched
+
+static void killWinProcessWithID(long processID)
+
+static boolean killUnixProcessWithID(long processID)
+	- for Mac/Linux
+
+
+__________________________________________________
+J. OTHER USEFUL INSTANCE METHODS
 __________________________________________________
 
@@ -437,15 +553,357 @@
 
 public boolean cancelRunningProcess()
+public boolean cancelRunningProcess(boolean forceWaitUntilInterruptible)
 	- cancel the SafeProcess instance
 	- untimately synchronized, so threadsafe
-__________________________________________________
-USEFUL SYNCHRONISATION NOTES
-__________________________________________________
-[Also add in links]
-
-
-__________________________________________________
-TICKETS, COMMITS, TAGS
-__________________________________________________
-
-
+	- returns true if the process were still running so that an interrupt needed to be sent to terminate it, returns false if sending an interrupt was unnecessary because the process had already entered the start of its termination phase when cancel was called. Will also return false if the process was never run by the time cancel was called.
+	- usually you want to call the zero-argument version
+	- See the section CANCELLING for further details
+
+_________________________________________________________________________________________________
+K. LINKS AND NOTES ON PROCESSES, PROCESS STREAMS, INTERRUPTING AND DESTROYING PROCESSES
+_________________________________________________________________________________________________
+
+Processes and streams
+
+- http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
+explains why SafeProcess.java is implemented with worker threads to handle a Process' iostreams.
+- http://steveliles.github.io/invoking_processes_from_java.html
+- http://mark.koli.ch/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec
+
+
+Interrupting a Process:
+
+- http://stackoverflow.com/questions/2126997/who-is-calling-the-java-thread-interrupt-method-if-im-not
+- http://stackoverflow.com/questions/13623445/future-cancel-method-is-not-working?noredirect=1&lq=1
+- http://stackoverflow.com/questions/3976344/handling-interruptedexception-in-java
+- http://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-when-catch-any-interruptexception
+- http://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-when-catch-any-interruptexception
+- https://praveer09.github.io/technology/2015/12/06/understanding-thread-interruption-in-java/
+
+
+Destroying a process and subprocesses on various OS:
+
+- Need process id, pid, for which Java Native Access libraries (jar files) are required.
+http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
+- To find the processID of the process launched by SafeProcess, need to use Java Native Access (JNA) jars, available jna.jar and jna-platform.jar.
+    http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
+    http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id
+    http://www.golesny.de/p/code/javagetpid
+    https://github.com/java-native-access/jna/blob/master/www/GettingStarted.md
+    We're using JNA v 4.1.0, downloaded from https://mvnrepository.com/artifact/net.java.dev.jna/jna
+
+WINDOWS NOTES:
+- Can't artificially send Ctrl-C: stackoverflow.com/questions/1835885/send-ctrl-c-to-process-open-by-java
+
+ On Windows, p.destroy() terminates process p that Java launched,
+ but does not terminate any processes that p may have launched. Presumably since they didn't form a proper process tree.
+    https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/e3cb7532-87f6-4ae3-9d80-a3afc8b9d437/how-to-kill-a-process-tree-in-cc-on-windows-platform?forum=vclanguage
+    https://msdn.microsoft.com/en-us/library/windows/desktop/ms684161(v=vs.85).aspx
+
+ Searching for: "forcibly terminate external process launched by Java on Windows"	
+ Not possible: stackoverflow.com/questions/1835885/send-ctrl-c-to-process-open-by-java 
+ But can use taskkill or tskill or wmic commands to terminate a process by processID
+ stackoverflow.com/questions/912889/how-to-send-interrupt-key-sequence-to-a-java-process
+ Taskkill command can kill by Image Name, such as all running perl, e.g. taskkill /f /im perl.exe
+ But what if we kill perl instances not launched by GS?
+    /f Specifies to forcefully terminate the process(es). We need this flag switched on to kill childprocesses.
+    /t Terminates the specified process and any child processes which were started by it. 
+			/t didn't work to terminate subprocesses. Maybe since the process wasn't launched as 
+			a properly constructed processtree.
+    /im is the image name (the name of the program), see Image Name column in Win Task Manager.
+	
+ We don't want to kill all perl running processes. 
+ Another option is to use wmic, available since Windows XP, to kill a process based on its command
+ which we sort of know (SafeProcess.command) and which can be seen in TaskManager under the 
+ "Command Line" column of the Processes tab.
+    https://superuser.com/questions/52159/kill-a-process-with-a-specific-command-line-from-command-line	
+ The following works kill any Command Line that matches -site localsite lucene-jdbm-demo
+    C:>wmic PATH win32_process Where "CommandLine like '%-site%localsite%%lucene-jdbm-demo%'" Call Terminate
+ "WMIC Wildcard Search using 'like' and %"
+    https://codeslammer.wordpress.com/2009/02/21/wmic-wildcard-search-using-like-and/
+ However, we're not even guaranteed that every perl command GS launches will contain the collection name
+ Nor do we want to kill all perl processes that GS launches with bin\windows\perl\bin\perl, though this works:
+    wmic PATH win32_process Where "CommandLine like '%bin%windows%perl%bin%perl%'" Call Terminate
+ The above could kill GS perl processes we don't intend to terminate, as they're not spawned by the particular
+ Process we're trying to terminate from the root down.
+	
+ Solution: We can use taskkill or the longstanding tskill or wmic to kill a process by ID. Since we can
+ kill an external process that SafeProcess launched OK, and only have trouble killing any child processes
+ it launched, we need to know the pids of the child processes. 
+ 
+ We can use Windows' wmic to discover the childpids of a process whose id we know.
+ And we can use JNA to get the process ID of the external process that SafeProcess launched.
+ 
+ See links further above on how to find the processID of the process launched by SafeProcess on various OS,
+ and where to find the JNA jars needed for this.
+  
+ WMIC can show us a list of parent process id and process id of running processes, and then we can
+ kill those child processes with a specific process id.
+    https://superuser.com/questions/851692/track-which-program-launches-a-certain-process
+    http://stackoverflow.com/questions/7486717/finding-parent-process-id-on-windows
+ WMIC can get us the pids of all childprocesses launched by parent process denoted by parent pid.
+ And vice versa:
+    if you know the parent pid and want to know all the pids of the child processes spawned:
+        wmic process where (parentprocessid=596) get processid
+    if you know a child process id and want to know the parent's id:
+        wmic process where (processid=180) get parentprocessid
+ 
+ The above is the current solution.
+ 
+ Linux ps equivalent on Windows is "tasklist", see
+    http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
+
+
+MAC/UNIX NOTES:
+- Kill signals, their names and numerical equivalents: http://www.faqs.org/qa/qa-831.html
+- Killing a processtree (a process group) on Unix:
+https://stackoverflow.com/questions/8533377/why-child-process-still-alive-after-parent-process-was-killed-in-linux
+Works on Linux but not Mac: kill -TERM -pid
+Works on Mac but not Linux: pkill -TERM -P pid did work
+- https://stackoverflow.com/questions/28332888/return-value-of-kill
+	"kill returns an exit code of 0 (true) if the process still existed it and was killed.
+	kill returns an exit code of 1 (false) if the kill failed, probably because the process was no longer running."
+- https://superuser.com/questions/343031/sigterm-with-a-keyboard-shortcut
+Ctrl-C sends a SIGNINT, not SIGTERM or SIGKILL. And on Ctrl-C, "the signal is sent to the foreground *process group*."
+- https://linux.die.net/man/1/kill (manual)
+- https://unix.stackexchange.com/questions/117227/why-pidof-and-pgrep-are-behaving-differently
+- https://unix.stackexchange.com/questions/67635/elegantly-get-list-of-children-processes
+- https://stackoverflow.com/questions/994033/mac-os-x-quickest-way-to-kill-quit-an-entire-process-tree-from-within-a-cocoa-a
+- https://unix.stackexchange.com/questions/132224/is-it-possible-to-get-process-group-id-from-proc
+- https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated
+
+_______________________________________________________________________________________
+L. USEFUL SYNCHRONISATION NOTES AND SUGGESTED READING ON THREADS AND THREAD SAFETY
+_______________________________________________________________________________________
+
+Things worth reading on Concurrency and Thread safety:
+
+- Deitel and Deitel's newer editions of their Java books have updated their chapter on Concurrency.
+- http://docs.oracle.com/javase/tutorial/uiswing/concurrency/
+series of Java articles on concurrency again.
+- https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html
+On "primitive" like variables that provide instrinsic locks.
+
+
+Notes on synchronization:
+
+- You can declare methods are synchronized. For example,
+	public synchronized void doStuff()
+This implicitly synchronizes on the *instance* of the class on which this method is called.
+
+- Within any methods, you can synchronize on specific objects to just lock on them. You have a synchronized code block within which you can manipulate the object.
+
+Keep synchronized blocks and methods as short as you can.
+There are some subtle issues related to using synchronized methods, as explained below, that can result in deadlocks.
+
+
+More reading:
+
+- http://stackoverflow.com/questions/574240/is-there-an-advantage-to-use-a-synchronized-method-instead-of-a-synchronized-blo
+
+       "Not only do synchronized methods not lock the whole class, but they don't lock the whole instance either. Unsynchronized methods in the class may still proceed on the instance."
+       "Only the syncronized methods are locked. If there are fields you use within synced methods that are accessed by unsynced methods, you can run into race conditions."
+       
+       "synchronizing on "this" is considered in some circles to be an anti-pattern. The unintended consequence is that outside of the class someone can lock on an object reference that is equal to "this" and prevent other threads from passing the barriers within the class potentially creating a deadlock situation. Creating a "private final Object = new Object();" variable purely for locking purposes is the often used solution. Here's another question relating directly to this issue.
+
+- http://stackoverflow.com/questions/442564/avoid-synchronizedthis-in-java?lq=1"
+
+       "A private lock is a defensive mechanism, which is never a bad idea.
+
+       Also, as you alluded to, private locks can control granularity. One set of operations on an object might be totally unrelated to another but synchronized(this) will mutually exclude access to all of them."
+
+
+- http://stackoverflow.com/questions/8393883/is-synchronized-keyword-exception-safe
+     "In any scoped thread-safe block, the moment you get out of it, the thread-safety is gone."
+     "In case of an exception the lock will be released."
+
+- http://stackoverflow.com/questions/8259479/should-i-synchronize-listener-notifications-or-not
+     "Use a CopyOnWriteArrayList for your listener arrays."
+     "If you use the CopyOnWriteArrayList, then you don't have to synchronize when iterating."
+     "CopyOnWriteArrayList is thread-safe, so there is no need to synchronize."
+
+     "Use a ConcurrentLinkedQueue<Listener> ... for this kind of problems: adding, removing and iterating simultaneously on a collection.
+     A precision : this solution prevents a listener from being called from the very moment it is deregistered."
+     "It means that you start iterating, an element is added, it will be called, another is removed, it won't, all this in the same iteration cycle.
+     It's the best of both world: ensuring synchronization, while being fine grained on who gets called and who's not."
+
+Examples of using CopyOnWriteArrayList: in GLI's shell/GShell.java and GS3's gsdl3/build/CollectionConstructor.java
+
+- http://stackoverflow.com/questions/8260205/when-a-listener-is-removed-is-it-okay-that-the-event-be-called-on-that-listener
+
+- http://stackoverflow.com/questions/2282166/java-synchronizing-on-primitives
+     
+     1. You can't lock on a primitive and
+     2. Don't lock on a Long unless you're careful how you construct them. Long values created by autoboxing or Long.valueOf() in a certain range are guaranteed to be the same across the JVM which means other threads could be locking on the same exact Long object and giving you cross-talk. This can be a subtle concurrency bug (similar to locking on intern'ed strings).
+
+     Cross-talk:
+     "In electronics, crosstalk is any phenomenon by which a signal transmitted on one circuit or channel of a transmission system creates an undesired effect in another circuit or channel. Crosstalk is usually caused by undesired capacitive, inductive, or conductive coupling from one circuit, part of a circuit, or channel, to another."
+
+
+__________________________________________________
+M. TICKETS, COMMITS, TAGS
+__________________________________________________
+
+The following was already documented in ticket http://trac.greenstone.org/ticket/895
+
+	Other Java classes of GLI and GS3 src code were shifted from using Java's Process class directly to using our new SafeProcess class.
+
+	GLI src code classes that were changed:
+	/Scratch/ak19/gs3-svn-15Nov2016/gli>fgrep -rl "Process" src
+
+	+ src/org/greenstone/gatherer/util/SafeProcess.java
+	+ src/org/greenstone/gatherer/gui/FormatConversionDialog.java
+	+ src/org/greenstone/gatherer/gui/DownloadPane.java
+	+ src/org/greenstone/gatherer/util/GS3ServerThread.java
+	+ 2 src/org/greenstone/gatherer/Gatherer.java [2 MORE but don't want to mess with those]
+	+ 1 src/org/greenstone/gatherer/download/ServerInfoDialog.java
+	+ 2 src/org/greenstone/gatherer/greenstone/Classifiers.java
+	+ 2 src/org/greenstone/gatherer/greenstone/Plugins.java
+	+ 1 src/org/greenstone/gatherer/collection/ScriptOptions.java
+	+ !! src/org/greenstone/gatherer/util/ExternalProgram.java && file/FileAssociationManager.java
+
+	After updating GS3 src code to using SafeProcess, returned to GLI:
+	- VERY HARD:
+	 + 1 src/org/greenstone/gatherer/shell/GShell.java
+	- VERY, VERY HARD:
+	 + 2 src/org/greenstone/gatherer/download/DownloadJob.java
+
+
+	GS3 src code classes that were changed:
+	> fgrep -r "Process" . | grep -v ".svn" | grep -v "~" | less
+
+	+ 2 ./java/org/greenstone/admin/guiext/Command.java
+	X ./java/org/greenstone/gsdl3/util/Processing.java
+	+ MANY OCCURRENCES ./java/org/greenstone/gsdl3/service/MapRetrieve.java
+	+ Uses Processing 2 times: ./java/org/greenstone/gsdl3/util/GDBMWrapper.java
+	+ ./java/org/greenstone/util/BrowserLauncher.java
+	+ ./java/org/greenstone/util/RunTarget.java
+
+	In the GLI and GS3 src files modified to use SafeProcess above, only the modifications to GS3's Command.java, MapRetrieve.java and GDMBWrapper.java are untested. All others have been tested, at least on Linux. Many have also been tested on Windows.
+
+	Tested GLI's collection building (uses GShell.java's modifications) and DownloadJob.java on all 3 OS. Both have a Cancel button that should cancel any processes and subprocesses launched. Before the modifications, subprocesses would still be running on Windows and during (full-)import on the Mac when cancel was pressed. But now have added code to SafeProcess to issue OS specific system calls to terminate the process and its subprocesses successfully on Windows and Mac too.
+
+	Also tested GS3 user comments and the online GS3's doc editor's meta editing followed by rebuilding. All worked successfully on Linux, Windows and Mac with the modifications to use SafeProcess.
+
+	The modifications to GLI started with GS3ServerThread.java and other *easily* changed classes in 
+	- http://trac.greenstone.org/changeset/31582 (beginning of GLI modification) 
+	- until http://trac.greenstone.org/changeset/31665 (GS3 src code modification).
+
+	The version of GS3 and GLI Java code before the GS3 src was modified is at 
+	- http://trac.greenstone.org/browser/main/tags/GS3-src-SafeProcess
+
+	Next, GLI's GShell.java and any associated files were modified along with SafeProcess, to support cancelling.
+
+	Then, around 22 May, GLI's DownloadJob.java and any associated class files were modified along with SafeProcess to ensure subprocesses were safely terminated on Windows when the download action was cancelled OR when building (GShell.java) was cancelled. The Mac modifications to SafeProcess to ensure subprocesses were terminated was finished on 26 May 2017.
+
+	The tagged version of the GS3 and GLI Java code for when all the changes related to using SafeProcess were made to GS3 and GLI code is at 
+	- http://trac.greenstone.org/browser/main/tags/UsingSafeProcess
+
+_________________________________________________________
+N. GLI vs GS3 CODE's SAFEPROCESS.JAVA - THE DIFFERENCES
+_________________________________________________________
+
+- package name
+	GLI: package org.greenstone.gatherer.util;
+	GS3: package org.greenstone.util;
+- imports:
+	GLI: import org.greenstone.gatherer.DebugStream;
+- GS3 uses Misc.java and GLI uses Utility.java for determining the OS and the appropriate newline character representation for the OS.
+- GS3 uses its Logger object for logging messages, GLI uses System.err (Debugstream code is presently commented out).
+
+
+	$ diff gli/src/org/greenstone/gatherer/util/SafeProcess.java src/java/org/greenstone/util/SafeProcess.java 
+	-----------------------------------------------------------------------------------------------------------
+	1c1
+	< package org.greenstone.gatherer.util;
+	---
+	> package org.greenstone.util;
+	27c27
+	< import org.greenstone.gatherer.DebugStream;
+	---
+	> //import org.greenstone.gatherer.DebugStream;
+	56c56
+	<     ///static Logger logger = Logger.getLogger(org.greenstone.util.SafeProcess.class.getName());
+	---
+	>     static Logger logger = Logger.getLogger(org.greenstone.util.SafeProcess.class.getName());
+	153a154
+	> 
+	816c817
+	< 	if(Utility.isMac()) { 
+	---
+	> 	if(Misc.isMac()) { 
+	880c881
+	<     if(Utility.isWindows()) {
+	---
+	>     if(Misc.isWindows()) {
+	909c910
+	< 	if(!Utility.isMac() && canSkipExtraWorkIfLinux) {
+	---
+	> 	if(!Misc.isMac() && canSkipExtraWorkIfLinux) {
+	1284c1285
+	< 		    outputstr.append(Utility.NEWLINE); // "\n" is system dependent (Win must be "\r\n")
+	---
+	> 		    outputstr.append(Misc.NEWLINE); // "\n" is system dependent (Win must be "\r\n")
+	1381c1382
+	< 	    /*if(Utility.isWindows()) {
+	---
+	> 	    /*if(Misc.isWindows()) {
+	1416c1417
+	< 	//logger.info(msg);
+	---
+	> 	logger.info(msg);
+	1418c1419
+	< 	System.err.println(msg);
+	---
+	> 	//System.err.println(msg);
+	1424c1425
+	< 	//logger.error(msg, e);
+	---
+	> 	logger.error(msg, e);
+	1426,1427c1427,1428
+	< 	System.err.println(msg);
+	< 	e.printStackTrace();
+	---
+	> 	//System.err.println(msg);
+	> 	//e.printStackTrace();
+	1434c1435
+	< 	//logger.error(e);
+	---
+	> 	logger.error(e);
+	1436c1437
+	< 	e.printStackTrace();
+	---
+	> 	//e.printStackTrace();
+
+	-----------------------------------------------------------------------------------------------------------
+
+
+__________________________________________________
+O. FUTURE WORK, IMPROVEMENTS
+__________________________________________________
+
+- On Windows, Perl could launch processes as proper ProcessTrees: http://search.cpan.org/~gsar/libwin32-0.191/
+Then killing the root process will kill child processes naturally, and we won't need to call OS commands to terminate a process.
+- Need to find a Mac (or Unix) equivalent way creating Process Tree in Perl too.
+
+Eventually, instead of running a windows/mac or even linux command to kill the process ourselves, investigate if it is useful to change over to use
+    https://github.com/flapdoodle-oss/de.flapdoodle.embed.process/blob/master/src/main/java/de/flapdoodle/embed/process/runtime/Processes.java 
+- mentioned by http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
+- works with Apache license, http://www.apache.org/licenses/LICENSE-2.0
+- This is a Java class that uses JNA to terminate processes. It also has the getProcessID() method.
+- However, does it kill subprocesses? (The OS specific commands presently issued in SafeProcess.destroyProcess() ensure subprocesses are killed.)
+
+
+Currently, SafeProcess does Java things the way that older Java versions recognise and accept, not only for backwards compatibility with earlier versions of Java, but in order to minimise the number of drastic changes from porting the existing Greenstone GLI and GS3 code to using SafeProcess.
+
+- In future, think of changing the method doRuntimeExec() over to using ProcessBuilder, instead of Runtime.exec(). ProcessBuilder seems to have been introduced from Java 5.
+https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
+See also https://zeroturnaround.com/rebellabs/how-to-deal-with-subprocesses-in-java/
+which suggests using Apache Common Exec to launch processes and says what will be forthcoming in Java 9
+
+- Instead of creating and running Threads the usual way, should we use features of newer Java versions like the Concurrency API and Executor which uses Threadpools, and let Executor handle these details? Improvements would be with multicore systems
+https://stackoverflow.com/questions/3330430/does-java-have-support-for-multicore-processors-parallel-processing
+
+
+
+
