¿Qué es Lock(), UnLock(), ReentrantLock(), TryLock() y en qué se diferencia del Bloque sincronizado en Java?]
Publicado: 2020-07-05
En este tutorial repasaremos Lock(), UnLock(), ReentrantLock(), TryLock() y cómo es diferente del Bloque sincronizado en Java.
Si también tiene preguntas a continuación, entonces está en el lugar correcto.
- Bloqueos en Java
- Ejemplo de bloqueo de Java y bloqueo de concurrencia vs sincronizado
- Tutorial de simultaneidad de Java: bloqueos reentrantes
- sincronización: uso adecuado de bloqueo/desbloqueo para Java
- java – Sincronización vs Bloqueo
- ejemplo de desbloqueo de bloqueo java
- mecanismo de bloqueo en java
- java bloquear desbloquear hilo diferente
Empecemos. Primero, entendamos cada uno de estos términos y luego repasaremos el ejemplo de trabajo.
Cerrar con llave():
java.util.concurrent.locks
. Un bloqueo es un mecanismo de sincronización de subprocesos como los bloques sincronizados, excepto que los bloqueos pueden ser más sofisticados que los bloques sincronizados de Java. Se trata de interfaces y clases que proporcionan un marco para bloquear y esperar condiciones distintas de la sincronización y los monitores integrados.
Desbloquear():
UnLock() libera el bloqueo de Object.
Bloqueo de reentrada ():
Un ReentrantLock
es propiedad del subproceso que se bloqueó con éxito por última vez, pero que aún no lo ha desbloqueado. Un subproceso que invoque el lock
regresará, adquiriendo con éxito el bloqueo, cuando el bloqueo no sea propiedad de otro subproceso. El método regresará inmediatamente si el hilo actual ya posee el bloqueo.
ProbarLock():
TryLock() adquiere el bloqueo solo si está libre en el momento de la invocación.
Consejo-1
Si simplemente está bloqueando un objeto, preferiría usar synchronized.
1 2 3 |
Lock . lock ( ) ; youMethod ( ) ; // Throws a NullPointerException! Lock . unlock ( ) ; // Here you never release the lock! |
Mientras que con sincronizado, es súper claro e imposible equivocarse:
1 2 3 |
synchronized ( myObject ) { doSomethingNifty ( ) ; } |
Detalles del ejemplo:
- Crear clase: CrunchifyLockTutorial.java
- Crear clases internas: Company y CrunchifyLoop
- Desde Main crea dos objetos de clase Empresa
- Inicie bucle de hilo para 10 en esos objetos
- Mientras Company1 habla con Company2, bloquea un objeto. Si al mismo tiempo, si
Company2
quiere hablar conCompany1
, entonces dice: Conflicto: el bloqueo ya existe. (Ambas empresas ya están en plática).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
package crunchify . com . tutorial ; import java . util . Random ; import java . util . concurrent . locks . Lock ; import java . util . concurrent . locks . ReentrantLock ; /** * @author Crunchify.com * */ public class CrunchifyLockTutorial { public static void main ( String [ ] args ) { final Company crunchify = new Company ( "Crunchify" ) ; final Company google = new Company ( "Google" ) ; new Thread ( new CrunchifyLoop ( crunchify , google ) ) . start ( ) ; new Thread ( new CrunchifyLoop ( google , crunchify ) ) . start ( ) ; } // Class CrunchifyLoop static class CrunchifyLoop implements Runnable { private Company companyName1 ; private Company companyName2 ; public CrunchifyLoop ( Company companyName1 , Company companyName2 ) { this . companyName1 = companyName1 ; this . companyName2 = companyName2 ; } public void run ( ) { Random random = new Random ( ) ; // Loop 10 for ( int counter = 0 ; counter < = 10 ; counter ++ ) { try { Thread . sleep ( random . nextInt ( 5 ) ) ; } catch ( InterruptedException e ) { } companyName2 . crunchifyTalking ( companyName1 ) ; } } } // Class Company static class Company { private final String companyName ; // ReentrantLock: Creates an instance of ReentrantLock. This is equivalent to using ReentrantLock(false) private final Lock lock = new ReentrantLock ( ) ; // Constructor public Company ( String name ) { this . companyName = name ; } public String getName ( ) { return this . companyName ; } public boolean isTalking ( Company companyName ) { Boolean crunchifyLock = false ; Boolean googleLock = false ; try { // tryLock: Acquires the lock only if it is free at the time of invocation. crunchifyLock = lock . tryLock ( ) ; googleLock = companyName . lock . tryLock ( ) ; } finally { if ( ! ( crunchifyLock && googleLock)) { if (crunchifyLock) { // unlock: Releases the lock. lock.unlock(); } if ( googleLock ) { companyName . lock . unlock ( ) ; } } } return crunchifyLock && googleLock; } public void crunchifyTalking ( Company companyName ) { // Check if Lock is already exist? if ( isTalking ( companyName ) ) { try { System . out . format ( "I'm %s: talking to %s %n" , this . companyName , companyName . getName ( ) ) ; } finally { lock . unlock ( ) ; companyName . lock . unlock ( ) ; } } else { System . out . format ( "\tLock Situation ==> I'm %s: talking to %s, but it seems" + " we are already talking. Conflicting. %n" , this . companyName , companyName . getName ( ) ) ; } } } } |
Producción:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
I 'm Crunchify: talking to Google Lock Situation ==> I' m Google : talking to Crunchify , but it seems we are already talking . Conflicting . I 'm Google: talking to Crunchify I' m Google : talking to Crunchify I 'm Crunchify: talking to Google I' m Google : talking to Crunchify I 'm Google: talking to Crunchify I' m Crunchify : talking to Google Lock Situation == > I 'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. Lock Situation ==> I' m Crunchify : talking to Google , but it seems we are already talking . Conflicting . Lock Situation == > I 'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. I' m Crunchify : talking to Google I 'm Google: talking to Crunchify I' m Google : talking to Crunchify I 'm Crunchify: talking to Google I' m Google : talking to Crunchify Lock Situation == > I 'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. Lock Situation ==> I' m Crunchify : talking to Google , but it seems we are already talking . Conflicting . I 'm Crunchify: talking to Google I' m Crunchify : talking to Google I 'm Crunchify: talking to Google I' m Crunchify : talking to Google |
Consejo-2

Puede lograr todo lo que hacen las utilidades en java.util.concurrent
con las primitivas de bajo nivel synchronized
, volatile
o wait
.