Multi-thread BackgroundWorker

Hi, 
Is BackgroundWorker a recommended way to write a multi-threading application? If not, what is the preferred way for multi-threading programming?
Thanks in advance!

Thanks for the comments.
Below is the scenario:
A main application is monitoring any incoming files in a network folder.
Whenever a new file turns up, application will start a BackgroundWorker to process the file.
There may be many files constantly go to this folder
Q: do I need to create a BackgroundWorker for each individual file?
Thanks for your help.

Similar Messages

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

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

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

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

  • Memory leaks and multi threading issues in managed client.

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

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

  • How to write a multi threaded Cache Event Listener

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

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

  • Multi-Threaded FTP

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

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

  • Multi Thread Server over TCP/IP

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

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

  • Running a Java Multi Thread Program in database

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

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

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

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

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

  • Acrobat 9 Pro Extended Distiller - Multi-threaded?

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

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

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

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

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

  • Multi-thread failure - Error in assignment

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

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

  • Multi threading under single file channel

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

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

  • Multi-threading

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

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

  • Multi-Threaded server using  ThreadPool

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

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

Maybe you are looking for