|
| 1 | +/** |
| 2 | + * The MIT License |
| 3 | + * Copyright (c) 2016 Thomas Bauer |
| 4 | + * |
| 5 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | + * of this software and associated documentation files (the "Software"), to deal |
| 7 | + * in the Software without restriction, including without limitation the rights |
| 8 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | + * copies of the Software, and to permit persons to whom the Software is |
| 10 | + * furnished to do so, subject to the following conditions: |
| 11 | + * |
| 12 | + * The above copyright notice and this permission notice shall be included in |
| 13 | + * all copies or substantial portions of the Software. |
| 14 | + * |
| 15 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 21 | + * THE SOFTWARE. |
| 22 | + */ |
| 23 | + |
| 24 | +package com.iluwatar.tls; |
| 25 | + |
| 26 | +import java.util.Calendar; |
| 27 | +import java.util.Date; |
| 28 | +import java.util.concurrent.ExecutorService; |
| 29 | +import java.util.concurrent.Executors; |
| 30 | +import java.util.concurrent.Future; |
| 31 | + |
| 32 | +/** |
| 33 | + * ThreadLocal pattern |
| 34 | + * <p> |
| 35 | + * This App shows how to create an isolated space per each thread. In this |
| 36 | + * example the usage of SimpleDateFormat is made to be thread-safe. This is an |
| 37 | + * example of the ThreadLocal pattern. |
| 38 | + * <p> |
| 39 | + * By applying the ThreadLocal pattern you can keep track of application |
| 40 | + * instances or locale settings throughout the handling of a request. The |
| 41 | + * ThreadLocal class works like a static variable, with the exception that it is |
| 42 | + * only bound to the current thread! This allows us to use static variables in a |
| 43 | + * thread-safe way. |
| 44 | + * <p> |
| 45 | + * In Java, thread-local variables are implemented by the ThreadLocal class |
| 46 | + * object. ThreadLocal holds a variable of type T, which is accessible via get/set |
| 47 | + * methods. |
| 48 | + * <p> |
| 49 | + * SimpleDateFormat is one of the basic Java classes and is not thread-safe. If |
| 50 | + * you do not isolate the instance of SimpleDateFormat per each thread then |
| 51 | + * problems arise. |
| 52 | + * <p> |
| 53 | + * App converts the String date value 15/12/2015 to the Date format using the |
| 54 | + * Java class SimpleDateFormat. It does this 20 times using 4 threads, each doing |
| 55 | + * it 5 times. With the usage of as ThreadLocal in DateFormatCallable everything |
| 56 | + * runs well. But if you comment out the ThreadLocal variant (marked with "//TLTL") |
| 57 | + * and comment in the non ThreadLocal variant (marked with "//NTLNTL") you can |
| 58 | + * see what will happen without the ThreadLocal. Most likely you will get incorrect |
| 59 | + * date values and / or exceptions. |
| 60 | + * <p> |
| 61 | + * This example clearly show what will happen when using non thread-safe classes |
| 62 | + * in a thread. In real life this may happen one in of 1.000 or 10.000 conversions |
| 63 | + * and those are really hard to find errors. |
| 64 | + * |
| 65 | + * @author Thomas Bauer, 2017 |
| 66 | + */ |
| 67 | +public class App { |
| 68 | + /** |
| 69 | + * Program entry point |
| 70 | + * |
| 71 | + * @param args |
| 72 | + * command line args |
| 73 | + */ |
| 74 | + public static void main(String[] args) { |
| 75 | + int counterDateValues = 0; |
| 76 | + int counterExceptions = 0; |
| 77 | + |
| 78 | + // Create a callable |
| 79 | + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); |
| 80 | + // start 4 threads, each using the same Callable instance |
| 81 | + ExecutorService executor = Executors.newCachedThreadPool(); |
| 82 | + |
| 83 | + Future<Result> futureResult1 = executor.submit(callableDf); |
| 84 | + Future<Result> futureResult2 = executor.submit(callableDf); |
| 85 | + Future<Result> futureResult3 = executor.submit(callableDf); |
| 86 | + Future<Result> futureResult4 = executor.submit(callableDf); |
| 87 | + try { |
| 88 | + Result[] result = new Result[4]; |
| 89 | + result[0] = futureResult1.get(); |
| 90 | + result[1] = futureResult2.get(); |
| 91 | + result[2] = futureResult3.get(); |
| 92 | + result[3] = futureResult4.get(); |
| 93 | + |
| 94 | + // Print results of thread executions (converted dates and raised exceptions) |
| 95 | + // and count them |
| 96 | + for (int i = 0; i < result.length; i++) { |
| 97 | + counterDateValues = counterDateValues + printAndCountDates(result[i]); |
| 98 | + counterExceptions = counterExceptions + printAndCountExceptions(result[i]); |
| 99 | + } |
| 100 | + |
| 101 | + // a correct run should deliver 20 times 15.12.2015 |
| 102 | + // and a correct run shouldn't deliver any exception |
| 103 | + System.out.println("The List dateList contains " + counterDateValues + " date values"); |
| 104 | + System.out.println("The List exceptionList contains " + counterExceptions + " exceptions"); |
| 105 | + |
| 106 | + } catch (Exception e) { |
| 107 | + // no action here |
| 108 | + } |
| 109 | + executor.shutdown(); |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Print result (date values) of a thread execution and count dates |
| 114 | + * |
| 115 | + * @param res contains results of a thread execution |
| 116 | + */ |
| 117 | + private static int printAndCountDates(Result res) { |
| 118 | + // a correct run should deliver 5 times 15.12.2015 per each thread |
| 119 | + int counter = 0; |
| 120 | + for (Date dt : res.getDateList()) { |
| 121 | + counter++; |
| 122 | + Calendar cal = Calendar.getInstance(); |
| 123 | + cal.setTime(dt); |
| 124 | + // Formatted output of the date value: DD.MM.YYYY |
| 125 | + System.out.println( |
| 126 | + cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + +cal.get(Calendar.YEAR)); |
| 127 | + } |
| 128 | + return counter; |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Print result (exceptions) of a thread execution and count exceptions |
| 133 | + * |
| 134 | + * @param res contains results of a thread execution |
| 135 | + * @return number of dates |
| 136 | + */ |
| 137 | + private static int printAndCountExceptions(Result res) { |
| 138 | + // a correct run shouldn't deliver any exception |
| 139 | + int counter = 0; |
| 140 | + for (String ex : res.getExceptionList()) { |
| 141 | + counter++; |
| 142 | + System.out.println(ex); |
| 143 | + } |
| 144 | + return counter; |
| 145 | + } |
| 146 | +} |
0 commit comments