Bonjour à tous,
Cherchant une solution pour remplacer les callback RMI, je suis tombé sur le code d'une personne.
Il marche très bien mais j'ai un doute quand à l'utilisation de ses blocs synchronized.
Comme je ne suis pas une flèche en synchronization, je voulais connaître votre avis sur ce code. Présente t'il un risque d'interblocage ?
EDIT: Petite précision, ceci est le code de l'objet partagé (RMI) auquel les clients accèdent.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 public ServerEvent getServerEvent(ServerEvent prevEvent) throws RemoteException { ServerEvent evt; // First waiting if(prevEvent == null){ synchronized (mutex) { try { mutex.wait(); evt = eventQueue.getLast(); } catch (InterruptedException e) { evt = new ServerEvent(e.getMessage()); e.printStackTrace(); } } } else { synchronized (mutex) { while((evt = getNewerEvents(prevEvent)) == null){ try { System.out.println("waiting"); mutex.wait(); } catch (InterruptedException e) { evt = new ServerEvent(e.getMessage()); e.printStackTrace(); } } } } System.out.println("returning :" + evt.getMessage()); return evt; } private synchronized ServerEvent getNewerEvents(ServerEvent event){ boolean areNewerEvents = false; // Iterate older from to newer events StringBuffer message = new StringBuffer(); for (ServerEvent queuedEvent : eventQueue) { if(queuedEvent.getId() > event.getId()){ areNewerEvents = true; message.append(queuedEvent.getMessage()); message.append("\n"); } } if(areNewerEvents){ return new ServerEvent(message.toString()); } else { return null; } } //Méthode appelé par le serveur lorsqu'un nouvel évènement survient /** * Fires the specified event to all clients */ synchronized private void fireEvent(ServerEvent event){ if(eventQueue.size() > MAX_EVENTS_IN_QUEUE){ eventQueue.poll(); } eventQueue.offer(event); synchronized (mutex) { mutex.notifyAll(); } }
Partager