Java Quiz #41 : time attack !

(FR)
La cellule d'expertise de votre entreprise a développé un Timer pour que vous puissiez mesurer les performances de votre application, mais... ils ont juste oublié de fournir une méthode pour récupérer la valeur du compteur ! Comment faire pour l'afficher une fois la mesure prise ?
Vous ne pouvez intervenir que sur la classe Quiz41, et il est interdit de modifier le code existant ou d'utiliser la Réflexion.
Bonne chance !

(EN)
The Architects Team developed a Timer class to help you measure the performance of your code, but... they forgot to provide a method to get the timer's value ! How can you get it back and print it in the console ?
You can only alter the Quiz41 class ; modifying the already existing code or using Reflection is forbidden.
Good luck !

  1. public class Quiz41 {
  2.  
  3. public static void main(String[] args) throws InterruptedException {
  4.  
  5. Timer timer = new Timer();
  6. timer.start();
  7. Thread.sleep(new Random().nextInt(2000));
  8. timer.stop();
  9.  
  10. }
  11. }
  1. public class Timer {
  2.  
  3. private TimerThread thread = new TimerThread();
  4.  
  5. public void start() {
  6. thread.start();
  7. }
  8.  
  9. public void stop() {
  10. thread.stop();
  11. }
  12.  
  13. public static class TimerThread extends Thread {
  14. private AtomicInteger counter = new AtomicInteger(0);
  15.  
  16. @Override
  17. public void run() {
  18. try {
  19. while (!isInterrupted()) {
  20. counter.incrementAndGet();
  21. Thread.sleep(100);
  22. }
  23. } catch (InterruptedException e) {
  24. interrupt();
  25. }
  26. }
  27.  
  28. public int getCounter() {
  29. return counter.get();
  30. }
  31. }
  32. }
Lire la suite...

Java Quiz #40

To please your Project Manager, a former developer (yeaaars ago), you sometimes let him help you develop some "very important" parts of your application.

Today, he's in charge of displaying "Hello World" by iterating on a list containing those words. Alas, distracted by his going on vacation this very afternoon, he forgets to add "World" to the list before starting the iteration. Trying to correct his mistake, he adds it a few lines later, but now his code unexpectedly breaks down at runtime ("this must be a JVM bug !").

A few minutes before leaving, he asks you to find a solution in his absence, with the following instructions :

  • Do not modify his existing code, it's Perfect (of course).
  • The FIXME tag shows where you're allowed to insert your corrective code
  • He must be able to understand your solution when he comes back (so

using Reflection is not an option).

Are you worth the trust of your beloved Manager ?

  1. final List<String> list = new ArrayList<String>() {{ add("Hello"); }};
  2. final Iterator<String> iterator = list.iterator();
  3. System.out.println(iterator.next());
  4. list.add("World");
  5. // FIXME : work here while I'm sunbathing
  6. System.out.println(iterator.next());

Hints - Keep in mind that :

  • the iterator is declared final
  • this is only a code fragment, so you cannot use System.exit(0) or return; you wouldn't like your application to terminate prematurely, would you ?
  • since you cannot modify the existing code, you cannot delete or ignore the last line, which must print "World"

Note : I must thank Romain Revol for helping me to write this quiz. Romain successfully attended the "Heinz Kabutz's Java Specialist Master Course" training session I presented in France in June at Zenika's office.

Lire la suite...

Java Quiz #39

If you're not getting your athletic body's tanned on a beach this week, here is a small quiz to keep your brain fit.
What does this code snippet do ?

  1. public class Quiz39 {
  2.  
  3. public static void main(String[] args) {
  4. int[] array = null;
  5. try {
  6. array[0] = array[(array = createArray())[array.length - 1]];
  7. } finally {
  8. System.out.println("Array = " + Arrays.toString(array));
  9. }
  10. }
  11.  
  12. public static int[] createArray() {
  13. return new int[]{1, 2, 3, 4};
  14. }
  15.  
  16. }
Lire la suite...

Java Quiz #38

Can you help the poor Exception to escape the Matrix ?
Beware, the Agents are nearby and will spot you if you attempt in any way to modify or remove the existing lines of code ! (but you may add new ones).

  1. public class Matrix {
  2. public static void getTheSpoon() {
  3. throw new java.lang.NoSuchMethodException("There is no spoon !");
  4. }
  5. }
  1. public class Test {
  2. public static void main(String[] args) {
  3. try {
  4. Matrix.getTheSpoon();
  5. } catch (Exception ex) {
  6. System.out.println(ex instanceof java.lang.NoSuchMethodException ? "You passed the Quiz !" : "You failed !");
  7. }
  8. }
  9. }
Lire la suite...

Java Quiz #37

Voici un nouveau quiz, pour bien finir le mois de mai avant d'entamer ce beau mois de juin.

