O que é Java Semaphore e Mutex – Java Concurrency MultiThread explicado com exemplo
Publicados: 2015-03-12Java Concurrency é um tópico muito amplo. Existem centenas de tutoriais e exemplos disponíveis para uso. Algum tempo atrás eu escrevi alguns tutoriais sobre Run Multiple Threads Simultaneamente em Java e diferentes tipos de Blocos Sincronizados.
Neste tutorial iremos abordar:
- Explicação do Mutex
- Explicação do Semáforo
- Dois exemplos com detalhes
Vamos começar
Let's keep this in mind
ao ler a explicação abaixo:
- Tome um exemplo de Comprador e Cliente
- O cliente está emprestando laptops
- O cliente pode vir e usar o Laptop - o cliente precisa de uma chave para usar um Laptop
- Após o uso - o cliente pode devolver o Laptop ao Shopper
O que é Mutex (Apenas 1 thread):
O cliente tem uma chave para um laptop. Um cliente pode ter a chave – emprestar um Laptop – no momento. Quando a tarefa termina, o Shopper entrega (libera) a chave para o próximo cliente da fila.
Official Definition
:
“Mutex é normalmente usado para serializar o acesso a uma seção de re-entrant code
que cannot be executed concurrently
por mais de um thread. Um objeto mutex permite apenas um thread em uma seção controlada, forçando outros threads que tentam obter acesso a essa seção a esperar até que o primeiro thread saia dessa seção. ”
Em outras palavras: Mutex = Mutually Exclusive Semaphore
O que é Semáforo (N threads especificados):
Digamos que agora o Shopper tenha 3 laptops idênticos e 3 chaves idênticas. Semáforo é o número de free identical Laptop keys
. A contagem de semáforos – a contagem de chaves – é definida como 3 no início (todos os três laptops estão livres), então o valor da contagem é decrementado à medida que o cliente está chegando. Laptop, a contagem de semáforos é 0. Agora, quando algum cliente devolve o Laptop, o semáforo é aumentado para 1 (uma chave livre), e dado ao próximo cliente na fila.
Official Definition
: “Um semáforo restringe o número de usuários simultâneos de um recurso compartilhado até um número máximo. Threads podem solicitar acesso ao recurso (diminuindo o semáforo) e podem sinalizar que terminaram de usar o recurso (incrementando o semáforo).”
Outro deve ler: Lazy Creation of Singleton ThreadSafe Instance
Exemplo-1: (Explicação abaixo)
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 |
package crunchify . com . tutorial ; import java . util . LinkedList ; import java . util . concurrent . Semaphore ; /** * @author Crunchify.com * */ public class CrunchifySemaphoreMutexTutorial { static Object crunchifyLock = new Object ( ) ; static LinkedList <String> crunchifyList = new LinkedList <String> ( ) ; // Semaphore maintains a set of permits. // Each acquire blocks if necessary until a permit is available, and then takes it. // Each release adds a permit, potentially releasing a blocking acquirer. static Semaphore semaphore = new Semaphore ( 0 ) ; static Semaphore mutex = new Semaphore ( 1 ) ; // I'll producing new Integer every time static class CrunchifyProducer extends Thread { public void run ( ) { int counter = 1 ; try { while ( true ) { String threadName = Thread . currentThread ( ) . getName ( ) + counter ++ ; mutex . acquire ( ) ; crunchifyList . add ( threadName ) ; System . out . println ( "Producer is prdoucing new value: " + threadName ) ; mutex . release ( ) ; // release lock semaphore . release ( ) ; Thread . sleep ( 500 ) ; } } catch ( Exception x ) { x . printStackTrace ( ) ; } } } // I'll be consuming Integer every stime static class CrunchifyConsumer extends Thread { String consumerName ; public CrunchifyConsumer ( String name ) { this . consumerName = name ; } public void run ( ) { try { while ( true ) { // acquire lock. Acquires the given number of permits from this semaphore, blocking until all are // available // process stops here until producer releases the lock semaphore . acquire ( ) ; // Acquires a permit from this semaphore, blocking until one is available mutex . acquire ( ) ; String result = "" ; for ( String value : crunchifyList ) { result = value + "," ; } System . out . println ( consumerName + " consumes value: " + result + "crunchifyList.size(): " + crunchifyList . size ( ) + "\n" ) ; mutex . release ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void main ( String [ ] args ) { new CrunchifyProducer ( ) . start ( ) ; new CrunchifyConsumer ( "Crunchify" ) . start ( ) ; new CrunchifyConsumer ( "Google" ) . start ( ) ; new CrunchifyConsumer ( "Yahoo" ) . start ( ) ; } } |
No tutorial acima CrunchifySemaphoreMutexTutorial.java
quando o CrunchifyProducer
adiciona threadName
ao objeto crunchifyList
linkedList ele pode sinalizar o semáforo.
O CrunchifyConsumer
pode então estar tentando adquirir o semáforo para que aguarde até que o CrunchifyProducer sinalize que um threadID foi adicionado. Ao sinalizar um dado adicionado, um dos consumidores será acordado e saberá que pode ler um objeto crunchifyList. Ele pode ler uma lista e depois voltar a tentar adquirir no semáforo.
Se nesse tempo o produtor escreveu outro pacote, ele sinalizou novamente e qualquer um dos consumidores irá ler outro pacote e assim por diante…
Em outras palavras:
1 2 3 |
CrunchifyProducer : Add an object o List - Semaphore . release ( 1 ) CrunchifyConsumer x N ) - Semaphore . acquire ( 1 ) - Read an object from List |

