/*
* Copyright (C) 2012, 2016 higherfrequencytrading.com
* Copyright (C) 2016 Roman Leventov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see
Typically, you need to specify two things to create an instance of * ProcessInstanceLimiter: a path to a file that will hold the shared map; and a * callback object (an instance implementing ProcessInstanceLimiter.Callback) to * handle the various possible callback messages that the ProcessInstanceLimiter * can generate. *
*Once you have a ProcessInstanceLimiter instance, you specify a type of * process (any string) which will be limited to up to N processes running at * the same time by calling the setMaxNumberOfProcessesOfType() method. Finally * you tell the instance you are starting your process of type X by calling * startingProcessOfType(X). This last is deliberately not done automatically as * you may wish for one type of process to define limitations on other types of * processes. *
*The are some convenience methods which allow you to quickly specify a limit * without consideration of the above. For example, if during your application * startup you call ProcessInstanceLimiter.limitTo(2), then you need not call * anything else and you have limited your application to running at most 2 JVM * instances of your application. Under the covers, this call is identical to * the sequence: *
*ProcessInstanceLimiter limiter = new ProcessInstanceLimiter(); * limiter.setMaxNumberOfProcessesOfType(processType,numProcesses); * limiter.startingProcessOfType(processType); *
*This:
* 1. Creates a shared file called ProcessInstanceLimiter_DEFAULT_SHARED_MAP_ in
* the temp directory to hold an instance of ChronicleMap
* 2. Creates an instance of ProcessInstanceLimiter.DefaultCallback to handle
* all callbacks in a reasonable way - all callbacks will emit a message on stdout
* (using System.out) and those that indicate a conflict will exit the process
* (using System.exit)
* 3. Call setMaxNumberOfProcessesOfType("_DEFAULT_",2) to specify that at most only
* 2 processes designated as type _DEFAULT_ will be allowed to run
* 4. Calls startingProcessOfType("_DEFAULT_") to indicate that this process is an
* instance of a _DEFAULT_ type process, and so should be limited appropriately
*/
public class ProcessInstanceLimiter implements Runnable {
private static final long DEFAULT_TIME_UPDATE_INTERVAL_MS = 100L;
private static final String DEFAULT_SHARED_MAP_NAME = "ProcessInstanceLimiter_DEFAULT_SHARED_MAP_";
private static final String DEFAULT_SHARED_MAP_DIRECTORY = System.getProperty("java.io.tmpdir");
private static final String DEFAULT_PROCESS_NAME = "_DEFAULT_";
static {
AffinitySupport.setThreadId();
}
private final String sharedMapPath;
private final ChronicleMap Create a ProcessInstanceLimiter instance which is limited to one OS
* process instance of the DEFAULT type. This will enforce that any JVM on
* the same box which runs the code
* "ProcessInstanceLimiter.limitToOneProcess()" will only have at most one
* JVM instance running at a time.
*
* @return - the ProcessInstanceLimiter instance
* @throws IOException - if the default shared file cannot be created
*/
public static ProcessInstanceLimiter limitToOneProcess() throws IOException {
return limitTo(1);
}
/**
* Convenience method.
* Create a ProcessInstanceLimiter instance which is limited to
* "numProcesses" OS process instances of the DEFAULT type. This will
* enforce that any JVM on the same box which runs the code
* "ProcessInstanceLimiter.limitTo(numProcesses)" will only have at most
* numProcesses JVM instances running at a time. All the JVMs must use the
* same "numProcesses" value or the process will immediately exit with a
* configuration error.
*
* @param numProcesses - the number of JVM processes that can run at any one time
* @return - the ProcessInstanceLimiter instance
* @throws IOException - if the default shared file cannot be created
*/
public static ProcessInstanceLimiter limitTo(int numProcesses) throws IOException {
return limitTo(numProcesses, DEFAULT_PROCESS_NAME);
}
/**
* Convenience method.
* Create a ProcessInstanceLimiter instance which is limited to
* "numProcesses" OS process instances of the "processType" type. This will
* enforce that any JVM on the same box which runs the code
* "ProcessInstanceLimiter.limitTo(numProcesses, processType)" will only
* have at most numProcesses JVM instances running at a time. All the JVMs
* must use the same "numProcesses" value for a "processType" or the process
* will immediately exit with a configuration error.
*
* @param numProcesses - the number of JVM processes that can run at any one time
* @param processType - any string, specifies the type of process that is limited to
* numProcesses processes
* @return - the ProcessInstanceLimiter instance
* @throws IOException - if the default shared file cannot be created
*/
public static ProcessInstanceLimiter limitTo(int numProcesses, String processType) throws IOException {
ProcessInstanceLimiter limiter = new ProcessInstanceLimiter();
limiter.setMaxNumberOfProcessesOfType(processType, numProcesses);
limiter.startingProcessOfType(processType);
return limiter;
}
/**
* Sleeps the thread for the specified number of milliseconds, ignoring
* interruptions.
*
* @param pause - time in milliseconds to sleep
*/
public static void pause(long pause) {
long start = System.currentTimeMillis();
long elapsedTime;
while ((elapsedTime = System.currentTimeMillis() - start) < pause) {
Thread.interrupted();// clear interruptions.
Jvm.pause(pause - elapsedTime);
}
}
/**
* The path to the shared file which stored the shared map.
*/
public String getSharedMapPath() {
return sharedMapPath;
}
/**
* The instance of the Callback interface held by the instance, which will
* receive callbacks
*/
public Callback getCallback() {
return this.callback;
}
/**
* Returns the MaxNumberOfProcesses allowed for processes of type
* "processType", as specified in the shared map. If that type hasn't been
* set, then this returns -1 (which is an invalid value, as it must be a
* positive value)
*/
public int getMaxNumberOfProcessesAllowedFor(String processType) {
Data data = this.starttimedata.get(processType);
if (data == null) {
return -1;
} else {
return data.getMaxNumberOfProcessesAllowed();
}
}
/**
* The interval between updates to the shared map timestamps - i.e. this is
* the interval between notifications of other processes starting
*/
public long getTimeUpdateInterval() {
return timeUpdateInterval;
}
/**
* Set the interval between updates to the shared map timestamps - i.e. this
* is the interval between notifications of other processes starting
*/
public void setTimeUpdateInterval(long timeUpdateInterval) {
this.timeUpdateInterval = timeUpdateInterval;
}
/**
* run() method for the ProcessInstanceLimiter which it starts in a thread
* called "ProcessInstanceLimiter updater"
*/
public void run() {
//every timeUpdateInterval milliseconds, update the time
while (true) {
try {
pause(timeUpdateInterval);
String processType;
Set The Timelock field is just for locking the time field
*/
public interface Data {
/**
* Ensure lock goes first in flyweight layout, to apply external locking
*/
@Group(0)
long getTimeLock();
void setTimeLock(long timeLock);
@Group(1)
@Array(length = 50)
void setTimeAt(int index, long time);
long getTimeAt(int index);
@Group(1)
int getMaxNumberOfProcessesAllowed();
void setMaxNumberOfProcessesAllowed(int num);
boolean compareAndSwapMaxNumberOfProcessesAllowed(int expected, int value);
}
/**
* A default implementation of the Callback interface, which prints an
* information line to System.out for each callback, and calls
* System.exit(0) for those methods which don't leave the current process
* owning a slot.
*/
public static class DefaultCallback implements Callback {
ProcessInstanceLimiter limiter;
public DefaultCallback(ProcessInstanceLimiter limiter) {
this.limiter = limiter;
}
public DefaultCallback() {
}
public ProcessInstanceLimiter getLimiter() {
return limiter;
}
public void setLimiter(ProcessInstanceLimiter limiter) {
this.limiter = limiter;
}
public void tooManyProcessesOfType(String processType) {
System.out.println("Sufficient processes (" + this.limiter.getMaxNumberOfProcessesAllowedFor(processType) + ") of type " + processType + " have already been started, so exiting this process");
System.exit(0);
}
public void noDefinitionForProcessesOfType(String processType) {
System.out.println("No definition for processes of type " + processType + " has been set, so exiting this process");
System.exit(0);
}
public void anotherProcessHasHijackedThisSlot(String processType, int slot) {
System.out.println("Another process of type " + processType + " has hijacked the slot (" + slot + "/" + this.limiter.getMaxNumberOfProcessesAllowedFor(processType) + ") allocated to this process, so exiting this process");
System.exit(0);
}
public void thisProcessOfTypeHasStartedAtSlot(String processType, int slot) {
System.out.println("This process of type " + processType + " has started at slot " + slot + "/" + this.limiter.getMaxNumberOfProcessesAllowedFor(processType));
}
public void anotherProcessHasStartedOnSlot(String processType, int slot, long startTime) {
System.out.println("Another process of type " + processType + " has started at slot " + slot + "/" + this.limiter.getMaxNumberOfProcessesAllowedFor(processType) + " at time " + new Date(startTime));
}
public void lockConflictDetected(String processType, int slot) {
System.out.println("The limiter lock has become conflicted for type " + processType + " on slot (" + slot + "/" + this.limiter.getMaxNumberOfProcessesAllowedFor(processType) + ") allocated to this process, so exiting this process");
System.exit(0);
}
}
}