La classe ColoredPoint ci-dessous pose un problème assez subtil. Lequel ?

  1. public class Point {
  2. private int x;
  3. private int y;
  4.  
  5. public Point(int x, int y) {
  6. this.x = x;
  7. this.y = y;
  8. }
  9.  
  10. public boolean equals(Object o) {
  11. if (this == o) { return true; }
  12. if (!(o instanceof Point)) { return false; }
  13.  
  14. final Point point = (Point) o;
  15. return (x == point.x && y == point.y);
  16. }
  17.  
  18. public int hashCode() {
  19. int result = x;
  20. result = 31 * result + y;
  21. return result;
  22. }
  23. }
  24.  
  25. public class ColoredPoint extends Point {
  26. private Color color;
  27.  
  28. public ColoredPoint(int x, int y, Color color) {
  29. super(x, y);
  30. this.color = color;
  31. }
  32.  
  33. public boolean equals(Object o) {
  34. if (this == o) { return true; }
  35. if (!(o instanceof ColoredPoint && super.equals(o))) {
  36. return false;
  37. }
  38.  
  39. final ColoredPoint point = (ColoredPoint) o;
  40. return (color == null ? (point.color == null) : color.equals(point.color));
  41. }
  42.  
  43. public int hashCode() {
  44. int result = super.hashCode();
  45. result = 31 * result + (color != null ? color.hashCode() : 0);
  46. return result;
  47. }
  48. }
Lire la suite...

Java Quiz #36

Pour créer des instances de classes dont on ne connait que le nom, rien de plus facile : il suffit de récupérer l'instance de Class<?> puis d'appeler newInstance() dessus, et puis de traiter les nombreuses exceptions susceptibles d'être levées.

C'est ce que fait la méthode statique newInstance ci-dessous :

  1. public class TestNewInstance {
  2. public static void main(String[] args) {
  3. final Object o = newInstance(args[0]);
  4. System.out.println(String.valueOf(o));
  5. }
  6.  
  7. private static Object newInstance(String className) {
  8. try {
  9. Class<?> clazz = Class.forName(className);
  10.  
  11. return clazz.newInstance();
  12. } catch (ClassNotFoundException e) {
  13. System.out.println("-- Class Not Found --");
  14. } catch (IllegalAccessException e) {
  15. System.out.println("-- Illegal Access --");
  16. } catch (InstantiationException e) {
  17. System.out.println("-- Cannot Instantiate --");
  18. }
  19. return null;
  20. }
  21. }

Bien sûr, la classe en question doit posséder un constructeur sans argument ; si ce n'est pas le cas, InstantiationException sera levée.

Cependant, malgré toutes ces précautions, ce code pose un gros problème de robustesse, qui ne se révèle que pour quelques classes bien particulières. Pourquoi ? Comment l'éliminer ?

Lire la suite...

Java Quiz #35

Depuis une classe tierce, comment afficher la valeur du champ "message" de la classe ci-dessous ?
Il est naturellement interdit de court-circuiter les règles de visibilité des champs de la classe.

  1. package net.thecodersbreakfast.quiz35
  2. public class OuterClass {
  3.  
  4. private String message = "Hello World";
  5.  
  6. private class InnerClass {
  7. private String getMessage() {
  8. return message;
  9. }
  10. }
  11. }
Lire la suite...

Java Quiz #34

Vous savez qu'au sein de la JVM, une classe est identifiée de manière unique par son nom complet et son classloader.

Cette règle est facile à implémenter sous la forme d'une méthode utilitaire :

  1. public class ClassUtils {
  2. public static boolean isSameClass(Class<?> class1, Class<?> class2) {
  3. if ((class1 == null) || (class2 == null)) { return false; }
  4. return (
  5. class1.getClassLoader().equals(class2.getClassLoader()) &&
  6. class1.getName().equals(class2.getName()) );
  7. }
  8. }

Il ne reste plus qu'à vérifier :

  1. System.out.println( ClassUtils.isSameClass(ClassUtils.class, ClassUtils.class) ); // true
  2. System.out.println( ClassUtils.isSameClass(String.class, ClassUtils.class) ); // false

A moins que... ?

Lire la suite...

Java Quiz #33

La classe ci-dessous part d'une bonne intention, mais où est le problème ?

  1. /**
  2.  * Garantit que les éventuelles exceptions levées par la méthode dangereuse
  3.  * seront loggées.
  4.  * @param <R> Le type de retour de la méthode
  5.  * @param <E> Le type d'exception levé
  6.  */
  7. public abstract class ExceptionLoggingExecutor<R, E extends Throwable> {
  8.  
  9. private final Logger logger = Logger.getLogger(ExceptionLoggingExecutor.class.getName());
  10.  
  11. public final R execute(Object... args) throws E {
  12. try {
  13. return dangerousOperation(args);
  14. } catch (E e) {
  15. logger.error(e);
  16. throw e;
  17. }
  18. }
  19.  
  20. /** La méthode contenant le code dangereux */
  21. protected abstract R dangerousOperation(Object... args) throws E;
  22. }
Lire la suite...

Java Quiz #32

Voici un quiz spécial saint-Valentin ! Comme d'habitude, il s'agit de trouver ce qui cloche avec ce code, sans le coller dans un IDE.

Comme le code est un peu plus long que d'habitude, il est exceptionnellement dans le corps du billet.
Bon quiz !

Lire la suite...

- page 1 de 5

Archives

Contacts

Olivier Croisier : mail, site
HollyDays : mail
Wikio - Top des blogs - Logiciels libres