Resultado:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Producer is prdoucing new value : Thread - 01 Crunchify consumes value : Thread - 01 , crunchifyList . size ( ) : 1 Producer is prdoucing new value : Thread - 02 Google consumes value : Thread - 02 , crunchifyList . size ( ) : 2 Producer is prdoucing new value : Thread - 03 Yahoo consumes value : Thread - 03 , crunchifyList . size ( ) : 3 Producer is prdoucing new value : Thread - 04 Crunchify consumes value : Thread - 04 , crunchifyList . size ( ) : 4 . . . . . . . . . . . . . . . |
Como evitar a condição de corrida:
What if you have multiple Consumers?
No Tutorial Java acima Os consumidores (não o produtor) devem bloquear o buffer ao ler o pacote (mas não ao adquirir o semáforo) para evitar condições de corrida. No exemplo abaixo, o produtor também bloqueia a lista, pois tudo está na mesma JVM.
Exemplo-2:
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 |
package crunchify . com . tutorial ; import java . util . concurrent . Semaphore ; /** * @author Crunchify.com * */ public class CrunchifyJavaSemaphoreTutorial { private static final int MAX_CONCURRENT_THREADS = 2 ; private final Semaphore crunchifyAdminLOCK = new Semaphore ( MAX_CONCURRENT_THREADS , true ) ; public void crunchifyStartTest ( ) { for ( int i = 0 ; i < 10 ; i ++ ) { CrunchifyPerson person = new CrunchifyPerson ( ) ; person . start ( ) ; } } public class CrunchifyPerson extends Thread { @Override public void run ( ) { try { // Acquire Lock crunchifyAdminLOCK . acquire ( ) ; } catch ( InterruptedException e ) { System . out . println ( "received InterruptedException" ) ; return ; } System . out . println ( "Thread " + this . getId ( ) + " start using Crunchify's car - Acquire()" ) ; try { sleep ( 1000 ) ; } catch ( Exception e ) { } finally { // Release Lock crunchifyAdminLOCK . release ( ) ; } System . out . println ( "Thread " + this . getId ( ) + " stops using Crunchify's car - Release()\n" ) ; } } public static void main ( String [ ] args ) { CrunchifyJavaSemaphoreTutorial test = new CrunchifyJavaSemaphoreTutorial ( ) ; test . crunchifyStartTest ( ) ; } } |
Resultado:
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 |
Thread 11 start using Crunchify 's car - Acquire() Thread 10 start using Crunchify' s car - Acquire ( ) Thread 10 stops using Crunchify 's car - Release() Thread 12 start using Crunchify' s car - Acquire ( ) Thread 13 start using Crunchify 's car - Acquire() Thread 11 stops using Crunchify' s car - Release ( ) Thread 13 stops using Crunchify 's car - Release() Thread 15 start using Crunchify' s car - Acquire ( ) Thread 14 start using Crunchify 's car - Acquire() Thread 12 stops using Crunchify' s car - Release ( ) Thread 14 stops using Crunchify 's car - Release() Thread 16 start using Crunchify' s car - Acquire ( ) Thread 15 stops using Crunchify 's car - Release() Thread 17 start using Crunchify' s car - Acquire ( ) Thread 17 stops using Crunchify 's car - Release() Thread 18 start using Crunchify' s car - Acquire ( ) Thread 19 start using Crunchify 's car - Acquire() Thread 16 stops using Crunchify' s car - Release ( ) Thread 18 stops using Crunchify 's car - Release() Thread 19 stops using Crunchify' s car - Release ( ) |