-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpresentation.html
498 lines (452 loc) · 24.5 KB
/
presentation.html
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Java Pitfalls</title>
<meta name="description" content="Errores que cometemos en Java una y otra vez">
<meta name="author" content="Carlos Sierra Andrés">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="pitfalls.css" id="theme">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' );
</script>
<script src="jquery-2.0.3.js"></script>
<style type="text/css" media="screen">
.ace_cursor {
border-left: 2px white solid;
}
section div.ace_content {
width: 960px;
}
section div.editor {
position: absolute;
right: 0;
bottom: 0;
top: 0;
text-align: left;
font-family: monospace;
font-size: 28px;
height: 400px;
width: 960px;
}
section {
font-family: Ubuntu;
}
section div.editor-whole {
top: -300px;
height: 700px;
}
section div.overcode {
margin-top: -200px;
}
</style>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section data-background="java%20tripping%20hazard.png" data-background-size="70%"></section>
<section>
<section>
<h3>Motivaciones</h3>
</section>
<section>
<h3>Es relativamente fácil encontrar información y ayuda para programadores noveles</h3>
</section>
<section>
<h3>¿Pero qué hay de la gente que tenemos experiencia ya en esto?</h3>
</section>
<section>
<h3>Esta charla no va a tratar sobre ningún producto nuevo...</h3>
</section>
<section>
<h3>sino sobre los errores y fallos que cometemos una y otra vez.</h3>
</section>
<section>
<h3>No porque no seamos buenos desarrolladores, creo...</h3>
</section>
<section>
<h3>sino porque no podemos habernos encontrado con todo</h3>
</section>
<section>
<h3>muchas veces utilizamos diferentes lenguajes de programación</h3>
</section>
<section>
<h3>y hay muchas cosas que no son precisamente intuitivas</h3>
</section>
</section>
<section>
<section>
<h2>Problemas de los arrays</h2>
<ul>
<li class="fragment">Contravariantes en asignación</li>
<li class="fragment">Covariantes en los elementos</li>
<li class="fragment">Motivaciones históricas anteriores a los genéricos</li>
</ul>
</section>
<section>
<div class="overcode">Para poder hacer funciones que trabajaran genéricamente sobre los arrays cualquier tipo de array debía ser asignable a Object[]</div>
<div class="editor">public static boolean binarySearch(Object[] haystack, Object needle) {
// ... aquí magia
}
public static void main(String args[]) {
binarySearch({"a", "b", "c"}, "c"); //<-- Esto tenía que funcionar
}
</div>
</section>
<section>
<div class="overcode">Los arrays también deben permitir asignar subclases del tipo como elementos</div>
<div id="editor2" class="editor">Number[] numeros = new Number[3];
numeros[0] = 1;
numeros[1] = 1.1;
numeros[2] = 10l;
System.out.println(Arrays.toString(numeros));</div>
</section>
<section>
<div class="overcode"><p>Lo que nos lleva a la siguiente situación... que compila perfectamente</p>
<p class="fragment roll-in">pero que falla en Runtime!!</p> </div>
<div id="editor" class="editor">String[] strings = {"a", "b", "c"};
Object[] objects = strings;
objects[2] = 10; // !!!</div>
</section>
<section>Para conseguir este comportamiento los arrays en java llevan un <i>tag</i> en runtime con el tipo que contienen para conseguir que funcionen, ya que en tiempo de compilación no se puede garantizar el funcionamiento</section>
<section>Pero ahora tenemos...
<h1 class="fragment">Generics!!!</h1>
<img class="fragment" src="parameterize_all_the_types.jpg" style="width: 640px">
</section>
<section>
<div class="overcode">Así que ahora podemos usar genéricos para parametrizar nuestra función anterior</div>
<div id="editor" class="editor">public static <T> boolean binarySearch(T[] haystack, T needle) {
//Put the magic here...
}</div>
</section>
<section>
<h1>según la
<a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_arrays_in_Java_and_C.23">Wikipedia</a>
</h1>
</section>
<section>
<div>
<h1>pero...<br> ¿Esto va a funcionar?</h1>
</div>
</section>
<section>
<h1>No</h1>
<h2 class="fragment">No sirve para nada en realidad</h2>
<h3 class="fragment">Al menos sin hacer alguna cosa más</h3>
</section>
<section>
<div class="overcode fragment fade-out">
<p >Esto funciona porque los contenedores genéricos en Java no son variantes</p>
</div>
<div class="overcode fragment">
<p >Parece ser el motivo de que Class<?> se hiciera parametrizable, servir de <i>puente</i>
para que compilador y runtime pudieran funcionar <i>de forma segura</i></p>
</div>
<div id="editor" class="editor">public static <T> boolean binarySearch(
Class<T> klazz, T[] haystack, T needle) {
//Put the magic here...
}</div>
</section>
<section>
<div class="overcode fragment fade-out">También podemos conseguir el mismo efecto si nuestros métodos forman parte de una clase parametrizada</div>
<div class="overcode fragment">pero claro... tenemos que instanciarla</div>
<div id="editor" class="editor">public class Searcher[T] {
public boolean binarySearch(T[] haystack, T needle) {
// The code here
}
public static void main(String args[]) {
new Searcher<String>().binarySearch({"a", "b"}, "c");
}
}</div>
</section>
</section>
<section>
<section>
<div id="editor" class="editor editor-whole" >public void store(Map<String, Object> m, String key, Object value) {
if (value instanceof Number) {
value = String.valueOf(value);
}
else if (value instanceof Boolean) {
value = String.valueOf(value);
}
m.put(key, value);
}</div>
</section>
<section>
<div id="editor" class="editor editor-whole">public void store(Map m, String key, Number value) {
m.put(key, String.valueOf(value));
}
public void store(Map m, String key, Boolean value) {
m.put(key, String.valueOf(value));
}
public void store(Map m, String key, Object value) {
m.put(key, value);
}</div>
</section>
<section>
<h1><p>¿Son</p></h1><h2><p>equivalentes?</p></h2>
</section>
<section>
<div id="editor" class="editor editor-whole">public static void main(String[] args) {
List<Object> l = new ArrayList<Object>();
l.add(2);
l.add(true);
l.add("hola mundo");
for (Object object : l) {
print(object);
}
}</div>
</section>
<section>
<ul>
<li>En java la resolución de los métodos en función de los parámetros se hace en tiempo de compilación</li>
<li class="fragment">Sólo se comprueba en runtime el tipo del objeto <i>this</i></li>
<li class="fragment">Se conoce como <i>single dispatch</i></li>
<li class="fragment">Java, C++, C# (< 4.0 aparentemente) y Smalltalk, entre otros, tienen single dispatch</li>
</ul>
</section>
<section>
<h2>Patrón visitor</h2>
<ul>
<li>Es una manera de hacer <i>double dispath</i></li>
<li class="fragment">Para implementarlo correctamente es necesario que todas las clases <i>visitables</i> implementen el método accept</li>
<li class="fragment">Esta es la única manera de usar siempre la implementación más concreta</li>
</ul>
</section>
</section>
<section>
<section>
<h2>¿Cómo matar un hilo?</h2>
<h3>(To kill a running thread)</h3>
</section>
<section>
<h2>Respuesta corta</h2>
<h3 class="fragment">No se puede :(</h3>
</section>
<section>
<h2>Respuesta larga</h2>
<p class="fragment">Debemos programar el código de manera que se pueda <i>señalizar</i> al hilo la parada</p>
<p class="fragment">Tenemos que tener cuidado con código <i>genérico</i> que, de repente, ponemos a ejecutar dentro de hilos de forma transparente sin que el código esté preparado</p>
</section>
<section>
<h2>
pero... pero... <br>¿Qué pasa con Thread.stop() y Thread.interrupt()?
</h2>
</section>
<section>
<ul>
<li>Thread.stop() está deprecado y no debe usarse.</li>
<li class="fragment">Básicamente generaba una excepción ThreadDeath en el stack del hilo sobre el que se llamaba.</li>
<li class="fragment">Puede convertir cerrar los recursos correctamente en una tarea imposible.</li>
<li class="fragment">Además de que el código descuidado o mal hecho podía capturar la excepción e inutilizarla.</li>
</ul>
</section>
<section>
<ul>
<li>Lo recomendado es utilizar un flag para señalizar la parada del hilo.</li>
<li class="fragment">El problema de esta aproximación es hacer la sincronización correctamente.</li>
</ul>
</section>
<section>
<ul>
<li>Para esto podemos usar <i>Thread.interrupt()</i></li>
<li class="fragment">Pone el estado del hilo a <i>interrumpido</i> de forma segura</li>
<li class="fragment">Podemos consultarlo usando <i>Thread.interrupted()</i>, que nos devuelve si el hilo ha sido interrumpido y lo devuelve al estado original</li>
</ul>
</section>
<section>
<div class="overcode">
<p><i>Thread.interrupt()</i> también puede generar excepciones que interrumpen el flujo de ejecución inmediatamente</p>
<p class="fragment">Sin embargo los hilos tienen que estar en estados <i>interrumpibles</i> para poder ser interrumpidos</p>
</div>
<div id="editor" class="editor">Object object = new Object();
synchronized (object) {
try {
object.wait();
} catch (InterruptedException e) {
//Cerrar los recursos y salir de la ejecución
}
}</div>
</section>
<section>
<ul>
<li>Básicamente estos <i>estados</i> son acciones que hacen <i>polling</i> periódico sobre <i>Thread.interrupted()</i> y lanzan <i>InterruptedException</i></li>
<li class="fragment">No todas las llamadas bloqueantes se pueden <i>desbloquear</i> usando <i>Thread.interrupt()</i></li>
<li class="fragment">Un ejemplo claro son las llamadas a sistema como <i>read</i></li>
<li class="fragment">Con lo que es recomendable utilizar <i>timeouts</i> sensatos y comprobar el estado del hilo periódicamente en las llamadas bloqueantes</li>
</ul>
</section>
<section>
<div id="editor" class="editor editor-whole">try {
while (true) {
byte[] buffer = resource.read(100L); //Leer durante 100ms
if (Thread.interrupted()) {
throw new InterruptedException();
}
//trabaja si puedes
}
catch(InterruptedException ie) {
//Clear resources
}
}</div>
</section>
</section>
<section>
<section>
<h3>Inicialización tardía de <i>Singletons</i></h3>
</section>
<section>
<div id="editor" class="editor editor-whole">public class Singleton {
}
</div>
</section>
<section>
<div id="editor" class="editor editor-whole">public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}</div>
</section>
<section>
<h2>Lo malo es que esto no es multihilo</h2>
<p class="fragment">A partir de aquí se complica la cosa</p>
</section>
<section>
<div class="overcode fragment"><p>Con esto serializamos el acceso aunque la instancia esté creada ya, lo que no es muy recomendable</p></div>
<div id="editor" class="editor">synchronized public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}</div>
</section>
<section>
<div id="editor" class="editor editor-whole">public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
instance = new Singleton();
}
}
return instance;
}</div>
</section>
<section>
<div id="editor" class="editor editor-whole">public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}</div>
</section>
<section>
<div id="editor" class="editor editor-whole">private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}</div>
</section>
<section>
<h3>Initialization on demand holder</h3>
</section>
<section>
<div id="editor" class="editor editor-whole">public class Singleton {
private Singleton() {}
private static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}</div>
</section>
<section>
<div>
<ul>
<li>El código es mucho más conciso</li>
<li class="fragment">Es <i>threadsafe</i></li>
<li class="fragment">Es <i>lazy</i></li>
<li class="fragment">La principal pega es que no se pueden controlar errores en la inicialización apropiadamente</li>
</ul>
</div>
</section>
</section>
</div>
</div>
<script src="ace.js" type="text/javascript" charset="utf-8"></script>
<script>
</script>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'linear', // default/cube/page/concave/zoom/linear/fade/none
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
Reveal.addEventListener( 'slidechanged', function( event ) {
$(event.currentSlide).find('div.editor').get().forEach(function(it) {
var editor = ace.edit(it);
editor.setTheme("ace/theme/ambiance");
editor.getSession().setMode("ace/mode/java");
editor.renderer.setShowGutter(false);
editor.setHighlightActiveLine(false);
editor.commands.addCommand({
name: 'exec',
bindKey: {win: 'Ctrl-E', mac: 'Command-E'},
exec: function(editor) {
$.ajax({
url: 'http://localhost:51081/execute',
type: 'POST',
data: {expression: editor.getValue()},
success: function(e) {
debugger;
}
})
},
readOnly: true // false if this command should not apply in readOnly mode
});
} );
});
</script>
</body>
</html>