Using multi threading to access 2 RS232 ports

Hi,
I'm a beginner in multi threading, so this question may be a very basic one....
I'm Using TS3.5 + CVI 8.01 to communicate withs 2 RS232 ports.  I thought to use mult threading so I can process 2 steps in parallel rather than in series. 
This is what I do:
1) I defined 2 subsequences, each of them call the same CVI function.  I use the sub sequence parameters to transfer the com number.
2) My CVI application includes one dll for this specific project and another one, a general dll to handle RS232 functions.  The RS232 dll uses one global buffer than collects all the traffic on the com. 
QUESTIONS:
1) What happens when 2 seperate threads run the same function in the RS232 dll?  (in terms of memory etc...).  Does each one use a different buffer (in terms of memory allocation), or, both of them writes to the same buffer?   Obviously, if they writes to the same buffer, then, my function will not operate properly.
2) What happens in TestStand after the 2 steps in new threads have finished their execution?  does the next step run back in the same threads the sequence run before?
Thanks
Rafi

Rafi,
Glad to hear you were able to make some ground on your application. As for all of your questions, I'll try to answer as many as I can.
First, when you are talking about your global buffer, is it created in TestStand or in the DLL itself? When you use DLLs, global variables or global structures are shared between all threads that call your DLL. On the other hand, if your buffer is declared inside of the DLL it is global for the DLL but not shared and would be a separate buffer for each call.
With your run-time error in TS, it would definitely be helpful to have more information about the error. From what you explained (executing fine on the first call, but failing on future executions), it sounds like the resource is not being released after the first execution.
As far as a specific example for TestStand Multithreading, you'll want to look at the TestStand Development Library and, specifically, Multithreading in TestStand. If you look and browse through the Application Notes and Tutorials section, as well as the Technical Presentations section, you will learn a great deal about multithreading and what options you have in TestStand. For a specific example, you may want to look at This Example. You could also look in the <TestStand>\Examples (where <TestStand> is the directory where TS is installed) at the MultiUUT example for an example of multithreading in TS. These examples may not be exactly what you need, but they should give you a jump start.
As far as making your DLL multithread safe, it is definitely not necessary; however, there are some significant advantages described in this article: Designing Thread-Safe DLLs. It is an MSDN article that focuses on Visual Basic, but it has some helpful information that can apply to C as well.
Hopefully this can help you move further. I have attached a list of links at the end of this post with other helpful links for you as well. Keep us posted with your progress.
Matt Mueller
NI
Links:
General Information on Multithreading for C Programmers
Building Multithreading Applications with LabWindows/CVI
Multithreading in LabWindows/CVI
Easy Multithreading Programming in LabWindows/CVI
Multithreading for Rookies

