Bonjour,
j'ai un petit problème avec le code suivant:
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 public class Test { public static void main(String[] args) { MonThread t1 = new MonThread("t1"); MonThread t2 = new MonThread("t2"); MonThread t3 = new MonThread("t3"); MonThread t4 = new MonThread("t4"); MonThread t5 = new MonThread("t5"); MonThread t6 = new MonThread("t6"); t2.start(); t1.start(); t3.start(); t4.start(); t5.start(); t6.start(); } } class MonThread extends Thread{ static TimeZone Tz_UTC = TimeZone.getTimeZone("UTC"); static DecimalFormat dfFlowID = new DecimalFormat ("00000"); static Object o=new Object(); public MonThread(String name){ super(name); } public void run(){ try{ for(int i=0; i<20000; i++){ synchronized(o){ long l = dfFlowID.parse("123").longValue(); } } System.out.println(this.getName()+" fini"); } catch(Exception e){ e.printStackTrace(); } } }
En gros, le thread va parser "123" 20000 fois via le DecimalFormat.parse(), et je lance 6 thread en même temps.
Résultat avec le synchronized(o):
les 6 threads se terminent correctement
Résultat en retirant le synchronized(o):
Les threads se plantent aléatoirement sur des exceptions variées:
"java.lang.NumberFormatException: empty String"
"java.lang.NumberFormatException: For input string: "E.3121323""
"java.lang.NumberFormatException: For input string: """
Et autres "multiple points" ...
En gros si je comprends bien la méthode DecimalFormat.parse doit être synchronisée, mais why? Il me semblait qu'il ne fallait synchroniser que les blocs où l'on modifie une variable commune, or ici la seule variable commune est l'instance de DecimalFormat.
Cette instance serait modifiée par le "parse" ?
Partager