首页 \ 问答 \ Java读写锁定要求,具有来自不同线程的锁定和释放(Java read & write lock requirement, with lock and release from different threads)

Java读写锁定要求,具有来自不同线程的锁定和释放(Java read & write lock requirement, with lock and release from different threads)

我试图找到一个不那么笨重的Java并发问题的解决方案。

问题的关键在于,当仍有工作线程处于活动状态时,我需要对块进行关闭调用,但关键的方面是每个工作任务都是异步生成和完成的,因此保持和释放必须由不同的线程完成。 一旦他们的工作完成,我需要他们以某种方式向关闭线程发送信号。 只是为了让事情更有趣,工作线程不能互相阻塞,所以我不确定信号量在这个特定实例中的应用。

我有一个解决方案,我认为安全地完成了这项工作,但是我对Java并发工具的不熟悉使我认为可能有一个更容易或更优雅的模式。 在这方面的任何帮助将不胜感激。

这是我到目前为止所做的,除了评论之外相当稀疏:

final private ReentrantReadWriteLock shutdownLock = new ReentrantReadWriteLock();
volatile private int activeWorkerThreads;
private boolean isShutdown;

private void workerTask()
{
   try
   {
      // Point A: Worker tasks mustn't block each other.
      shutdownLock.readLock().lock();

      // Point B: I only want worker tasks to continue if the shutdown signal
      // hasn't already been received.
      if (isShutdown)
         return;

      activeWorkerThreads ++;

      // Point C: This async method call returns immediately, soon after which
      // we release our lock. The shutdown thread may then acquire the write lock
      // but we want it to continue blocking until all of the asynchronous tasks
      // have completed.
      executeAsynchronously(new Runnable()
      {
         @Override
         final public void run()
         {
            try
            {
              // Do stuff.
            }
            finally
            {
               // Point D: Release of shutdown thread loop, if there are no other
               // active worker tasks.
               activeWorkerThreads --;
            }
         }
      });
   }
   finally
   {
      shutdownLock.readLock().unlock();
   }
}


final public void shutdown()
{
   try
   {
      // Point E: Shutdown thread must block while any worker threads
      // have breached Point A.
      shutdownLock.writeLock().lock();

      isShutdown = true;

      // Point F: Is there a better way to wait for this signal?
      while (activeWorkerThreads > 0)
         ;

      // Do shutdown operation.
   }
   finally
   {
      shutdownLock.writeLock().unlock();
   }
}

预先感谢任何帮助!

拉斯


I'm trying to find a less clunky solution to a Java concurrency problem.

The gist of the problem is that I need a shutdown call to block while there are still worker threads active, but the crucial aspect is that the worker tasks are each spawned and completed asynchronously so the hold and release must be done by different threads. I need them to somehow send a signal to the shutdown thread once their work has completed. Just to make things more interesting, the worker threads cannot block each other so I'm unsure about the application of a Semaphore in this particular instance.

I have a solution which I think safely does the job, but my unfamiliarity with the Java concurrency utils leads me to think that there might be a much easier or more elegant pattern. Any help in this regard would be greatly appreciated.

Here's what I have so far, fairly sparse except for the comments:

final private ReentrantReadWriteLock shutdownLock = new ReentrantReadWriteLock();
volatile private int activeWorkerThreads;
private boolean isShutdown;

private void workerTask()
{
   try
   {
      // Point A: Worker tasks mustn't block each other.
      shutdownLock.readLock().lock();

      // Point B: I only want worker tasks to continue if the shutdown signal
      // hasn't already been received.
      if (isShutdown)
         return;

      activeWorkerThreads ++;

      // Point C: This async method call returns immediately, soon after which
      // we release our lock. The shutdown thread may then acquire the write lock
      // but we want it to continue blocking until all of the asynchronous tasks
      // have completed.
      executeAsynchronously(new Runnable()
      {
         @Override
         final public void run()
         {
            try
            {
              // Do stuff.
            }
            finally
            {
               // Point D: Release of shutdown thread loop, if there are no other
               // active worker tasks.
               activeWorkerThreads --;
            }
         }
      });
   }
   finally
   {
      shutdownLock.readLock().unlock();
   }
}


final public void shutdown()
{
   try
   {
      // Point E: Shutdown thread must block while any worker threads
      // have breached Point A.
      shutdownLock.writeLock().lock();

      isShutdown = true;

      // Point F: Is there a better way to wait for this signal?
      while (activeWorkerThreads > 0)
         ;

      // Do shutdown operation.
   }
   finally
   {
      shutdownLock.writeLock().unlock();
   }
}

Thanks in advance for any help!

Russ


原文:https://stackoverflow.com/questions/6921530
更新时间:2023-03-25 09:03

最满意答案

对于第一次编辑,我建议您将对象更改为其他形式

var object = {
"10-10-2017": "Black friday",
"11-09-2017": "Some holiday",
"10-10-2017": "Fathers day"
}

var object =[
{"date":"10-10-2017","value":"Black friday"},
{"date":"11-09-2017","value":"Some holiday"},
{"date":"10-10-2017","value":"Fathers day"}
]

如果这有助于你这里的工作解决方案

var object = [{date:"10-10-2017",value:"Black friday"},{date:"11-09-2017",value:"Some holiday"},{date:"10-10-2017",value:"Fathers day"}];

var output =[];

object.forEach(function(value) {
  var existing = output.filter(function(v, i) {
    return v.date == value.date;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value += ' '+value.value
    
  } else {
    if (typeof value.value == 'string')
      value.value = value.value;
    output.push(value);
  }
});

console.log(JSON.stringify(output)); //returns [{"date":"10-10-2017","value":"Black friday Fathers day"},{"date":"11-09-2017","value":"Some holiday"}]


For the first edit I suggest that you change your object into other form from

var object = {
"10-10-2017": "Black friday",
"11-09-2017": "Some holiday",
"10-10-2017": "Fathers day"
}

to

var object =[
{"date":"10-10-2017","value":"Black friday"},
{"date":"11-09-2017","value":"Some holiday"},
{"date":"10-10-2017","value":"Fathers day"}
]

If that helps you here's the working solution

var object = [{date:"10-10-2017",value:"Black friday"},{date:"11-09-2017",value:"Some holiday"},{date:"10-10-2017",value:"Fathers day"}];

var output =[];

object.forEach(function(value) {
  var existing = output.filter(function(v, i) {
    return v.date == value.date;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value += ' '+value.value
    
  } else {
    if (typeof value.value == 'string')
      value.value = value.value;
    output.push(value);
  }
});

console.log(JSON.stringify(output)); //returns [{"date":"10-10-2017","value":"Black friday Fathers day"},{"date":"11-09-2017","value":"Some holiday"}]

相关问答

更多

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)