Similar Messages

  • How can i use multi threading in labview?

    i want to run a Digital storage oscilloscope and an energ ratio meter simultaneously using labview. i am using GPIB interfacing and windows XP. how can i do this using multi threading. Bot the instruments shd run and give data at the same time.

    You can't do this - at least not with a single GPIB board. It has nothing to do with threading or LabVIEW. There can only be one talker at a time over the bus. Depending on the instruments, you could probably set them up to take measurements simultaneously but you have to sequentially poll them to get the data.

  • Using multi-thread in RMI

    i know how to do a simple RMI program, but now i want to have a multi-threaded server to support the client. could any one tell me how to do this (using Thread in RMI) ??
    thx.
    Mo

    Well, you kind of answered your own question.
    An RMI server is inherently multi-threaded. This means that each remote request from a client is a separate thread, and can execute simultaneously with requests from other clients. In fact, your biggest problem will probably be to identify the places where access to objects must be synchronized, so that simultaneous requests do not conflict.
    So what is it you have to do that RMI doesn't do?

  • How to use Multi Thread to make a animation

    Hello
    Currently i am writing a router simulator using Java SE 1.4.2. I am facing a problem that is I cannot use multithread to update my Jframe animation.
    Here i give my approach.
    My idea is I used a JPanel in JFrame and I used Graphics g draw all background in Jpanel and add it into Jframe. It works since there is no animation invovled. I want to do some animation based on this background which i draw. But all animation should be controled by other threads due to i want other threads can control all animation. But i hit a error which is nullpointexception. The reason looks like which i used another to do animation, it cannot find the reference which is point to the Jpanel and Jframe. May u teach me a correct way to do multi threads animation in Jframe? thanks.
    all the best and regards!

    A simple annimation moving a circle round a screen. This uses a model that defines the dynamics of the annimation, a view to display a visual representation of the model and an event system (observer/observable) to notify the view that the model has changed.
    I hope this helps.
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Test20041023 extends JFrame
        public Test20041023()
            super("Simple Annimation Demo");
            AnnimationModel annimationModel = new AnnimationModel();
            AnimationView animationView = new AnimationView(annimationModel);
            setContentPane(animationView);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
        private static class AnimationView extends JPanel
            private static final int PREFERRED_WIDTH = 512;
            private static final int PREFERRED_HEIGHT = 256;
            AnimationView(AnnimationModel annimationModel)
                // Save a reference to the model for use
                // when the view is updated
                annimationModel_ = annimationModel;
                // Listen for the events indicating that the model has changed
                annimationModel_.addObserver(new Observer()
                    public void update(Observable o, Object arg)
                        // All we need to do is to get the view to repaint
                        AnimationView.this.repaint();
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                // Update the view based on the information in the model.
                g.setColor(Color.red);
                // Convert the model positions to view positions
                // in this case by scaling to the actual width and height.          
                int xScreenPosition = scaleValue(annimationModel_.getX(), getWidth() - 20 ) + 5;
                int yScreenPosition = scaleValue(annimationModel_.getY(), getHeight() - 20 ) + 5;
                // Display the position of the point
                g.fillOval(xScreenPosition, yScreenPosition, 10, 10);
            private int scaleValue(double v, double size)
                return (int)((v+1.0)*0.5 * size + 0.5);
            public Dimension getPreferredSize()
                return new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT);
            // The saved reference to the model
            private AnnimationModel annimationModel_;
        private static class AnnimationModel extends Observable
            AnnimationModel()
                Thread annimationThread = new Thread()
                    public void run()
                        // Loop forever updating the model
                        // and notifying the observers.
                        while(true)
                            // Wait 0.05 seconds until the next frame update point
                            try
                                sleep(50L);
                            catch (InterruptedException e)
                                // Nothing to do
                            // Update the model - in this case it is very simple
                            theta_ += 0.1;
                            // Notify the observers
                            setChanged();
                            notifyObservers();
                annimationThread.start();
            // Model access methods
            public double getX()
                return Math.cos(theta_);
            public double getY()
                return Math.sin(theta_);
            // The angular position of the point
            private double theta_;
        // Simple test main
        static public void main(String[] args)
            new Test20041023().setVisible(true);
    }

  • Accessing RS232 Port (Comm Port) from Applet

    I have an interesting "problem". I would like to create an applet that allows me to read the Comm port of the client machine but obviously I get a security exception when I try to do this. Firstly is this possible (I know it can be done from an application)? If so, how would I go about doing it?
    Thanks,
    Rishi

    you need to install the jre, and place the win32.dll at JavaSoft\JRE\1.3.1_06\bin, that properties file place at JavaSoft\JRE\1.3.1_06\lib, comm.jar at JavaSoft\JRE\1.3.1_06\lib\ext\
    and in ur code try to use it to open ur com port
    public String test() {
              String drivername = "com.sun.comm.Win32Driver";
              try
                   CommDriver driver = (CommDriver) Class.forName(drivername).newInstance(); driver.initialize();
              catch (Throwable th)
                   {* Discard it */}
              drivername = "javax.comm.*";
              try
                   CommDriver driver = (CommDriver) Class.forName(drivername).newInstance(); driver.initialize();
              catch (Throwable th)
                   {* Discard it */}
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    if (portId.getName().equals("COM2")) {
    //if (portId.getName().equals("/dev/term/a")) {
    try {
    serialPort = (SerialPort)
    portId.open("SimpleWriteApp", 2000);
    } catch (PortInUseException e) {}
    try {
    outputStream = serialPort.getOutputStream();
    } catch (IOException e) {}
    try {
    serialPort.setSerialPortParams(9600,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {}
                             int i=0;
                             while(true)
         try {
                                       messageString="hi";
                                       System.out.println(i++);
         outputStream.write(messageString.getBytes());
         } catch (IOException e)
                                       System.out.println(e);
                                       messageString=String.valueOf(e);
              return messageString;
    and yet u need to signed the applet
    1.     Compile the applet
    2.     Create a JAR file
    3.     Generate Keys
    4.     Sign the JAR file
    5.     Export the Public Key Certificate
    6.     Import the Certificate as a Trusted Certificate
    7.     Create the policy file
    8.     Run the applet
    Susan
    Susan bundles the applet executable in a JAR file, signs the JAR file, and exports the public key certificate.
    1.     Compile the Applet
    In her working directory, Susan uses the javac command to compile the SignedAppletDemo.java class. The output from the javac command is the SignedAppletDemo.class.
    javac SignedAppletDemo.java
    2.     Make a JAR File
    Susan then makes the compiled SignedAppletDemo.class file into a JAR file. The -cvf option to the jar command creates a new archive (c), using verbose mode (v), and specifies the archive file name (f). The archive file name is SignedApplet.jar.
    jar cvf SignedApplet.jar SignedAppletDemo.class
    3.     Generate Keys
    Susan creates a keystore database named susanstore that has an entry for a newly generated public and private key pair with the public key in a certificate. A JAR file is signed with the private key of the creator of the JAR file and the signature is verified by the recipient of the JAR file with the public key in the pair. The certificate is a statement from the owner of the private key that the public key in the pair has a particular value so the person using the public key can be assured the public key is authentic. Public and private keys must already exist in the keystore database before jarsigner can be used to sign or verify the signature on a JAR file.
    In her working directory, Susan creates a keystore database and generates the keys:
    keytool -genkey -alias signFiles -keystore susanstore -keypass kpi135 -dname "cn=jones" -storepass ab987c
    This keytool -genkey command invocation generates a key pair that is identified by the alias signFiles. Subsequent keytool command invocations use this alias and the key password (-keypass kpi135) to access the private key in the generated pair.
    The generated key pair is stored in a keystore database called susanstore (-keystore susanstore) in the current directory, and accessed with the susanstore password (-storepass ab987c).
    The -dname "cn=jones" option specifies an X.500 Distinguished Name with a commonName (cn) value. X.500 Distinguished Names identify entities for X.509 certificates.
    You can view all keytool options and parameters by typing:
    keytool -help
    4.     Sign the JAR File
    JAR Signer is a command line tool for signing and verifying the signature on JAR files. In her working directory, Susan uses jarsigner to make a signed copy of the SignedApplet.jar file.
    jarsigner -keystore susanstore -storepass ab987c -keypass kpi135 -signedjar SSignedApplet.jar SignedApplet.jar signFiles
    The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
    5.     Export the Public Key Certificate
    The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
    The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
    5: Export the Public Key Certificate
    The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
    In her working directory, Susan uses keytool to copy the certificate from susanstore to a file named SusanJones.cer as follows:
    keytool -export -keystore susanstore -storepass ab987c -alias signFiles -file SusanJones.cer
    Ray
    Ray receives the JAR file from Susan, imports the certificate, creates a policy file granting the applet access, and runs the applet.
    6.     Import Certificate as a Trusted Certificate
    Ray has received SSignedApplet.jar and SusanJones.cer from Susan. He puts them in his home directory. Ray must now create a keystore database (raystore) and import the certificate into it. Ray uses keytool in his home directory /home/ray to import the certificate:
    keytool -import -alias susan -file SusanJones.cer -keystore raystore -storepass abcdefgh
    7.     Create the Policy File
    The policy file grants the SSignedApplet.jar file signed by the alias susan permission to create newfile (and no other file) in the user's home directory.
    Ray creates the policy file in his home directory using either policytool or an ASCII editor.
    keystore "/home/ray/raystore";
    // A sample policy file that lets a JavaTM program
    // create newfile in user's home directory
    // Satya N Dodda
    grant SignedBy "susan"
         permission java.security.AllPermission;
    8.     Run the Applet in Applet Viewer
    Applet Viewer connects to the HTML documents and resources specified in the call to appletviewer, and displays the applet in its own window. To run the example, Ray copies the signed JAR file and HTML file to /home/aURL/public_html and invokes Applet viewer from his home directory as follows:
    Html code :
    </body>
    </html>
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="600" height="400" align="middle"
    codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,1,2">
    <PARAM NAME="code" VALUE="SignedAppletDemo.class">
    <PARAM NAME="archive" VALUE="SSignedApplet.jar">
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
    </OBJECT>
    </body>
    </html>
    appletviewer -J-Djava.security.policy=Write.jp
    http://aURL.com/SignedApplet.html
    Note: Type everything on one line and put a space after Write.jp
    The -J-Djava.security.policy=Write.jp option tells Applet Viewer to run the applet referenced in the SignedApplet.html file with the Write.jp policy file.
    Note: The Policy file can be stored on a server and specified in the appletviewer invocation as a URL.
    9.     Run the Applet in Browser
    Download JRE 1.3 from Javasoft
    good luck! [email protected]
    i already give u many tips, i use 2 weeks to try this to success, hopw that u understand that, a result of success is not important, the process of how to get things done is most usefull!

  • Performance problem using multi-thread

    I am using berkeley db to store a int/double pair, and i randomly get 100,0000 results to check the performance . Using 1 thread, it cost about 1 Mins. But using 4 threads, it costs 4 Mins. More threads, lower performance. Is there Anyone know the reason?
    Env flags:
    envFlags=DB_CREATE | DB_INIT_MPOOL | DB_THREAD | DB_PRIVATE|DB_INIT_CDB;
    DB open flags: DB_THREAD
    and i use db->get method to get results.

    Berkeley DB 4.8 will be released soon and has features that address CMP/SMP scalability. We would appreciate your feedback on your experiences with it. Once available, please test it and post your results here, I'm sure you'll be pleasently surprised.
    regards,
    -greg

  • Using multi-threading: Setting a VI to be used for two sequences at same time

    I have two sequences running as two different threads. This is supposed to be in parallel but both sequences access the same VI, then they're not executing as parallel because one sequence use this VI then liberates it and the other sequence use it, and so on consecutively until both sequences finish. This is not what I want.
    How can I do to set this VI with any kind of property or something that can be accessed for both sequences at the same time?
    Thanks,

    Hi Margarita, you can set a VI to be reentrant (under VI Setup»Execution Options from TestStand, this function can also be used from LabVIEW) . Now depending on the king of VI you are using this can be something safe or can cause trouble. If the VI needs to keep information (for example a Functional Global Variable) or it is handling Hardware it can give you errors (for example trying to access the same DAQ at the same time from different task.
    If you need more information can you tell us what does this VI does?
    This Links might also be useful:
    When I Run Parallel TestStand Executions That Call the Same VI, Why Don't the VIs Run in Parallel?
    Differences Between Reentrant VIs (Preallocate), Reentrant VIs (Share Clones), VI Templates, and Dyn...
    Best Regards
    Benjamin C
    Senior Systems Engineer // CLA // CLED // CTD

  • Trouble rationalizing use of multi-threading in run of the mill servlets

    Hey everybody,
    While spending time writing an internal wiki article on servlets for work, I asked myself a very basic question: What does multi-threading buy average servlets where the business logic requires procedural handling of the request?
    Don't get me wrong: I appreciate the fact that servlet containers spawning a new thread being less expensive than spawning an entirely new process is helpful and efficient. Coming from a background in PHP, it is great how servlets maintain persistence. However, as more of my coworkers are required to gain proficiency in Java and designing servlets, it is a question that many will ask and aside from having real-time processing of data files and other arduous tasks, I cannot think of any instances of where multi-threading benefits the application.
    What are some of the ways that you are using multi-threading with web applications?
    How would you explain why and where you would want to use multi-threading to someone?
    Thank you in advance for your insight,
    Andy

    how can we pass arguments to the run ()method?Create classes which implement Runnable that take your runtime parameters as constructor arguments and store them.
    eg: if your single thread method is   static void foo (int quantity, String name) {
        for (int i=0; i<quantity; i++) {
          System.out.println(name);
    // caller code
      foo(7, "wombats");Then you can make a runnable implementation thus:public class Foo implements Runnable {
      final int quantity_;
      final String name_;
      public Foo (int quantity, String name) {
        quantity_ = quantity;
        name_ = name;
      public void run () {
        for (int i=0; i<quantity_; i++) {
          System.out.println(name_);
    // caller code
      new Thread(new Foo(7, "wombats")).start();
    You could overload this method to take parameters in
    your class that implements the Runnable interface,
    and then call the base run() method.I don't get what you mean by this; Runnable is an interface so there is no base class run() method, and a run() overloaded with extra parameters method wouldn't get called by the thread.
    Pete

  • Java multi-thread Applet and Multi-processor

    Hello,
    I have a JAVA applet which work fine on a mono-processeur machine and not fine at all on multi-processors.
    It use multi thread (for reading on socket) and some times, request are lost.
    Is that a matter of programming or a JVM bug ?
    This happens on Linux and Windows NT bi-processors.
    We hare using JAVA 1.3.0_02
    Thanks for your help
    [email protected]

    I have already have a look to javax.swing.SwingUtilities.invokeLater() but (I think) it don't work for my need.
    A graphic applet which create 2 threads : one for reading and one for writing on a socket.
    Request sent to the server are memorized in a vector, and once answer is received, the request is remove from vector and treated. Access to the list is protected by synchronize.
    Everything works fine one several plateforme (linux, windows 98/2000/NT, Solaris). The only problem is on multi-processor : request are lost !

  • 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 concept

    Hi All,
    Want to know how we can multi-thread a program for a particular PLSQL code in Oracle EBS for which the child thread doesn't consume any thread in the front-end even though it executes with user-specified threads?

    Hi;
    Please review below notes which could gives you some idea:
    How Does iPayment Use Multi Threading? [ID 983478.1]
    http://orabiz.blogspot.com/2010/06/ebs-plsql-multithreading-example.html
    Can I have multi-thread program in EBS
    Regard
    Helios

  • Multi-thread application recompile object with make but runs with old value

    Hi. I am working on a simulation in Java, and there is some behavior going on that I cannot understand. Granted, I'm a mechanical engineer, not a CS student (a fact that is probably made obvious by the code I'm posting below). The simulation comprises three parts: a controller, a robot, and a 3-d sensor. Here's the code for the "Simulation" application.
    class Simulation {
        void go() {
         ThreeDSensor sensorRunner = new ThreeDSensor();
         VSController controllerRunner = new VSController();
         KukaKR15SL robotRunner = new KukaKR15SL();
         Thread sensorThread = new Thread(sensorRunner);
         Thread controllerThread = new Thread(controllerRunner);
         Thread robotThread = new Thread(robotRunner);
         sensorThread.start();
         try {
             Thread.sleep(1000);  // Give sensorThread time to start in order to catch first triggers
         } catch(InterruptedException ex) {
             ex.printStackTrace();
         controllerThread.start();
         try {
             Thread.sleep(1000);  // Give controllerThread time to open the socket for communication with robotThread
         } catch(InterruptedException ex) {
             ex.printStackTrace();
         robotThread.start();
        public static void main(String[] args) {
         Simulation sim = new Simulation();
         sim.go();
    }I guess the big reason I'm using multi-threading is that once this simulation is working I want to be able to just run VSController alone and have it interface with a robot controller and a PC performing image processing. So with multiple threads I'm sending TCP and UDP messages around just like the final system will.
    I have made an object for my VSController that just stores values used by the simulation. That way I could have them all in one place instead of hunting through methods to change them. One example is "double noiseThreshold". Quickly, here is the code for "ControllerSettings.java".
    class ControllerSettings {
        final double cameraXOffset = 0;  // If > 0 then the origin of the camera CS is not on the center line of the lens
        final double cameraYOffset = 0;  // If > 0 then the origin of the camera CS is not on the center line of the lens
        final double cameraZOffset = 700;  // The distance that must be kept between the camera and the target
        // Error magnitude less than this is disregarded (in centimeters if roundingData else in millimeters)
        final double noiseThreshold = 60;
        final boolean estimatingEndPoints = false;  // If the controller is using two images per cycle then true
        final boolean roundingData = false;
        final boolean using3DData = true;  // How double[] sent from Matlab image processing is used
         * If the robot controller uses the output of this controller to command
         * motions in cartesian space then true.  This is used in two places: 1) initial guess of Jacobian,
         * and 2) "commandType" element sent to robot controller.
        final boolean useRobotControllerModel = false;
        final double thetaBumpValueForEstimationOfJacobian = .1;  // Distance each joint is jogged in estimation process
        final double bumpDistance = 50;  // Distance robot moves each time (magnitude of translation in mm)
        final double limitAngular = .5;  // Max amout robot joint will be commanded to rotate (in degrees)
    }And here is some pertinent code from "VSController.java".
    class VSController implements Runnable{
        ControllerSettings cSettings;  // Stores all the preferences used by the controller
        NGN controller;  // This is the controller algorithm.
        int dof;  // The degrees of freedom of the robot being controlled
        KukaSendData ksd;  // This provides communication to the robot.
        protected DatagramSocket socketForVisionSystem = null;
        ImageFeaturesData ifd;  // This parses and stores data from the image system.
        double[] errorVector;  // This is what's acted on by the algorithm
        PrintWriter errorTrackerOut = null;  // For analysis of error vector
        public void run() {
         VSController vsc = new VSController();
         vsc.go();
        public void go() {
         initWriters();
         cSettings = new ControllerSettings();
        public boolean isNoise() {
         boolean ret = false;
         double magnitude = 0;
         for (int i = 0; i < errorVector.length; i++) {
             magnitude += errorVector[i] * errorVector;
         magnitude = Math.sqrt(magnitude);
         if (magnitude <= cSettings.noiseThreshold) {
         System.out.println("VSController: magnitude (of errorVector) = " + magnitude +
                   ", threshold = " + cSettings.noiseThreshold); // Debug
    Now here's my issue: I change the value for "noiseThreshold" in "ControllerSettings.java" then run make from terminal (makefile code posted below) and rerun "Simulation". However, despite my changes to "ControllerSettings.java" the value for "noiseThreshold" is not changed, as evidenced by the output on the terminal screen:VSController: magnitude (of errorVector) = 6.085046125925263, threshold = 10.0 See, that value of 10.0 is what I used to have for noiseThreshold. I do not know why this value does not update even though I save the java file and execute make in between executions of Simulation. I would love it if someone could explain this problem to me.
    Here's the contents of makefile.
    JFLAGS = -cp ../Jama\-1\.0\.2.jar:../utils/:/usr/share/java/vecmath\-1\.5\.2.jar:.
    JC = javac
    .SUFFIXES: .java .class
    .java.class:
         $(JC) $(JFLAGS) $*.java
    CLASSES = \
         ControllerSettings.java \
         ImageFeaturesData.java \
         KukaKR15SL.java \
         ../utils/KukaSendData.java \
         NGN.java \
         Puma560.java \
         Robot.java \
         RobotSettings.java \
         Simulation.java \
         SimulationSettings.java \
         SixRRobot.java \
         Targets.java \
         TargetsSettings.java \
         ThreeDData.java \
         ThreeDSensor.java \
         VSController.java
    default: classes
    classes: $(CLASSES:.java=.class)
    clean:
         $(RM) *.classEdited by: raequin on Apr 5, 2010 1:43 PM

    I saw this explanation about what's causing my problem.
    "When the Java compiler sees a reference to a final static primitive or String, it inserts the actual value of that constant into the class that uses it. If you then change the constant value in the defining class but don't recompile the using class, it will continue to use the old value."
    I verified that the value updates if I also change something in VSController.java, forcing it to recompile. I think I will solve this problem by just making the variables in ControllerSettings no longer final (and then recompile VSController to make sure it takes effect!). Is there another solution? I saw intern(), but that seems to only apply to Strings.
    Thanks.

  • The speed of multi threads

    I desing a program to test the speed of using multi threads to add up from 0 to 1000000000
    As I know from some books ,I assumed that the multithread to caculate should faster than single thread , but what supprised me is that I was wrong , the result is that : 5 threads is slower than single thread ,and so did 10 threads slower than 5 threads !
    why ?

    "Adding up" a sequential series of numbers doesn't
    sound like a good application for multithreading.How
    did you divide up the responsibility among multiple
    threads?You use a divide-and-conquer strategy. The sequence is
    split into halves recursively down to a certain depth
    (sequence length) and distributed among the avilable
    processors.Thanks for the explanation, but I understand that - I assumed (perhaps incorrectly) that the OP is testing on a single-processor system (one reason why the threading didn't improve performance as expected) or that the actual code to accomplish the multithreading was improperly implemented (another reason). That's why I asked what the OP did to divide up the responsibility. :o)

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

  • Multi thread D/B access design.

    Hi,
    I'm trying to performance test a 3 tiered design from client > TCP/IP to Server > ODBC to MSQL.
    I have a multi thread requesting client which connects via sockets to the server.
    The server kicks off multithread servelets which create a connection via ODBC ( Or reuse an existing one ) and communicates the data back to the requesting client.
    However, no matter the number of threads/ports/connections/ODBC data sources/Device managers I use I always get a linear progression for the data I am accessing.
    ie 1 file of 1000 records is 390 milliseconds, 10 is 4600 milliseconds etc.
    Is there somethings simple I'm missing out to make the access to the server linear ?
    The only option I'm considering at the moment is that the MSQL V 7.0 I have is the free one with visual studio and so has been "enhanced" to provide reduced performance.
    Any ideas ?
    Cheers,
    Gary

    The answer to you question is JDBC-ODBC BRIDGE IS SYNCHRONIZED..meaning it is SINGLE THREADED. No matter how many threads you create to access your database, only one thread enters the monitor at a time. The monitor I am referring to is the process space allocated to the thread at any given time, in your case I am referring to the process space as the particular lines of code which are responsible for database access. Your problem can be solved if you go for other database drivers( like type 4 drivers ). There are a variety of mutithreadd drivers available for most of the databases. I have raised this question at Sun Seminars also , and apparently this seems to be the only solution..
    Cheers,
    Shafique Razzaque,
    Senior Apps Developer,
    Singapore.

Maybe you are looking for

  • How to send multiple files with it's original name over HTTPS using one CC?

    I am working on a File to HTTPs scenario. It is in production and working fine. Currently we send only one file and I have hard coded the name in the communication channel in the header fields. Now we have to send more files with different names and

  • F.81 picking documents without Reversal Reason

    Hello gurus, We are posting the provisional entries using a BAPI and then for reversal we use the T-Code --> F.81. When we are executing F.81, a list of documents are getting picked for reversal, which were posted using the BAPI. Please note that the

  • Saved? Where?

    I created a page document. I saved it to a folder where I have my "page" documents. It is there, it is not in the cloud but I can see it in "All My Files". Why is it not saved in the folder I designated?

  • Program crashes in Vista

    Hello again, I have been testing our projector program on a Vista Home Premium machine and it crashes for no reason. The message I am getting is Macromedia Director had to close. The program works fine on Windows XP. Does anyone know what could be ca

  • How do I do the partition of the hard drive?

    Mac Pro