O que é Lock(), UnLock(), ReentrantLock(), TryLock() e como é diferente do Bloco Sincronizado em Java?]
Publicados: 2020-07-05
Neste tutorial, veremos Lock(), UnLock(), ReentrantLock(), TryLock() e como é diferente do Bloco Sincronizado em Java.
Se você também tem perguntas abaixo, então você está no lugar certo.
- Bloqueios em Java
- Exemplo de bloqueio de Java e bloqueio de simultaneidade vs sincronizado
- Tutorial de simultaneidade Java – Bloqueios reentrantes
- sincronização – Uso adequado de bloqueio/desbloqueio para Java
- java – Sincronização vs Bloqueio
- exemplo de desbloqueio de bloqueio java
- mecanismo de bloqueio em java
- java lock desbloquear thread diferente
Vamos começar. 1º vamos entender cada um desses termos e depois vamos ver o exemplo de trabalho.
Trancar():
java.util.concurrent.locks
. Um bloqueio é um mecanismo de sincronização de threads como blocos sincronizados, exceto que os bloqueios podem ser mais sofisticados do que os blocos sincronizados do Java. É uma interface e classes que fornecem uma estrutura para bloqueio e espera por condições distintas da sincronização e monitores internos.
Desbloquear():
UnLock() libera o bloqueio em Object.
ReentranteLock():
Um ReentrantLock
é de propriedade do último encadeamento bloqueando com êxito, mas ainda não o desbloqueando. Um encadeamento que invoca o lock
retornará, adquirindo o bloqueio com êxito, quando o bloqueio não pertencer a outro encadeamento. O método retornará imediatamente se o thread atual já possuir o bloqueio.
TryLock():
TryLock() adquire o bloqueio somente se estiver livre no momento da invocação.
Dica-1
Se você está simplesmente bloqueando um objeto, prefiro usar synchronized.
1 2 3 |
Lock . lock ( ) ; youMethod ( ) ; // Throws a NullPointerException! Lock . unlock ( ) ; // Here you never release the lock! |
Considerando que com sincronizado, é super claro e impossível errar:
1 2 3 |
synchronized ( myObject ) { doSomethingNifty ( ) ; } |
Detalhes do exemplo:
- Criar classe: CrunchifyLockTutorial.java
- Crie classes internas: Company e CrunchifyLoop
- De Main crie dois objetos da classe Company
- Inicie o loop de thread para 10 nesses objetos
- Enquanto Company1 fala com Company2 – ele bloqueia um objeto. Se ao mesmo tempo – se
Company2
quiser falar comCompany1
, então ele diz – Conflicting – Lock já existe. (Ambas as empresas já estão conversando).
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 ( ) ) ; } } } } |
Saída:
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 |
Dica-2

Você pode conseguir tudo o que os utilitários em java.util.concurrent
fazem com as primitivas de baixo nível como synchronized
, volatile
, ou wait
.