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)

Similar Messages

  • The problem about multi-thread in java application

    i have problem with the multi-thread in java application, i don't know how to stop and restart a thread safely, because the function thread.stop(),thread.suspend() are both deprecated.
    now what i can only do is making the thread check a flag(true or false) to determine whether to start or to stop, but i think this thread will always be in the memory and maybe it will lower the performance of the system, as the program i am developping is working under realtime enviorement.
    please help me about it. thanks !

    hi,
    you can stop a thread by exiting it's run()-method which in terms can be done by checking the interrupted-flag:
    public void run(){
    while(interrupted()){ //if the thread consists of a loop
    or
    public void run(){
    if(interrupted())return;
    if(interrupted())return;
    or by the use of the return-statement anywhere withing the run-method. Afterwards, that is when the thread is no longer needed, you clear all the references to the specific thread object by setting them to null:
    Thread t;
    ... //working
    t.interrupt(); //interrupting
    while(t.isAlive()){
    Thread.yield(); //wait till thread t has stopped
    t=null;
    best regards, Michael

  • Is the directory watcher multi-threaded once it calls the cfc?

    the docs say there's a single thread that watches the directory.  But say for example it finds 3 files and calls the cfc.  At that point do all 3 files run one at a time on a single thread in the order they came in, or do they run at the same time on multi-threads?

    I think I understood your questions. There were more than one, some implicit. Here are my answers:
    ColdFusion runs the directory-watcher in a single thread.
    During the execution of the same thread, ColdFusion detects whether of not a file has, or any number of files have, been added, deleted or changed.
    When ColdFusion calls the CFC, it does so in that same single thread. My guess is that any file add-events, delete-events and change-events are queued and handled one after the other.

  • Enterprise User and Multi Thread Server

    Hi,
    We are going to build a system which uses a configuration:
    10g2
    Enterprise User
    Multi Thread Server
    Client apps accesses db over JDBC/SSL
    Could some please share experience about issues regarding
    using Enterprise User and Multi Thread Server ?
    Is MTS transparant for Enterprise User authentication ?
    Regards,
    Cezary

    If you build simpserv with -t, and set MIN and MAXDISPATCHTHREADS, you
    should have an example of a multithreaded server.
         Scott
    Johan Philippe wrote:
    >
    We have been going to the documentation on multi-threading and contexting in servers
    on Tuxedo 7.1.
    And the impression so far is that apart from the function definitions there is
    not much information around.
    Didn't even find a simple example of a multi-threaded server in the Bea refs yet.
    Does anyone know/have such an example?
    And is anyone using multi-contexting in a server, because the limitation that
    only server-dispatched
    thread get a context puts quite a limitation on its usefullness.

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

  • Question using Java API in a multi threaded application for MDX queries

    Currently I’m building a web application that makes a lot of MDX calls using the Essbase Java API. Each time we run an MDX call we basically run the following code:
    IEssbase ess = IEssbase.Home.create(IEssbase.JAPI_VERSION);
    IEssDomain dom = ess.signOn(userName, password, false, null, "embedded");
    IEssCubeView cv = cv=dom.openCubeView("view", hostName, appName, cubeName);
    IEssOpMdxQuery op = cv.createIEssOpMdxQuery();
    op.setQuery(false,mdx,false,IEssOpMdxQuery.EEssMemberIdentifierType.NAME);
    cv.performOperation(op);
    IEssMdDataSet mddata = cv.getMdDataSet();
    cv.close();
    My questions is, is this the correct way to use the API in multi threaded environment where many users may be hitting the application at the same time? For every request do I need to create a separate IEssbase object and sign on to an IEssDomain? Or can I use a single IEssbase and IEssDomain object for the entire application? If not should I call the IEssDomain.signOff() method after each user’s request has completed? Which of the above objects are thread safe? I’m using Essabae 9.3.1. Any insight would be really appreciated.
    Thanks
    David

    Thanks for the input friend,
    I should have mentioned that in my application all
    connections to Essbase use the same user name and
    password so the filtering isn’t a concern. This is my
    first Java application using Essbase has a data
    source, I’m used to connecting to various SQL
    databases and I always use a connection pool, how is
    connection pooling handled in the Essbase java API?I'm not sure what happened to it since I never used it, but there used to be something called the High Availability Services or something that was essentially a connection pool for Essbase JAPI connections, but it required an extra license.
    Since you don't care about identity (everyone has full access to everything), you can create your own connection pool, but you'll have to manage your multithreading yourself. Its been this way since the beginning. The C API isn't/wasn't thread-safe either (we tried).

  • How to improve spreadsheet speed when single-threaded VBA is the bottleneck.

    My brother works with massive Excel spreadsheets and needs to speed them up. Gigabytes in size and often with a million rows and many sheets within the workbook. He's already refined the sheets to take advantage of Excel's multi-thread recalculation and
    seen significant improvements, but he's hit a stumbling block. He uses extensive VBA code to aid clarity, but the VB engine is single-threaded, and these relatively simple functions can be called millions of times. Some functions are trivial (e.g. conversion
    functions) and just for clarity and easily unwound (at the expense of clarity), some could be unwound but that would make the spreadsheets much more complex, and others could not be unwound. 
    He's aware of http://www.analystcave.com/excel-vba-multithreading-tool/ and similar tools but they don't help as the granularity is insufficiently fine. 
    So what can he do? A search shows requests for multi-threaded VBA going back over a decade.
    qts

    Hi,
    >> The VB engine is single-threaded, and these relatively simple functions can be called millions of times.
    The Office Object Model is
    Single-Threaded Apartments, if the performance bottleneck is the Excel Object Model operation, the multiple-thread will not improve the performance significantly.
    >> How to improve spreadsheet speed when single-threaded VBA is the bottleneck.
    The performance optimization should be based on the business. Since I’m not familiar with your business, so I can only give you some general suggestions from the technical perspective. According to your description, the size of the spreadsheet had reached
    Gigabytes and data volume is about 1 million rows. If so, I will suggest you storing the data to SQL Server and then use the analysis tools (e.g. Power Pivot).
    Create a memory-efficient Data Model using Excel 2013
    and the Power Pivot add-in
    As
    ryguy72 suggested, you can also leverage some other third party data processing tool
    according to your business requirement.
    Regards,
    Jeffrey
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • InfoPath: the multi-threading challenge

    Or to be more specific: calling a DataSource from a different thread.
    A project I'm working on includes an InfoPath form in which some heavy duty tasks are executed. These tasks can take over 10+ seconds to execute. To avoid the GUI to get stuck during execution, multi-threading is implemented. The problem lies in providing
    feedback to the user. Several methods have been used, but all end in the exceptions shown below.
    Unlike WinForms and such, InfoPath does not seem to provide a way to invoke the GUI. What we are trying to do is change field values to reflect the status of the process. This is done through the MainDataSource. I've tried several methods to call
    this datasource through another thread, like invoking a provided delegate, or execution context. However all these methods have similar results.
    When calling a method or property on the datasource the following exception is thrown:
    System.InvalidOperationException was unhandled
      Message="Operation is not valid due to the current state of the object."
      Source="Microsoft.Office.InfoPath.Client.Internal.Host"
      StackTrace:
           at Microsoft.Office.Interop.InfoPath.SemiTrust.ICLRExtensionsWrapper.IncrementSqmPoint(Int32 idDataPt)
           at Microsoft.Office.InfoPath.Internal.DataSourceHost.CreateNavigator()
           at Form1.FormCode.ContextCallbackMethod(Object obj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 74
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at Form1.FormCode.ThreadMethod(Object myParamsObj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 68
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)
    This seems to indicate the DataSource is locked for some reason. Even the ReadOnly property can not be read.
    When calling the SetValue method on an XPathNavigator provided by a datasource and passed through another thread, the following exception is thrown:
    System.AccessViolationException was unhandled
      Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
      Source="Microsoft.Office.InfoPath.Client.Internal.Host.Interop"
      StackTrace:
           at Microsoft.MsoOffice.InfoPath.MsxmlInterop.NativeHelpers.SetText(IXMLDOMNode* , Char* )
           at Microsoft.MsoOffice.InfoPath.MsxmlInterop.MsxmlNodeImpl.set_Text(String strText)
           at Microsoft.Office.InfoPath.MsxmlNavigator.SetValue(String value)
           at Form1.FormCode.DelegateMethod(XPathNavigator nav) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 81
           at Form1.FormCode.ThreadMethod(Object myParamsObj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 70
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)
    I have searched through the internet but am unable to find any useful information about this subject. There are only a few weeks remaining before the deadline. A work-around has been implemented, but since it requires additional active user interaction
    it is far from ideal. I hope you can help me in finding a solution.

    For anyone who is still interested all this time later....
    I wouldn't use a Dispatcher in InfoPath simply because InfoPath requires .Net 2.0 only and Dispatcher was not added until .Net 3.0 which means you would have to enforce installation of .Net 3.0 yourself.
    There is an easy alternative which is SynchronizationContext (more specifically a WindowsFormsSynchronizationContext).
    Also I suggest you do not use ThreadStart but rather use one of the more modern and well known threading paradigms. A good alternative is a BackgroundWorker.
    e.g.
    private BackgroundWorker _Worker;
    public void InternalStartup()
    InitializeWorker();
    ((ButtonEvent)EventManager.ControlEvents["Button"]).Clicked += new ClickedEventHandler(ButtonClick);
    public void InitializeWorker()
    _Worker = new BackgroundWorker();
    _Worker.WorkerReportsProgress = true;
    _Rorker.WorkerSupportsCancellation = true;
    _Worker.DoWork += new DoWorkEventHandler(_Worker_DoWork);
    _Worker.ProgressChanged += new ProgressChangedEventHandler(_Worker_ProgressChanged);
    _Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_Worker_RunWorkerCompleted);
    public void ButtonClick(object sender, ClickedEventArgs e)
    if (_Worker.IsBusy)
    _Worker.CancelAsync();
    else
    // Very important to include this line!
    AsyncOperationManager.SynchronizationContext = new WindowsFormsSynchronizationContext();
    _Worker.RunWorkerAsync();
    void _Worker_DoWork(object sender, DoWorkEventArgs e)
    // Do stuff in another thread and report back to the UI thread.
    object state;
    int percentage = 0;
    _Worker.ReportProgress(percentage, state).
    public void _Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    // This is called on the thread that started the worker.
    // In this case the UI thread which means it is safe to use the MainDataSource.
    CreateNavigator().SelectSingleNode("my:Main/my:Progress", NamespaceManager).SetValue(e.ProgressPercentage);
    void _Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    // Do anything you want to do on completion here.
    One thing of note is that the SynchronizationContext in InfoPath for some reason or other always seems to be Null. The result is that when you call RunWorkerAsync() it captures the current synchronization context (null) which means the default is used and
    a ProgressChanged is called on a new thread each time. To prevent this we need to manually set the context before calling RunWorkerAsync() which is done using the AsyncOperationManager.

  • Multi-threaded application crashing the VM

    Hi,
    I have a multi-threaded (about 120 threads) application which crashes without after running for a while.
    I get this in the windows event viewer
    Faulting application java.exe, version 0.0.0.0, faulting module kernel32.dll, version 5.2.3790.0, fault address 0x000017b1.
    Anyone knows why this would happen?
    - vineet

    Hi Alexis,
    Thanks for the response to my post!!
    Which version of the JVM?C:\>java -version
    java version "1.4.2_05"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_05-b04)
    Java HotSpot(TM) Client VM (build 1.4.2_05-b04, mixed mode)
    Are you using the -server option?I was not using this option earlier but even on using this the jvm crashes after running for sometime.
    I am using these jvm options now -
    java -server -Xss128K -Xms256M -Xmx512M
    - vineet

  • Clarification of the handle/body idiom in multi threaded applications

    Hello
    As some DBXML classes use the handle-body idiom (handle/body idiom in some docs), could someone please clarify the consequences of that in a multi threaded application like a web container?
    For 100% Java people, like me, this is known in the Java world as 'programming towards interfaces', or as the Bridge pattern; which is seen as good practice.
    Let's take an example. The class XmlQueryContext is not thread safe, but it has a copy constructor. Imagine that your web application has one XmlQueryContext, that we never use in a query, but that we prepare only to be copied in new threads. Is it thus safe to instantiate various new XmlQueryContexts using that copy constructor in various new threads and use them simultaneously?
    Thank you
    Koen
    PS What I am really asking here is if somebody could please translate the following to Java parlé:
    A copy constructor is provided for this class. The class is implemented using a handle-body idiom. When a handle is copied both handles maintain a reference to the same body.

    As a Java user you do not have to worry about how the C++ copy constructors behave. In the Java API if a copy constructor exists for the object, then the copy constructor will copy all of the original object's data into a new object (XmlContainer is the one exception to this rule, generally one should not use that copy constructor at all). So in short, what you plan to do will work.
    Lauren Foutz

  • 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

  • The problem of profiling a multi-thread flash game  using adobe scout cc

    I have a multi-thread flash game code, it can run perfectly. The main swf creates another swf which will connect to a remote server. I can get profiling information of the main swf  using adobe scout cc, but the problem is that I can't get profiling information of another swf ! The scout complains " can't start a session because the telemetry data isn't valid" for another swf. Although some times, the scout does not complain, the Summary Panel of scout provides information“We encountered an error while processing this session: Some of the data we present may not be correct". And the scout log file shows:
    Log file created: 2014/11/20 15:35:08
    11/20/2014 15:35:08.395 Scout starting up.
    11/20/2014 15:35:08.471 InitDNSService failed
    11/20/2014 15:36:47.055 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [100000,200000] is greated than its parent
    11/20/2014 15:36:47.057 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [200000,300000] is greated than its parent
    11/20/2014 15:36:47.058 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [300000,400000] is greated than its parent
    11/20/2014 15:36:47.058 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [400000,500000] is greated than its parent
    11/20/2014 15:36:47.061 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [500000,600000] is greated than its parent
    11/20/2014 15:36:47.062 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [600000,700000] is greated than its parent
    11/20/2014 15:36:47.063 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [700000,800000] is greated than its parent
    11/20/2014 15:36:47.063 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [800000,900000] is greated than its parent
    11/20/2014 15:36:47.064 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [900000,1000000] is greated than its parent
    11/20/2014 15:36:47.064 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1000000,1100000] is greated than its parent
    11/20/2014 15:36:47.064 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1100000,1200000] is greated than its parent
    11/20/2014 15:36:47.065 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1200000,1300000] is greated than its parent
    11/20/2014 15:36:47.065 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1300000,1400000] is greated than its parent
    11/20/2014 15:36:47.065 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1400000,1500000] is greated than its parent
    11/20/2014 15:36:47.066 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1500000,1600000] is greated than its parent
    11/20/2014 15:36:47.066 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1600000,1700000] is greated than its parent
    11/20/2014 15:36:47.066 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1700000,1800000] is greated than its parent
    11/20/2014 15:36:47.067 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1800000,1900000] is greated than its parent
    11/20/2014 15:36:47.067 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1900000,2000000] is greated than its parent
    11/20/2014 15:36:47.067 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2000000,2100000] is greated than its parent
    11/20/2014 15:36:47.068 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2100000,2200000] is greated than its parent
    11/20/2014 15:36:47.068 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2200000,2300000] is greated than its parent
    11/20/2014 15:36:47.068 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2300000,2400000] is greated than its parent
    11/20/2014 15:36:47.069 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2400000,2500000] is greated than its parent
    11/20/2014 15:36:47.069 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2500000,2600000] is greated than its parent
    11/20/2014 15:36:47.069 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2600000,2700000] is greated than its parent
    11/20/2014 15:36:47.070 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2700000,2800000] is greated than its parent
    11/20/2014 15:36:47.070 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2800000,2900000] is greated than its parent
    11/20/2014 15:36:47.070 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2900000,3000000] is greated than its parent
    11/20/2014 15:36:47.071 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [3000000,3100000] is greated than its parent
    11/20/2014 15:36:47.071 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [3100000,3200000] is greated than its parent
    11/20/2014 15:46:30.931 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [100000,200000] is greated than its parent
    11/20/2014 15:46:30.933 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [200000,300000] is greated than its parent
    11/20/2014 15:46:30.936 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [300000,400000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [400000,500000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [500000,600000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [600000,700000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [700000,800000] is greated than its parent
    11/20/2014 15:46:30.938 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [800000,900000] is greated than its parent
    11/20/2014 15:46:30.938 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [900000,1000000] is greated than its parent
    I run flash code directly on flash_player_11_7_sa.exe. I think the problem may have something to do with ActionScript Sampler of scout, because I can get the correct profiling information  without ActionScript Sampler.
    But I don't know what the information in the log file means.

    We are using Microsoft SQL Server 2008 . but it's well with MySQL & JBoss

  • How does the servlet implement the multi-thread feature?

    There is only one instance of every servlet in one wep application.
    When several clients invoke the doPost() method of the same servlet,the servlet can process their request respectively.
    So there much multi threads of one servelt.
    But the Servlet doesn't implement the Runnable interface of extends the Thread class.
    I wan't to know,how does the servlet/servlet container implement the multi-thread feature?

    Hi johnnylzb
    There is only one servlet instance existing.
    (assuming u have <load-on-startup>1</load-on-startup>)
    The server creates a thread for every request ..
    and all the threads access the same servlet instance.
    For this its not necessary for the Servlet to extend Thread or Runnable.
    hope this helps

  • Proble with multi-threaded app using the same connection

    have a multi-threaded app. The threads all share the
    same connection. They all do some selects / updates.
    The OS is NT 4.0 and the application server is weblogic
    Some times I am getting the error "java.sql.SQLException: Io exception: not in streaming mode"
    and some times I am getting "java.sql.SQLException: Io exception: Protocal violation
    Any Ideas?
    Regards
    Suresh

    Don't create threads.... Your threads should if they are necessary be reusable, your threads should call the connections it needs from the cache service with let's say a max number of N pools (each pool a max number of M connections), if the connection domain asked exists on cache a connection is asked for corresponding pool, if the connection domain is not on cache the less used domain is thrown away (all inner connections closed first) and substituted by the new one requested. While the pool is not full keep creating connections as the request came (and all existing connections are being held and not released), when M connections exists, a request should wait till a connection is released.
    If you can have 20 threads asking for the same connection and the max number of connections on pool is M=10, then yopur threads will wait for a connection being released. All this must be synchronized. You should set M the closest as possible to the normal number of requests you can imagine to happen the same time. You should get connection use it and release it right away if you can have a lot of requests.
    I hope this helps you.

  • The CPU utilization is 0% for the other remaining processes when multi threading is used

    I am new to AE ,so I am trying to render a project enabling multi threading process the additional processes are present but their utilization is 0% .
    I want to juice out every single CPU utiliaztion .
    ANy help is greatly appriciated,.
    My system specs:
    AMD 9690 4.7 Ghz 8 core
    32 GB DDR3
    C:\256 GB Solid Satte Raid 0
    GeForce 780 Ti DDR5 3GB

    It is very tempting to try and use all of your system resources and multiprocessing for all your projects, but this is not the way After Effects works. Many third-party plug-ins, many codecs, and many operations do not respond well to multiprocessing. All it takes is one process in your entire thread that is not MP aware to foul the whole thing and give you longer render times.
    You are also leaving zero processors for the rest of your computer. Not a wise idea.
    After effects renders one frame at a time. One HD frame even with multiple layers of pixel processing just isn't that much data. It does take a while to do the calculations, but expecting to have every one of your CPUs jacked up at 100% to render a single frame of video is expecting an awful lot.
    I would suggest that you read up on optimizing After Effects for your computer. Do not expect to be able to utilize 100% of your system resources at all times. That's just not the way processing video on a pixel by pixel basis works.
    Just a little FYI,  for 99% of my projects in After Effects I have render multiple frames simultaneously turned off. It just doesn't work with most of the things I do. Sorry for the disappointment.

Maybe you are looking for

  • No longer able to drag and drop files to an iPhone in iTunes.

    I accidentally unplugged my iPhone 3G before it was finished syncing in iTunes and I lost all of music, playlist, podcasts, etc. I had copied to it. The problem I am now having is that I can no longer drag and drop anything to my iPhone in the Device

  • Ipod not recognized by any MAC computer

    I have a 20gb IPOD 2nd generation which has worked fine until recent itunes and tiger software upgrade. Now Finder nor utilities (ipod updater) nor itunes will recognize the ipod when connected with firewire-- even in disc mode. Ipod is not recognize

  • Lost my ipod installation disk

    hi, iv just got my ipod back from repair and they have sent me a new one and since i sent it i purchased a new pc, does anyone know where i can download the installation disk? iv downloaded the latest itunes and ipod update and my pc recognises the i

  • How to detect DataGridColumn's width

    Hi, When I resize DataGridColumn, may I know if existing any methods to detect DataGridColumn's width after mouse release? Thanks,

  • My flash player doesnt display text

    so every time i goto youtube.com or listen.grooveshark.com, theres text it the flash player thats suppost to show up, for like the names of videos or music. but its not there any reason why, and how do i fix it...? i use google chrome but i've found