简体   繁体   English

在Java中实现全局锁

[英]Implementing a global lock in Java

I have a relatively simple (perhaps stupid) question regarding synchronisation in Java. 关于Java中的同步,我有一个相对简单(也许是愚蠢的)问题。

I have synchronisation blocks that acquire locks on various objects throughout my code. 我有同步块,在我的代码中获取各种对象的锁。 In some scenarios, I want to acquire a global lock that subsumes every other synchronisation statement in my code. 在某些情况下,我想获取一个全局锁,它包含我的代码中的每个其他同步语句。

Is there a fancy way to do this in Java without re-writing all the current synchronisation code? 有没有一种奇特的方法在Java中执行此操作而不重写所有当前的同步代码?

For example, 例如,

Thread t1 线程t1

synchronized (o1)
{
    synchronized (o2)
    {
        // ...
    }
}

Thread t2 线程t2

synchronized (global_lock)
{
    // ...
}

When thread t2 is inside the synchronised block, thread t1 should not be allowed to acquire the locks on o1 and o2. 当线程t2在同步块内时,不应允许线程t1获取o1和o2上的锁。

Many thanks if 非常感谢,如果

  1. It's not possible; 这是不可能的;
  2. It's a really bad idea ( sorry ). 这是一个非常糟糕的主意(对不起)。

It's deadlock-prone, since it forces you to have a pre-determined locking order for all locks, no matter where they are. 它容易出现死锁,因为它会迫使您对所有锁具有预先确定的锁定顺序,无论它们位于何处。

Usually it's a good idea, if you need to acquire two locks, to always have a predetermined order: 通常这是一个好主意,如果你需要获得两个锁,总是有一个预定的顺序:

synchronized(LOCK1) {
  synchronized(LOCK2) {

  }
}

But a global lock would need some sort of protocol - a global aquisition order - for all the locks. 但是全局锁需要某种协议 - 全局采购订单 - 用于所有锁。 And that may not be possible at all. 这根本不可能。 Most locks guard specific, self-contained, critical sections. 大多数锁具保护特定的,独立的关键部分。 They would be unaware that someone would 'yank' them out and aquire them and therefore would not be written to handle this situation. 他们不会意识到有人会“猛拉”他们并获取他们,因此不会被写入来处理这种情况。

So it's not possible, and you should be happy it's not. 所以这是不可能的,你应该感到高兴它不是。 Although it seems to be the easy way out, it would bring a lot of pain. 虽然这似乎是一个简单的方法,但它会带来很多痛苦。

Leaving aside the sheer horror of what you are proposing, you may want to consider using Aspect Oriented Programming (AOP) to "weave" additional synchronization/locking into your code at run time. 撇开你提议的绝对恐怖,你可能想要考虑使用面向方面编程(AOP)在运行时“编织”代码中的额外同步/锁定。 You should be able to do this without writing the source. 您应该能够在不编写源代码的情况下执行此操作。

There are many AOP options, including AspectJ and Spring AOP, which may be suitable depending on your environment. 有许多AOP选项,包括AspectJ和Spring AOP,它们可能适合您的环境。

The only feasible way to do it would be actually parse/modify/save (automatically) all the code. 唯一可行的方法是实际解析/修改/保存(自动)所有代码。 I did something like this for a project recently and it worked pretty good. 我最近为一个项目做了类似的事情并且工作得非常好。 We can talk more if you are interested. 如果您有兴趣,我们可以多说。

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

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