简体   繁体   English

在多线程环境中运行应用程序

[英]Running application in a multithreaded environment

In the application,a heavy file is being loaded in a function.在应用程序中,一个重文件被加载到 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. function,然后应用程序由于创建了多个对象和多个线程加载同一个文件而崩溃。 If a single thread calls the function, then the application becomes slow as each thread is waiting for the previous thread to be completed.如果单个线程调用 function,则应用程序会变慢,因为每个线程都在等待前一个线程完成。 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.通常你有一个用于用户交互的 UI 线程和 N 个工作线程。 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.文件加载 function 只能由工作线程调用,如果加载过程已经开始,您必须防止其他工作线程访问 function。

Consider using:考虑使用:

With above you can implement two strategies:有了上面,您可以实施两种策略:

  1. prevent any function call if function is running already如果 function 已经在运行,则阻止任何 function 调用
  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?我认为你需要做 1. - 为什么要多次加载同一个文件?

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.您需要确保 isFileLoaded 仅写入同步的 function 内部。 In code above function is synchronized by class instance.在上面的代码中 function 由 class 实例同步。

Most likely your application crashes due to OutOfMemory .您的应用程序很可能由于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 -xmx的增加
  2. Use NIO to process the file使用 NIO 处理文件
  3. You can yourself, instead of NIO, load the file into native memory您可以自己而不是 NIO 将文件加载到本机 memory
  4. Make a cache for the function and save the cached file locally on the application为 function 做一个缓存,并将缓存文件本地保存在应用程序上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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