简体   繁体   中英

Running application in a multithreaded environment

In the application,a heavy file is being loaded in a function. If multiple threads try calling the same
function, then the application crashes due to multiple objects being created and multiple threads loading the same file. If a single thread calls the function, then the application becomes slow as each thread is waiting for the previous thread to be completed. Suggestions for a good approach to mitigate this issue !

Your code is lacking synchronization. Usually you have one UI thread for user interaction and N worker threads. File loading function should be called only by worker thread and you have to prevent other worker threads from accessing function if loading process started already.

Consider using:

With above you can implement two strategies:

  1. prevent any function call if function is running already
  2. wait for previous execution to complete and then block&execute it doesn't solve synchronization problem by default.

I think you need to do 1. - why load same file multiple times?

class FileLoader {

  private boolean isFileLoaded = false

  @WorkerThread
  public synchronized void loadFilePseudoCode() {
     if(isFileLoaded) return;
     if(startFileLoading()) isFileLoaded = true;
  }
}

You need to make sure that isFileLoaded is written only inside synchronized function. In code above function is synchronized by class instance.

Most likely your application crashes due to OutOfMemory . If several threads load large files into the application.

In blind (without code and example),i can advice the following:

  1. The increase of -xmx
  2. Use NIO to process the file
  3. You can yourself, instead of NIO, load the file into native memory
  4. Make a cache for the function and save the cached file locally on the application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM