Other way to synchronize method

末鹿安然 提交于 2019-12-07 00:05:47

问题


How to synchronize method in java other than using synchronized keyword?


回答1:


You could use the java.util.concurrent.locks package, especially Lock interface:

Lock l = ...; 
l.lock();
try {
    // access the resource protected by this lock
} finally {
    l.unlock();
}

See here.




回答2:


Depends on you concrete needs.

See Java concurrent package for higher level synchronization abstractions. Note that they may still use synchronized underneath ...




回答3:


you can use Lock classes provided in java.util.concurrent.locks package

see http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/util/concurrent/locks/Lock.html




回答4:


That depends on what you're trying to do. Are you looking out of curiosity or is there a specific reason?

If you are trying to speed up your multi-threaded methods, try synchronizing or locking around specific sections, or avoiding the threading issues altogether; make shared data final, make static (non-shared) data ThreadLocal, use the atomic types from java.util.concurrent.atomic, use concurrent collections (from the java.util.concurrent packages), etc.

BTW, the java.util.concurrent stuff is only available in Java5 onwards, though there as a project to back-port the packages for Java 1.4 at http://backport-jsr166.sourceforge.net/

I'd recommend the the book 'Java Concurrency in Practice', by Brian Goetz.




回答5:


You could also use @Synchronized from Project Lombok to generate a private field that will be used as the lock for your method.




回答6:


You could use a synchronized block inside your method. This can be useful if you want two methods belonging to the same class to be synchronized separately.

private Object guard = new ...
public method(){
   synchronized(guard){
      \\method body
      ...
   }
} 

Although in most cases this suggests that you should really break your class up.



来源:https://stackoverflow.com/questions/5482981/other-way-to-synchronize-method

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