Allowing a method to lock its parent Object in Java

允我心安 提交于 2019-12-09 13:23:19

问题


Is there a way in Java to get a method to lock (mutex) the object which it is in?

I know this sounds confusing but basically I wan't an equivelent to this snippet of C# but in Java.

lock(this)
{
    // Some code here...
}

I've been tasked with reimplementing an API written in .Net into Java, and I've been asked to keep the Java version as similar to the .Net version as humanly possible. This isn't helped by the fact that the .Net version looked like it was transcribed from a C++ version which I don't have access to.

Anyway the above line appears in the C# version and I need something that does the same in Java.


回答1:


The equivalent of that is:

synchronized (this)
{
}

(And no, you shouldn't generally do it in either C# or Java. Prefer locking on private references which nothing else has access to. You may be aware of that already, of course - but I didn't want to leave an answer without the warning :)




回答2:


Assuming that the C++ code is a simple mutex, replace "lock" with "synchronized"

synchronized (this)
{
// ...
}

Here's the Java Concurrency tutorial for more info




回答3:


I'd recommend Brian Goetz's "Java Concurrency In Practice." It's an excellent book.

It can be a good thing to keep the synchronized block as small as possible. Using the synchronized modifier on the method is coarse-grained and sometimes necessary, but otherwise you can use another object to do it that keeps the block smaller.

Like this:

public class PrivateLock {
    private final Object myLock = new Object();
    @GuardedBy("myLock") Widget widget;

    void someMethod() {
        synchronized (myLock) {
            // Access or modify the state of widget
        }
    }
}



回答4:


You should also look into the java.util.concurrent package of the API (JDK 5.0+) for additional concurrency management objects such as semaphore, exchanger, etc

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html



来源:https://stackoverflow.com/questions/439302/allowing-a-method-to-lock-its-parent-object-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!