Multi-thread

package com.bindhuw.saro.corpactions.control;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.log4j.LogManager;
import com.bindhuw.saro.common.saroMultiProcess;
* @author
* @version 1.0
* @Description saro Application Main class for the Event Manager background process. The class runs the following 4 threads:
* CAInitialReconGenerator,CaStatementGenerator CaTaskGenerator & CATaskController
public class CAEventManager extends saroMultiProcess {
// Name of the process
public static final String PROCESS_NAME = "caEventManager";
* The instance of logger for logging
// private static Category logger;
private static Log logger;
* Constructor of the class.
* @param port Port number
* @param envId Environment id.
* @param processId Process id.
* @param termId Terminal id.
* @param procName Process name.
public CAEventManager(int port, int envId, int processId, String termId, String procName) {
super(port, envId, processId, termId, procName);
* Main fucntion to start the service.
* @param args Command line arguments.
static public void main(String[] args) {
final int NO_OF_PARAMS = 5;
// check for valid number of parameters
if (args.length < NO_OF_PARAMS) {
System.err.println("Invalid number of command line parameters: " + args.length);
System.err.println("Expected number of command line parameters: " + NO_OF_PARAMS);
System.exit(1);
logger = LogFactory.getLog(PROCESS_NAME);
// print some messages
String msgPrefix = "[SYSTEM][" + PROCESS_NAME + "]";
logger.fatal(msgPrefix + "Process starting...");
Date now = new Date();
logger.info("************************************************************");
logger.info("* Process : " + PROCESS_NAME);
logger.info("* Time Stamp: " + now);
logger.info("************************************************************");
try {
System.setProperty("CONFIG_BASE", args[4]);
// load properties
loadPropertiesFor(PROCESS_NAME);
logger.info("Loaded properties from file: " + getPropertiesFile());
int port = Integer.parseInt(args[0]);
int envId = Integer.parseInt(args[1]);
int processId = Integer.parseInt(args[2]);
CAEventManager eventMgr = new CAEventManager(port, envId, processId, args[3], PROCESS_NAME);
eventMgr.getChildProcesses().add(new CAInitialReconGenerator(eventMgr));
eventMgr.getChildProcesses().add(new CAStatementGenerator(eventMgr));
eventMgr.getChildProcesses().add(new CATaskGenerator(eventMgr));
eventMgr.getChildProcesses().add(new CATaskController(eventMgr));
eventMgr.getChildProcesses().add(new CADirectoryWatcher(eventMgr));
eventMgr.startServer();
} catch (Throwable t) {
logger.error(msgPrefix + "Server startup exception: " + t.getMessage());
logger.info("Stack trace: ", t);
} finally {
logger.fatal(msgPrefix + "Process exiting...");
// Category.shutdown();
if (logger instanceof Log4JLogger) {
LogManager.shutdown();
System.exit(0);
* saroMultiProcess.java
* Copyright (c) 2001 bindhu
* All Rights Reserved.
* Fixed Income Banking Products
package com.bindhuw.saro.common;
import static com.bindhuw.saro.infrastructure.util.FileUtility.constructEtcPath;
import static com.bindhuw.saro.infrastructure.util.FileUtility.locate;
import static java.lang.String.format;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.xml.sax.SAXException;
import com.bindhuw.saro.infrastructure.dao.saroUtilDao;
import com.bindhuw.saro.infrastructure.exception.saroException;
import com.bindhuw.saro.infrastructure.exception.saroInvalidPropertyException;
import com.bindhuw.saro.infrastructure.file.PasswordFileReader2;
import com.bindhuw.saro.infrastructure.file.PasswordObject;
import com.bindhuw.saro.infrastructure.model.saroMqDefinition;
import com.bindhuw.saro.infrastructure.util.MqUtilities;
import com.bindhuw.saro.infrastructure.util.YorN;
* Models the saro process capable of running multiple threads.
* @author Veera Shivanantham, Anant Kumar Mishra
* @version %I%, %G%
* @see com.bindhuw.saro.common.saroMultiProcess.java
public class saroMultiProcess extends csaroProcess {
// Sleep time for the main thread - 5000 ms (5 sec)
private static final int SLEEP_TIME = 5000;
// Contains the list of saroChildProcess
private List childProcesses;
// flag that holds the request for stopping the process
private boolean alreadyRequestedToStop;
// properties file
private static String propertiesFile;
// debug flag
private static final boolean DEBUG = false;
* Only constructor.
* @param port
* @param envId
* @param processId
* @param termId
* @param processName
public saroMultiProcess(int port, int envId, int processId, String termId, String processName) {
super(port, envId, processId, termId, processName);
this.childProcesses = new ArrayList(10);
* Start all the child processes in the server
public void startServer() {
// // rfs 545
// String killServerOnAllErrors = System.getProperty("KILL_SERVER_ON_ALL_ERRORS");
// if (killServerOnAllErrors != null && killServerOnAllErrors.trim().length() > 0) {
// killServerOnAllErrors = killServerOnAllErrors.trim();
// if (killServerOnAllErrors.startsWith("Y") || killServerOnAllErrors.startsWith("y")
// || killServerOnAllErrors.startsWith("T") || killServerOnAllErrors.startsWith("t")
// || killServerOnAllErrors.startsWith("1"))
// setFlagOn(FLAG_KILL_SERVER_ON_ALL_ERRORS);
for (int i = 0; i < childProcesses.size(); i++) {
saroChildProcess child = (saroChildProcess) childProcesses.get(i);
child.start();
while (this.getStatus() != isaroProcess.SERVER_REQUEST_TO_KILL) {
try {
Thread.sleep(SLEEP_TIME); // sleep for 5 sec.
} catch (InterruptedException ie) {
ie.printStackTrace();
boolean allThreadsDead = true;
for (int i = 0; i < childProcesses.size(); i++) {
saroChildProcess child = (saroChildProcess) childProcesses.get(i);
if (child.isAlive()) {
allThreadsDead = false;
break;
if (allThreadsDead) {
setStatus(isaroProcess.SERVER_REQUEST_TO_KILL);
stopProcess();
* Over rided parent, to check all the child are done and closed properly.
public synchronized void stopProcess() {
if (alreadyRequestedToStop) return;
else alreadyRequestedToStop = true;
// Check all the childs are free. if they are, then stop the childs and exit.
boolean childAlive = true;
while (childAlive) {
childAlive = false;
for (int count = 0; count < childProcesses.size(); count++) {
saroChildProcess child = (saroChildProcess) childProcesses.get(count);
if (child.getServiceStatus() == saroChildProcess.SERVICE_BUSY) {
// If one child is alive no need to check for other childs, go to sleep until childs are
// stopped.
childAlive = true;
if (DEBUG)
System.out.println("[SYSTEM][CHILD]-[" + child.getServiceName() + "]- Alive.");
} else if (child.getServiceStatus() == saroChildProcess.SERVICE_NO_BUSY && child.isAlive()) {
// child thread is sleeping, wake it up to make the exit faster
child.interrupt();
if (childAlive) {
if (DEBUG)
System.out.println("[SYSTEM]-Childs are active, sleeping for " + SLEEP_TIME / 1000
+ " seconds.");
try {
Thread.sleep(SLEEP_TIME); // Sleep for 5 seconds.
} catch (InterruptedException ie) {
if (DEBUG) System.out.println("[SYSTEM]-All child process are finished.");
super.stopProcess();
* Child raised the error. stop all the childs and clean exit of the process.
* @param child
public void raiseClientError(saroChildProcess child) {
System.out.println("[SYSTEM][CHILD]-[" + child.getServiceName() + "]- Child raised the error.");
this.setStatus(isaroProcess.SERVER_REQUEST_TO_KILL);
System.out.println("[SYSTEM] - Closing down all the childs and the system.");
stopProcess();
* Load the properties file from saro_BASE/etc/<process_name>.properties
* @param process name of the process
* @throws FileNotFoundException
* @throws IOException
* @throws saroException
public static void loadPropertiesFor(String process) throws FileNotFoundException, IOException,
saroException {
// try opening it using saro_BASE system property
propertiesFile = System.getProperty("CONFIG_BASE");
if (propertiesFile != null && propertiesFile.trim().length() > 0) {
if (!propertiesFile.trim().endsWith(File.separator))
propertiesFile = propertiesFile.trim() + File.separator;
propertiesFile += ("etc" + File.separator + process + ".properties");
} else {
throw new saroException(" Invalid CONFIG_BASE property: " + propertiesFile
+ ". Unable to locate properties file using this property!");
loadProperties(propertiesFile);
* Loads the properties from the file to the system properties. If the properties value match the password
* file entry pattern the corresponding value from the password file is loaded.
* @param file
public static void loadProperties(String file) throws FileNotFoundException, IOException,
saroInvalidPropertyException, saroException {
propertiesFile = file;
Properties props = new Properties();
props.load(new FileInputStream(propertiesFile));
PasswordFileReader2 passwordFileReader = new PasswordFileReader2();
PasswordObject oPasswordObject = new PasswordObject();
// load the values to the system properties
Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = null;
if (PasswordFileReader2.looksLikePasswordFileKey(props.getProperty(key))) value = passwordFileReader
.getValue(props.getProperty(key)).getValue();
else value = props.getProperty(key);
if (value == null || value.trim().length() == 0)
throw new saroInvalidPropertyException("The value of property " + key
+ " is either null or blank.");
System.setProperty(key, value);
// load DB Properties...
int noOfPools = Integer.parseInt(System.getProperty("NUMBER_OF_POOLS"));
for (int i = 1; i <= noOfPools; i++) {
String[] strURLArray = null;
oPasswordObject = passwordFileReader.getValue(System.getProperty("DBPOOL_DS_NAME_" + i), "SYB",
"URL");
System.setProperty("DBPOOL_SYBASE_URL_" + i, oPasswordObject.getValue());
strURLArray = PasswordFileReader2.splitURL(oPasswordObject.getValue());
System.setProperty("DBPOOL_SERVER_NAME_" + i, strURLArray[3]);
System.setProperty("DBPOOL_PORT_NUMBER_" + i, strURLArray[4]);
oPasswordObject = passwordFileReader.getValue(System.getProperty("DBPOOL_DS_NAME_" + i), "SYB",
"DBN");
System.setProperty("DBPOOL_DB_NAME_" + i, oPasswordObject.getValue());
oPasswordObject = passwordFileReader.getValue(System.getProperty("DBPOOL_DS_NAME_" + i), "SYB",
"USR");
System.setProperty("DB_USER_" + i, oPasswordObject.getValue());
oPasswordObject = passwordFileReader.getValue(System.getProperty("DBPOOL_DS_NAME_" + i), "SYB",
"PWD");
System.setProperty("DB_PASS_" + i, oPasswordObject.getValue());
System.setProperty("DB_USER", System.getProperty("DB_USER_1"));
System.setProperty("DB_PASS", System.getProperty("DB_PASS_1"));
* This method fetches the MQ details from the static table <code>saroMqDefinitions</code> based on the
* <code>processName</code> . For each Mq detail, it then generates mba.xml file only if enabled flag in
* the table is Y and (the mba.xml does not exists for the particular MQ or the boolean createFile flag is
* set to true). Then it loads the child process with argument <code>MqDefinitions</code> and name of
* the class.
* @param logger - For logging reports
* @param processName - MQ definitions are picked based on this process name
* @param serviceName - Name of the service
* @param serviceClass - class of the saroChildProcess3 which we want to run
* @param createNewFile - new mba.xml file is created if true. else mba.xml is created only if not
* present.
* @throws saroInvalidPropertyException
* @throws SQLException
* @throws SAXException
* @throws IOException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
protected void loadChildProcesses(Log logger, String processName, String serviceName, Class serviceClass,
boolean createNewFile) throws saroInvalidPropertyException, SQLException, SAXException,
IOException, SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
List<saroMqDefinition> list = new saroUtilDao().fetchMqDetails(logger, processName);
for (saroMqDefinition def : list) {
if (def.getEnableFlag() == YorN.Y) {
MqUtilities util = new MqUtilities();
String fileName = serviceName + "." + def.getMqAlias() + ".mba.xml";
String serverFileName = locate(fileName);
if (serverFileName == null || createNewFile) {
serverFileName = constructEtcPath(fileName);
logger.info(format("For mqAlias [%s] writing the file [%s]", def.getMqAlias(),
serverFileName));
String xmlString = util.generateXml(def.toMap());
util.writeFile(serverFileName, xmlString);
} else {
logger.info(format("For mqAlias [%s] using the file [%s]", def.getMqAlias(),
serverFileName));
def.setConfigName(serverFileName);
Constructor constr = serviceClass
.getConstructor(saroMultiProcess.class, saroMqDefinition.class);
saroChildProcess3 w = (saroChildProcess3) constr.newInstance(this, def);
w.setSleepTimeInSecs(def.getSleepTimeInSecs());
w.setServiceActivationStatus(def.getEnableFlag());
getChildProcesses().add(w);
* This method fetches the MQ details from the static table <code>saroMqDefinitions</code> based on the
* <code>processName</code> . For each Mq detail, it then generates mba.xml file only if enabled flag in
* the table is Y and the system property CREATE_NEW_MBA_XML_FILE is set to true. If the property
* CREATE_NEW_MBA_XML_FILE is set to false, then if the mba file already exists, it will not create the
* file. Then it loads the child process with argument <code>MqDefinitions</code> and name of the class.
* @param logger - For logging reports
* @param processName - MQ definitions are picked based on this process name
* @param serviceName - Name of the service
* @param serviceClass - class of the saroChildProcess3 which we want to run
* @throws saroInvalidPropertyException
* @throws SQLException
* @throws SAXException
* @throws IOException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
protected void loadChildProcesses(Log logger, String processName, String serviceName, Class serviceClass)
throws saroInvalidPropertyException, SQLException, SAXException, IOException, SecurityException,
NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException,
InvocationTargetException {
loadChildProcesses(logger, processName, serviceName, serviceClass, Boolean
.getBoolean("CREATE_NEW_MBA_XML_FILE"));
* Getter for the attribute childProcesses
* @return the list of child processes
public List getChildProcesses() {
return childProcesses;
* Setter for the attribute childProcesses
* @param newChildProcesses
public void setChildProcesses(List newChildProcesses) {
childProcesses = newChildProcesses;
* Getter for the attribute propertiesFile
* @return the value of attribute propertiesFile
public static String getPropertiesFile() {
return propertiesFile;
package com.bindhuw.saro.common;
import com.bindhuw.saro.dbobjects.*;
import com.bindhuw.saro.util.*;
* Title: csaroProcess
* Description:
* Copyright: Copyright (c) 2001
* Company: bindhuW
* @author Veera
* @version 1.0
public class csaroProcess implements isaroProcess{
public static int status = isaroProcess.PROCESS_READY;
public static int serviceCount = 0;
private int controlFlag;
private int loginNumber = 0;
private String userCode = "SYS";
private String loginType = "BACK";
private String hostName;
private int port; //passed In
private int processId; //passed In
private String processName;
private int environmentId; //passed In
private String terminalId; //passed In
private int taskId = 1;
private String longProgramName = "Martini Server";
cUDPService udp;
cUserLoginService userLogin;
public csaroProcess(int port, int envId, int processId, String termId, String processName){
this.setPort(port);
this.setEnvironmentId(envId);
this.processId = processId;
this.terminalId = termId;
this.processName = processName;
//Set the default values.
try{
hostName = java.net.InetAddress.getLocalHost().getHostName();
udp = new cUDPService(this);
udp.setDaemon(true);
userLogin = new cUserLoginService(this);
System.out.println("[SYSTEM]-Starting UDP");
udp.listenToUDP();
System.out.println("[SYSTEM]-Make an entry to User login.");
userLogin.doLogin();
}catch(Exception e) {
System.out.println("[SYSTEM]-Server initialise error.\n"+e.getMessage());
e.printStackTrace();
System.exit(0);
public void finalise() {
userLogin.doLogout();
public void stopProcess() {
System.out.println("[SYSTEM]-Requested to stop this service. Shutting Down System.");
System.out.println("[SYSTEM]-Removing entry from user_login table.");
userLogin.doLogout();
public int getStatus() {
return this.status;
public void setStatus(int status) {
this.status = status;
public int getServiceCount() {
return this.serviceCount;
public String getProcessName() {
return this.processName;
public String getUserCode() {
return this.userCode;
public String getLoginType() {
return this.loginType;
public String getHostName() {
return this.hostName;
public int getPort() {
return this.port;
public int getProcessId() {
return this.processId;
public int getEnvironmentId() {
return this.environmentId;
public String getTerminalId() {
return this.terminalId;
public int getTaskId() {
return this.taskId;
public String getLongProgramName() {
return this.longProgramName;
public int getLoginNumber() {
return loginNumber;
public void setLoginNumber(int loginNum) {
this.loginNumber = loginNum;
public void setHostName(String newHostName) {
hostName = newHostName;
public void setLoginType(String newLoginType) {
loginType = newLoginType;
public void setLongProgramName(String newLongProgramName) {
longProgramName = newLongProgramName;
public void setServiceCount(int newServiceCount) {
this.serviceCount = newServiceCount;
public void setTaskId(int newTaskId) {
taskId = newTaskId;
public void setUserCode(String newUserCode) {
userCode = newUserCode;
public boolean checkService(int serviceId, String client_name) {
if(serviceId == this.SERVICE_START) {
if(this.status == isaroProcess.SERVER_REQUEST_TO_KILL) {
System.out.println("[SYSTEM]-Server flagged to die. No more conections.");
return false;
this.serviceCount ++;
System.out.println("[SYSTEM]-New client connected.("+this.serviceCount+") Clients are connected.");
} else if(serviceId == this.SERVICE_END){
if(this.serviceCount > 0)
this.serviceCount --;
System.out.println("[SYSTEM]-New client connected.("+this.serviceCount+") Clients are connected.");
if(this.status != isaroProcess.SERVER_REQUEST_TO_KILL && this.serviceCount == 0)
setStatus(isaroProcess.PROCESS_READY);
return true;
public void setPort(int newPort) {
port = newPort;
public void setEnvironmentId(int newEnvironmentId) {
environmentId = newEnvironmentId;
public void setProcessId(int newProcessId) {
processId = newProcessId;
public void setProcessName(String newProcessName) {
processName = newProcessName;
public void setTerminalId(String newTerminalId) {
terminalId = newTerminalId;
* Get the value of control flag.
* @return
public int getControlFlag(){
     return controlFlag;
* Set the specified flag on.
* @param flag
public void setFlagOn(int flag) {
     controlFlag |= flag;
* Set the specified flag off.
* @param flag
public void setFlagOff(int flag) {
     controlFlag &= (~flag);
* saroChildProcess3.java
* Copyright (c) 2001 bindhu
* All Rights Reserved.
* Fixed Income Banking Products
package com.bindhuw.saro.common;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.bindhuw.saro.infrastructure.util.YorN;
* Refractored version of the saroChildProcess2. Now uses commons-logging logger.
* @author Veera, Anant
* @version 1.3
* @see com.bindhuw.saro.common.saroChildProcess3.java
public class saroChildProcess3 extends saroChildProcess {
protected Log logger = null;
* Default constructor
public saroChildProcess3() {
super();
logger = LogFactory.getLog(this.getClass());
/** Constructor
* @param newServer Object of saroMultiProcess
public saroChildProcess3(saroMultiProcess newServer) {
this();
setServer(newServer);
* Constructs the object for the server with the specified name
* @param newServer server
* @param name service name
public saroChildProcess3(saroMultiProcess newServer, String name){
this(newServer);
setServiceName(name);
logger = LogFactory.getLog(name);
// set the enabled flag
String enabled = System.getProperty(name + ".enabled", "true");
setServiceActivationStatus(enabled);
// set sleep time
String sleepTimeInSecs = System.getProperty(name + ".sleepTimeInSecs");
if (sleepTimeInSecs != null)
setSleepTimeInSecs(sleepTimeInSecs);
/** Over ride the fundamental behaviour of Runnable target, to acomplish
* the interoprability with saroMultiProcess.
public void run() {
if (getServiceStatus() == SERVICE_DISABLED)
return;
String msgPrefix = "[SYSTEM][" + getServer().getProcessName() + "][" + getServiceName() + "]";
try {
init();
} catch (Exception e) {
setErrorFlag(FATAL_ERROR);
logger.error(msgPrefix + "Error during initialisation of the child process. " + e.getMessage());
logger.info("Stack trace: ", e);
if (getServer().getStatus() != isaroProcess.SERVER_REQUEST_TO_KILL && getErrorFlag() != FATAL_ERROR)
logger.fatal(msgPrefix + "Service launched...");
boolean isAlive = true;
while (isAlive) {
try {
if (getServer().getStatus() == isaroProcess.SERVER_REQUEST_TO_KILL || getErrorFlag() == FATAL_ERROR
          || getErrorFlag() == SERVICE_DONE) {
isAlive = false;
//Set this status flag to SERVICE_NO_BUSY.
setServiceStatus(SERVICE_NO_BUSY);
String msg = null;
if (getErrorFlag() == FATAL_ERROR){
                              msg = "Terminating thread due to the errors above...";
                              if((getServer().getControlFlag() & isaroProcess.FLAG_KILL_SERVER_ON_ALL_ERRORS)
                                             == isaroProcess.FLAG_KILL_SERVER_ON_ALL_ERRORS)
                                   getServer().raiseClientError(this);
}else if(getErrorFlag() == SERVICE_DONE){
     setErrorFlag(SERVICE_DONE);
     msg = "Service completed... ";
} else{
                              msg = "Request to stop the thread...";
logger.error(msgPrefix + msg);
//Break the loop and exit.
break;
} else {
setServiceStatus(SERVICE_BUSY);
performSpecificService();
setServiceStatus(SERVICE_NO_BUSY);
if (getServer().getStatus() != isaroProcess.SERVER_REQUEST_TO_KILL && getErrorFlag() != FATAL_ERROR) {
try {
Thread.sleep(getSleepTimeInSecs() * 1000); //Sleep for specified time.
} catch (InterruptedException ie) {
// do nothing
} catch (Exception e) {
String msg = "Caught an exception:Message:" + e.getMessage();
logger.error(msgPrefix + msg);
logger.info("Stack trace: ", e);
//Set the error Flag. and set the service status to SERVICE_NO_BUSY.
setErrorFlag(FATAL_ERROR);
getServer().raiseClientError(this);
setServiceStatus(SERVICE_NO_BUSY);
//Raise the error to server.
msg = "Informed to the parent with fatal error. " + "Stoping the child process...";
logger.error(msgPrefix + msg);
logger.fatal(msgPrefix + "Thread exiting... ");
try {
clean();
} catch (Exception e) {
setErrorFlag(FATAL_ERROR);
logger.error(msgPrefix + "Error during clean up of the child process. " + e.getMessage());
logger.info("Stack trace: ", e);
* One time initialization. Called before starting the process.
* @throws Exception
protected void init() throws Exception {
* One time cleanup. Called before exiting the process.
* @throws Exception
protected void clean() throws Exception {
* Getter for property logger
* @return the logger
public Log getLogger() {
return logger;
* Setter for property logger
* @param logger - the logger
public void setLogger(Log logger) {
this.logger = logger;
/** Setter for property sleepTimeInSecs.
* @param sleepTimeInSecs New value of property sleepTimeInSecs
public void setSleepTimeInSecs(String sleepTimeInSecs) {
int sleepTime = getSleepTimeInSecs();
try {
sleepTime

Very interesting.
But who will be willing to read that amount of unformatted code - needless to say, you didn't even post a question...or did I miss it in that pile of characters...?

Similar Messages

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Memory leaks and multi threading issues in managed client.

    In our company we use a lot of Oracle, and after the release of the managed provider we migrated all applications to it. First the  things were very impressive : the new client was faster, but after some days applications that uses 100MB with old client goes to 1GB and up. The memory is not the only issue, we use a lot of multi threading, and we experience connection drops and not disposal, after 1 days working one of the application had over 100 sessions on the server. I think there is something wrong with connection pool and multi threading.
    Is someone experience same problems.
    Yesterday we went back with unmanaged provider. Now things are back to normal.

    connection drops: did you try to use "Validate Connection=true" parameter in your connection string?
    the new client was faster: are you sure with this statement? Even in 64bit environment? I got quite serious performance problems when running application under 64bit process: https://forums.oracle.com/thread/2595323

  • How to write a multi threaded Cache Event Listener

    I have a distributed data cache called tokenCache for my application. I have also added a mapListener to this cache to listen to a particular kind of events.
    tokenCache.addMapListener((MapListener) new TokenCacheListenerBean(), new MapEventFilter(tokenFilter), false);
    So bascially everytime a token (The domain object of this cache) is updated the entryUpdated() method in my EJB TokenCacheListenerBean is invoked.
    The issue I have though is that, from what I observe on running my code is that the Cache Listener is single threaded. So if two Token Objects on my tokenCache are updated,
    lets say Token Object A and Token Object B one after the other,  the entryUpdated() method in my EJB is invoked for Token Object A and  once the invocation is complete
    then the entryUpdated() method is invoked again for Token Object B(). At a given point of time there is only one instance of TokenCacheListenerBean EJB.  Is there a way to
    make this happen in multi-threaded manner ?
    Is there a configuration setting somewhere which allows multiple CacheListeners to be instantiated at a given point of time ?
    TokenCacheListenerBean  EJB_
    package oracle.communications.activation.asap.ace;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.logging.Logger;
    import javax.ejb.Stateless;
    import com.tangosol.net.NamedCache;
    import com.tangosol.util.MapEvent;
    import com.tangosol.util.MapListener;
    import com.tangosol.util.ValueUpdater;
    import com.tangosol.util.extractor.PofExtractor;
    import com.tangosol.util.extractor.PofUpdater;
    import com.tangosol.util.filter.EqualsFilter;
    import com.tangosol.util.filter.LikeFilter;
    import com.tangosol.util.filter.LimitFilter;
    import com.tangosol.util.processor.UpdaterProcessor;
    * Session Bean implementation class TokenCacheListenerBean
    @Stateless
    public class TokenCacheListenerBean implements TokenCacheListenerBeanRemote, TokenCacheListenerBeanLocal, MapListener {
    NamedCache asdlCache;
    NamedCache tokenCache;
    private final int PAGE_SIZE = 1;
    private static Logger logger = Logger.getLogger(ConnectionManager.class.getName());;
    * An instance of the JCAModeler EJB, represents the JCA-JNEP
    JCAModeler jcaBean;
    * Default constructor.
    public TokenCacheListenerBean() {
    // TODO Auto-generated constructor stub
    public void entryDeleted(MapEvent Event) {
    public void entryInserted(MapEvent Event) {
    public void entryUpdated(MapEvent Event) {
    Token newToken = (Token) Event.getNewValue();
    Token oldToken = (Token) Event.getOldValue();
    if ((oldToken.getState() == Token.TOKEN_RESERVED)
    && (newToken.getState()== Token.TOKEN_AVAILABLE)) {
    String networkID = newToken.getNeID();
    asdlCache = AceCacheFactory.getCache("asdlCache");
    tokenCache = AceCacheFactory.getCache("tokenCache");
    EqualsFilter filterNE = new EqualsFilter(new PofExtractor(String.class,Asdl.NETWORKID), networkID);
    LimitFilter limitFilter = new LimitFilter(filterNE, PAGE_SIZE);
    Set removeASDL = asdlCache.keySet(limitFilter);
    Iterator asdlIterator = removeASDL.iterator();
    if (asdlIterator.hasNext()) {
    logger.info(printASDLCache());
    ValueUpdater updater = new PofUpdater(Token.STATE);
    System.out.println("Token ID:" + newToken.getTokenID());
    UpdaterProcessor updaterProcessor = new UpdaterProcessor(updater, Integer.toString(Token.TOKEN_RESERVED));
    tokenCache.invoke(newToken.getTokenID(), updaterProcessor);
    jcaBean = new JCAModeler(tokenCache);
    Object asdlID = asdlIterator.next();
    Asdl provisionAsdl = (Asdl) asdlCache.get(asdlID);
    asdlCache.remove(asdlID);
    jcaBean.provision(provisionAsdl, newToken.getTokenID());
    logger.info(ConnectionManager.printTokenCache());
    logger.info(printASDLCache());
    }

    Here is what I am asking!
    I have added 2 listeners (Listener A and Listener B) which each listen on for changes made to 2 different token Cache Objects (Token A and Token B).
    for (i = 0; i < 2 ; i++) {
    Token tokenAdded = new Token(UUID.randomUUID().toString(),TOKEN_AVAILABLE, networkID);
    tokenCache.put(tokenAdded.getTokenID(), tokenAdded);
         tokenCache.addMapListener((MapListener) new TokenCacheListener(), tokenAdded.getTokenID(), false);
    Now assume that updates are made to Token A and Token B simuntaneosly.
    Why do i observe in my diagnostic messages that only one Listener is invoked at a given point of time.
    Which means I see Listener A getting invoked and then once invocation of Listener A is complete I see Listener B bieng invoked.
    Ideally I would want both listeners to be invoked simultaneously rather than in a one off fashion.
    Here is the code for my token cache Listener
    package oracle.communications.activation.asap.ace;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import com.tangosol.net.CacheFactory;
    import com.tangosol.net.NamedCache;
    import com.tangosol.util.AbstractMapListener;
    import com.tangosol.util.Filter;
    import com.tangosol.util.MapEvent;
    import com.tangosol.util.MapListener;
    import com.tangosol.util.ObservableMap;
    import com.tangosol.util.ValueUpdater;
    import com.tangosol.util.extractor.PofExtractor;
    import com.tangosol.util.extractor.PofUpdater;
    import com.tangosol.util.filter.AndFilter;
    import com.tangosol.util.filter.EqualsFilter;
    import com.tangosol.util.filter.LikeFilter;
    import com.tangosol.util.filter.LimitFilter;
    import com.tangosol.util.processor.UpdaterProcessor;
    public class TokenCacheListener extends AbstractMapListener {
         NamedCache asdlCache;
         NamedCache tokenCache;
         AceCacheFactory cacheFactoryBean = new AceCacheFactory();
         private final int PAGE_SIZE = 1;
         private static Logger logger = Logger.getLogger(ConnectionManager.class
                   .getName());;
         * An instance of the JCAModeler EJB, represents the JCA-JNEP
         JCAModeler jcaBean;
         * This is a utility method and prints the tokens cache.
         public String printTokenCache() {
              NamedCache tokenCache = cacheFactoryBean.getCache("tokenCache");
              LikeFilter tokenList = new LikeFilter(new PofExtractor(String.class,
                        Token.STATE), "%", (char) 0, false);
              Set keySet = tokenCache.keySet(tokenList);
              StringBuffer cachedTokenList = new StringBuffer("\n################################## Token(s) Cache ##################################");
              int counter = 1;
              for (Object tokenInCache: keySet) {
                   Token tokenObject = (Token) tokenCache.get(tokenInCache.toString());
                   cachedTokenList.append("\nS.NO:" + (counter++)
                             + "\t ID:" + tokenInCache.toString()
                             + "\t State:" + Token.tokenToString(tokenObject.getState()));
              cachedTokenList.append("\n####################################################################################");
              return cachedTokenList.toString();     
         * This method is a utility method and it prints all the ASDL(s) currently present on the
         * asdlCache.
         private String printASDLCache() {
              NamedCache asdlCache = cacheFactoryBean.getCache("asdlCache");
              LikeFilter asdlList = new LikeFilter(new PofExtractor(String.class,
                                  Asdl.NETWORKID), "%", (char) 0, false);
              Set keySet = asdlCache.keySet(asdlList);
              StringBuffer cachedASDLList = new StringBuffer("\n################ ASDL Cache ######## ########");
              int counter = 1;
              for (Object asdlInCache: keySet) {
                   cachedASDLList.append("\nS.NO:" + (counter++) + "\t ID:" + asdlInCache.toString());
              cachedASDLList.append("\n################ ASDL Cache ######## ########\n");
              return cachedASDLList.toString();     
         public TokenCacheListener() {
         public void checkASDLCache(MapEvent Event) {
         // Not currently used
         public void entryUpdated(MapEvent Event) {
              Token newToken = (Token) Event.getNewValue();
              Token oldToken = (Token) Event.getOldValue();
              logger.info("\n=============================================================================================="
                        + "\nTOKEN CACHE LISTENER"
                        + "\n=============================================================================================="
                        + printTokenCache()
                        + "\n==============================================================================================");
              if ((oldToken.getState() == Token.TOKEN_RESERVED)
                        && (newToken.getState()== Token.TOKEN_AVAILABLE)) {
              String networkID = newToken.getNeID();
              asdlCache = cacheFactoryBean.getCache("asdlCache");
              tokenCache = cacheFactoryBean.getCache("tokenCache");
              EqualsFilter filterNE = new EqualsFilter(new PofExtractor(String.class,Asdl.NETWORKID), networkID);
              LimitFilter limitFilter = new LimitFilter(filterNE, PAGE_SIZE);
              Set removeASDL = asdlCache.keySet(limitFilter);
              Iterator asdlIterator = removeASDL.iterator();
              if (asdlIterator.hasNext()) {
              logger.info(printASDLCache());
              ValueUpdater updater = new PofUpdater(Token.STATE);
              System.out.println("Token ID:" + newToken.getTokenID());
              UpdaterProcessor updaterProcessor = new UpdaterProcessor(updater, Integer.toString(Token.TOKEN_RESERVED));
              tokenCache.invoke(newToken.getTokenID(), updaterProcessor);
              jcaBean = new JCAModeler(tokenCache);
              Object asdlID = asdlIterator.next();
              Asdl provisionAsdl = (Asdl) asdlCache.get(asdlID);
              asdlCache.remove(asdlID);
              jcaBean.provision(provisionAsdl, newToken.getTokenID());
              logger.info(printTokenCache());
              logger.info(printASDLCache());
    I only see one instance of this listener alive at any given point of time.
    Edited by: 807103 on Nov 3, 2011 1:00 PM
    Edited by: 807103 on Nov 3, 2011 1:12 PM

  • Multi-Threaded FTP

    Multi-Threaded FTP was a huge attraction for me, and one of the features that sold me on upgrading to Dreamweaver CS6.  However, I haven't seen any sign of it in the product or any documentation to help me use it.  My files keep transferring in the traditional one-at-a-time way.
    Is there something I need to do to enable this feature? Has anybody used this feature yet?

    Might not help but I saw this in the comments on David Powers' blog
    http://foundationphp.com/blog/2012/04/23/my-verdict-on-dreamweaver-cs6/
    "Multi-thread FTP is the default in Dreamweaver CS6. You can neither turn it on nor off. It handles a maximum of three transfers simultaneously in either direction (so you can download at the same time as uploading). However, it doesn’t work with Check In/Check Out."
    He also has the following comments in the body of the blog entry:
    Multichannel FTP
    Let’s be honest. In the past, Dreamweaver’s FTP client was a dog. Not any more. It now supports multichannel transfers, and can even download at the same time as uploading. Orange arrows indicate items queued for transfer. When the transfer begins, the arrow turns green. And if you’re transferring a large item, hovering over the filename displays a tooltip of how much of the file has been transferred. With Dreamweaver CS5.5, it took more than 90 minutes to  upload a WordPress site on my internet connection. Now, it’s more than ten times faster.
    The FTP error messages are also more meaningful. No one is likely to buy Dreamweaver CS6 for its FTP client alone, but this is a major improvement to the program.

  • Multi Thread Server over TCP/IP

    Multi Thread Server over TCP/IP. Does it work?
    In my box it works only over IPC protocol.
    null

    S C Maturi (guest) wrote:
    : Mark Malakanov (guest) wrote:
    : : Multi Thread Server over TCP/IP. Does it work?
    : : In my box it works only over IPC protocol.
    : Mark,
    : Multi threaded server over TCP/IP will not work with
    : the current distribution of Oracle 8.0.5 on Linux.
    : This is corrected and a patch would be released soon.
    : Maturi
    tcp 0 0 bock.nettek-ll:listener bock.nettek-
    llc.co:4196 ESTABLISHED
    tcp 0 0 bock.nettek-llc.co:4196 bock.nettek-
    ll:listener ESTABLISHED
    (I have serveral of these)
    TNS Ping Utility for Linux: Version 8.0.5.0.0 - Production on 07-
    JAN-99 18:45:52
    (c) Copyright 1997 Oracle Corporation. All rights reserved.
    Attempting to contact (ADDRESS=(PROTOCOL=TCP)(HOST=localhost)
    (PORT=1521))
    OK (440 msec)
    ...and from my install log you see that I selected MTS:
    -[ YESNO
    Q> Would you like MTS (Multi-Threaded Server) configured
    and the SQL*Net$
    A> TRUE
    Please explain? Will TCP/IP MTS work via the loopback adapter
    only? So far I have not tried a remote TCP/IP connection.
    -STEVEl
    null

  • Running a Java Multi Thread Program in database

    I have created a multi threaded program in Java and it runs successfully from the command prompt. I want to create a DBMS Job which will wake up at regular intervals and runs the java program(Java stored procedure). Is this possible in 9.2/10G ?? If Yes, will there be any impact on the DB performance/increase memory etc.,
    The database (9.2...) resides on a RH 2.3 AS box.
    Any ideas...
    Thanks,
    Purush

    Purush,
    Java stored procedures cannot be multi-threaded. Well, they can, but the threads will not run in parallel. You may be able to find some more information in the Oracle documentation, which is available from:
    http://tahiti.oracle.com
    Good Luck,
    Avi.

  • What's wrong with my multi-threaded Matrix Mult. code? 1 thread is fastest

    For some reason, 1 thread performs the best. What's wrong with my implementation?
    import java.util.Random;
    import java.util.Date;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    public class Matrix {     
         private int values[][];
         private int rows;
         private int columns;
         public Matrix(int r, int c) {
              this.rows = r;
              this.columns = c;
              this.values = new int[r][c];
         private void randomize() {
              Random generator = new Random();
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < this.columns; c++) {
                        this.values[r][c] = generator.nextInt(10);
         public String toString() {
              String out = "";
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < this.columns; c++) {
                        if (c == 0) out += "[";
                        else out += "\t";
                        out += this.values[r][c];
                   out += "]\n";
              return out;
         public boolean equals(Object obj) {
              Matrix other = (Matrix) obj;
              if (this.columns != other.columns || this.rows != other.rows)  {
                   return false;
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < this.columns; c++) {
                        if (this.values[r][c] != other.values[r][c]) {
                             return false;
              return true;
         // matrix multiplication using single thread
         public Matrix times(Matrix other) {
              assert(this.columns == other.rows);
              Matrix out = new Matrix(this.rows, other.columns);
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < other.columns; c++) {
                        int dotProduct = 0;
                        for (int z = 0; z < this.columns; z++) {
                             dotProduct += this.values[r][z] * other.values[z][c];
                        out.values[r][c] = dotProduct;
              return out;
         // matrix multiplication with many threads
         public Matrix ptimes(Matrix other, int numberOfThreads) throws InterruptedException { // parallel
              assert(this.columns == other.rows);
              Matrix out = new Matrix(this.rows, other.columns);
              ExecutorService threadExecutor = Executors.newFixedThreadPool(numberOfThreads);
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < other.columns; c++) {
                        threadExecutor.execute(new HelperThread(r, c, this, other, out));
              threadExecutor.shutdown();
              threadExecutor.awaitTermination(2, TimeUnit.DAYS);
              return out;
         private class HelperThread implements Runnable {
              private int row;
              private int col;
              private Matrix a;
              private Matrix b;
              private Matrix out;
              HelperThread(int r, int c, Matrix a, Matrix b, Matrix o) {
                   this.row = r;
                   this.col = c;
                   this.a = a;
                   this.b = b;
                   this.out = o;
              public void run() {
                   int dotProduct = 0;
                   for (int z = 0; z < a.columns; z++) {
                        dotProduct += this.a.values[row][z] * this.b.values[z][col];
                   this.out.values[row][col] = dotProduct;
         public static void main(String[] args) throws InterruptedException {
              int size = 100;
              Matrix a = new Matrix(size, size);
              a.randomize();     
              Matrix b = new Matrix(size, size);
              b.randomize();
              for (int t = 1; t < 15; t++) {
                   long start = new Date().getTime();
                   System.out.print(t + " threads: ");
                   Matrix c = a.ptimes(b, t);
                   //System.out.println(c);
                   long finish = new Date().getTime();
                   System.out.println((finish - start) + " milliseconds");
                   Matrix d = a.times(b);
                   assert(c.equals(d));
    }

    This one is even faster. On my dual core I get:
    Warmup
    Single Threaded
    5.20616 milliseconds
    5.52872 milliseconds
    5.12708 milliseconds
    5.59048 milliseconds
    5.16104 milliseconds
    5.1838 milliseconds
    5.37104 milliseconds
    5.1788 milliseconds
    5.18636 milliseconds
    5.15736 milliseconds
    Multi Threaded with 2 threads
    3.22184 milliseconds
    2.86552 milliseconds
    2.86284 milliseconds
    3.67032 milliseconds
    3.08032 milliseconds
    2.97388 milliseconds
    2.93084 milliseconds
    3.44012 milliseconds
    2.89744 milliseconds
    2.88136 milliseconds
    As you can see the Multi-Threaded versions are now faster.
        // matrix multiplication with many threads
        ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        public Matrix ptimes(Matrix other) throws InterruptedException, ExecutionException {
            assert (this.columns == other.rows);
            Matrix out = new Matrix(this.rows, other.columns);
            Future futures[] = new Future[rows];
            for (int r = 0; r < this.rows; r++) {
                futures[r] = threadExecutor.submit(new HelperThread(r, this, other, out));
            for(Future f : futures) {
                f.get();
            return out;
        private class HelperThread implements Callable<Object> {
            private int row;
            private Matrix a;
            private Matrix b;
            private Matrix out;
            HelperThread(int r, Matrix a, Matrix b, Matrix o) {
                this.row = r;
                this.a = a;
                this.b = b;
                this.out = o;
            public String call() throws Exception {
                int dotProduct = 0;
                for (int c = 0; c < b.columns; c++) {
                    for (int z = 0; z < a.columns; z++) {
                        dotProduct += this.a.values[row][z] * this.b.values[z][c];
                    this.out.values[row][c] = dotProduct;
                return null;
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            int size = 100;
            Matrix a = new Matrix(size, size);
            a.randomize();
            Matrix b = new Matrix(size, size);
            b.randomize();
            System.out.println("Warmup");
            for (int t = 0; t < 1000; t++) {
                Matrix c = a.ptimes(b);
                Matrix d = a.times(b);
                assert (c.equals(d));
            System.out.println("Single Threaded");
            for (int t = 0; t < 10; t++) {
                long start = System.nanoTime();
                Matrix d = a.times(b);
                long finish = System.nanoTime();
                System.out.println((finish - start)/1000000.0 + " milliseconds");
            System.out.println("Multi Threaded with " + Runtime.getRuntime().availableProcessors() + " threads");
            for (int t = 0; t < 10; t++) {
                long start = System.nanoTime();
                Matrix c = a.ptimes(b);
                long finish = System.nanoTime();
                System.out.println((finish - start)/1000000.0 + " milliseconds");
                Matrix d = a.times(b);
                assert (c.equals(d));
            System.exit(0);
        }

  • Acrobat 9 Pro Extended Distiller - Multi-threaded?

    I am using distiller on some fairly large postscript files (also large numbers of small postscript files) and am running into what appears to be machine limitations. I'm running on a 32 bit workstation with 3gb RAM and an intel core duo CPU. Looking at the perf monitor, my processes are not RAM limited and I never seem to get the CPU use above 50% which indicates to me that distiller may not be multi-threaded. Is that the case? If so, is there a way to get distiller to use both CPUs? (or all 4 on a quad core)

    I am also facing the same issue. Although you can run multiple instances of Distiller using switch "N"
    acrodist.exe -N
    But don't know how to distribute the watchedFolders among them.
    Even though you can specify the Watch Folders once the instances are up and running.. but in case if you close the instances and start them again.. only one instance will have all the watched folders with it.
    So don't know the solution to this, anyone pls help
    Thanks in Advance
    Naveen Sharma

  • Can Acrobat 9 Multi-Thread (use all my cpu cores)

    i have several 700+ page thick PDF documents i want to run OCR on. i can batch run them just fine, however i cannot get adobe to use more than one core of my 8 core iMac. so the process takes needlessly long because 87% of my CPU power is just sitting idle. i also cannot do anything with adobe while it is running its OCR program.
    is there a way to force acrobat to be multi-threaded?
    is there a way to use it for other things while its working?

    Nope, no version of Acrobat is a multithreaded application. See the first bullet point: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/DevFAQ_Introduction.21.16.ht ml

  • Multi-thread failure - Error in assignment

    Hello
    I have a c++ program processor running under Windows XP with Oracle 9i. My program access to oracle by an ODBC driver version 9.2.0.4.0. It could be launched in multi-thread to increase performance. When I launch it with one thread everything is fine. When I use several threads I have problems. ODBC driver returns to me a "error in assignment ... General error" message and my updates queries failed. Under SQl server it works without problems. It seems to be a kind of deadlock. When I disable check box in my odbc driver of "enable query timeout" my program encounter a problem and freezes...
    Could someone help me ?

    user13335017 wrote:
    I have thought of the above solutions as workable, however, it is not. Some exhibited errors are:
    A. "Attempt to use database while environment is closed." This error applies to 2, 3 and 4 all the way;
    B. "Attempt to read / write database while database is closed." This error applies to 3 in particular;
    C. "Attempt to close environment while some database is still open." This error applies to 5.
    Please help me with designing a better strategy to solve the concurrent issue. Many thanks in advance.All these are expected errors. You should design the application so that you do not close an environment handle while database handles are still open, keep database handles open for as long as operations need to be performed on the underlying databases, open the database handles after opening the database handles, and close database handles before closing the environment handle.
    In short, in pseudo-code, you should have something like this:
    - open environment handle,
    - open database handles,
    - perform whatever operations are needed on the databases,
    - close database handles,
    - close environment handle.
    You can refer to the Getting Started with Data Storage and the Getting Started with Transaction Processing guides appropriate for the API you are using, from the Berkeley DB documentation page.
    Regards,
    Andrei

  • Multi threading under single file channel

    Hi,
      We have File-Proxy scenario .
    We are using fCC sender channel and using
    recordset sequence as varaibale
    recordsets per message was 250.
    When large size file like 2GB was processed, PI is taking 45-50 min to process the file and from proxy end its taking 8 hrs to process this file.
    we are using one channel and 250 recordsets per message by chunking file and process to target. We are following EOIO for sequence for these chunk files.
    with this approach in PI target system proxy is taking huge time to process.
    experts suggested using multi threading and multiple channels are the ideal solution for this issue.
    am expecting with multiple channels and multi threading  will cause issue for receiver proxy  because of more objects and current approach is fine.
    Please suggest any other alternatives we can acheive in PI with respect to this issue?
    Note: I checked blog for file chunk option under Adv parameters and I cant use that here as FCC and Mapping is there .
    Rgds,
    aman

    Hi Aman,
    We had file to proxy interface and the XML payload of the proxy was around 400mb...to reduce the time taken in PI in mapping step we reduced the XML payload of the proxy by cutting the XML tagnames.
    for example an xml field <firstname>Anand</firstname> was converted to <f>Anand</f>
    with this we were able to achieve about 40-50% reduction in XML payload the file and a good improvement in the time taken by PI mapping to process the file.
    Hope it helps,
    Thanks,
    Anand

  • Multi-threading

    Hi folks,
    I need to have one Connection object and multiple Statement objects created from this Connection Object. Is it safe to do this from a multi-threaded application?
    Does createStatement() destroy any previously created Statement?

    You can have multiple statements in different threads coming of the same connection.
    But, all such statements will be part of the same transacion. A DML in one thread will be reflected in a query in another thread.
    If this not what you wanted, then you can have a connection pool and get connections from it in the individual threads.

  • Multi-Threaded server using  ThreadPool

    Dear friends,
    I am writing a client-server program in which the client and server communicate using SUN-RPC. The client reads a file containing some numbers and then spawns threads which it uses to request the server for a service. These threads are executed using a thread pool. Till this time, it's working fine. But when it comes to the server, the real trouble begins because it too needs to be made a multi-threaded one using thread pooling. The server has to capture the call information for each request for the service and then pass this information to a thread/runnable object in whose run() method the code for execution of the service would be present. Since the tasks(requests for the service) are not present already, i am unable to execute the server side threads in a loop using a thread pool. How to solve this problem? Kindly help.
    Thanks,
    Subhash

    The server has to capture the call information for each request for the serviceWhy?
    and then pass this information to a thread/runnable object in whose run() method the code for execution of the service would be present.Why can't the run() method get the call information when it starts? That's what's normally done. The server's accept loop mustn't do any other I/O: otherwise a rogue client can block the server complete.y

  • Multi-threading in Flash Builder 4.6

    Hello All,
    I am a new user of Flex and Flash Builder 4.6.
    Is there any built-in mechanism that allows to implement multi-threading in Flex/Flash Builder 4.6?
    I have done a little research via the Internet regarding this issue, and I understand that there are ways to implement multi-threading, but I am interested in a built in mechanism.
    Thanks in advance,
    Felix.
    P.S. Some links regarding this issue:
    http://cookbooks.adobe.com/post_Is_multi_threading_possible_in_Flash_or_ActionScri-12026.h tml
    http://www.flexjunk.com/2009/01/15/multi-threading-in-flexair/
    http://blogs.infosupport.com/flex-4-a-multi-threading-solution/

    Wokrers has been just announced today:
    http://www.bytearray.org/?p=3705
    Be patient around 3 more months and it will be out of the box.
    C

  • Multi-Thread application and common data

    I try to make a multi-Thread application. All the Threads will update some common data.
    How could I access the variable �VALUE� with the Thread in the following code:
    public class Demo {
    private static long VALUE;
    public Demo(long SvId) {
    VALUE = 0;
    public static class makeThread extends Thread {
    public void run() {
    VALUE++;
    public static long getVALUE() {
    return VALUE;
    The goal is to get the �VALUE� updated by the Thread with �getVALUE()�
    Thanks for your reply
    Benoit

    That code is so wrong in so many ways......
    I know you're just experimenting here, learning what can and can't be done with Threads, but bad habits start early, and get harder to kick as time goes on. I am going to give a little explanation here about what's wrong, and what's right.. If you're going to do anything serious though, please, read some books, and don't pick up bad habits.
    Alright, The "answer" code. You don't use Thread.sleep() to wait for Threads to finish. That's just silly, use the join() method. It blocks until the threads execution is done. So if you have a whole bunch of threads in an array, and you want to start them up, and then do something once they finish. Do this.
    for(int k=0; k<threads.length; k++) {
      threads[k].start();
    for(int k=0; k<threads.length; k++) {
      threads[k].join();
    System.out.println("All Threads Done");Now that's the simple problem. No tears there.
    On to the java memory model. Here where the eye water starts flowing. The program you have written is not guarenteed to do what you expect it to do, that is, increment VALUE some amount of time and then print it out. The program is not "Thread Safe".
    Problem 1) - Atomic Operations and Synchronization
    Incrementing a 'long' is not an atomic operation via the JVM spec, icrementing an int is, so if you change the type of VALUE to an int you don't have to worry about corruption here. If a long is required, or any method with more then one operation that must complete without another thread entering. Then you must learn how to use the synchronized keyword.
    Problem 2) - Visiblity
    To get at this problem you have to understand low level computing terms. The variable VALUE will NOT be written out to main memory every time you increment it. It will be stored in the CPUs cache. If you have more then one CPU, and different CPUs get those threads you are starting up, one CPU won't know what the other is doing. You get memory overwrites, and nothing you expect. If you solve problem 1 by using a synchronized block, you also solve problem 2, because updating a variable under a lock will cause full visiblity of the change. However, there is another keyword in java.. "volatile".. A field modified with this keyword will always have it's changes visible.
    This is a very short explaination, barely scratching the surface. I won't even go into performance issues here. If you want to know more. Here's the resources.
    Doug Lea's book
    http://java.sun.com/docs/books/cp/
    Doug Lea's Site
    http://g.cs.oswego.edu
    -Spinoza

Maybe you are looking for