Another method synchronization method

How to synchronize a method in java besides using a synchronized keyword?

+6
java synchronization
source share
6 answers

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

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

See here .

+6
source share

Depends on specific needs.

See the Java parallel package for higher-level synchronization abstractions. Please note that they can use synchronized under ...

+2
source share

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

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

+1
source share

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

If you are trying to speed up multi-threaded methods, try synchronizing or blocking certain sections or avoiding threading problems at all; create general final data, create static (not general) ThreadLocal data, use atomic types from java.util.concurrent.atomic , use parallel collections (from java.util.concurrent packages), etc.

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

I would recommend Brian Goetz's book Java Concurrency in Practice.

+1
source share

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

+1
source share

You can 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 really need to break your class.

0
source share

All Articles