Skip to content

Commit 7200329

Browse files
authored
Add files via upload
Rework replaces previous version completely. Using ExecutorService. Use of result object instead of static variables. Ugly example is left out.
1 parent f170aaa commit 7200329

File tree

3 files changed

+284
-0
lines changed

3 files changed

+284
-0
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
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.text.DateFormat;
27+
import java.text.SimpleDateFormat;
28+
import java.util.concurrent.Callable;
29+
30+
/**
31+
* DateFormatCallable converts string dates to a date format using
32+
* SimpleDateFormat. The date format and the date value will be passed to the
33+
* Callable by the constructor. The constructor creates a instance of
34+
* SimpleDateFormat and stores it in a ThreadLocal class variable. For the
35+
* complete description of the example see {@link App}
36+
*
37+
* You can comment out the code marked with //TLTL and comment in the
38+
* code marked //NTLNTL. Then you can see what will happen if you do not
39+
* use the ThreadLocal. For details see the description of {@link App}
40+
*
41+
* @author Thomas Bauer, 2017
42+
*/
43+
public class DateFormatCallable implements Callable<Result> {
44+
// class variables (members)
45+
private ThreadLocal<DateFormat> df; //TLTL
46+
// private DateFormat df; //NTLNTL
47+
48+
private String dateValue; // for dateValue Thread Local not needed
49+
50+
51+
/**
52+
* The date format and the date value are passed to the constructor
53+
*
54+
* @param inDateFormat
55+
* string date format string, e.g. "dd/MM/yyyy"
56+
* @param inDateValue
57+
* string date value, e.g. "21/06/2016"
58+
*/
59+
public DateFormatCallable(String inDateFormat, String inDateValue) {
60+
final String idf = inDateFormat; //TLTL
61+
this.df = new ThreadLocal<DateFormat>() { //TLTL
62+
@Override //TLTL
63+
protected DateFormat initialValue() { //TLTL
64+
return new SimpleDateFormat(idf); //TLTL
65+
} //TLTL
66+
}; //TLTL
67+
// this.df = new SimpleDateFormat(inDateFormat); //NTLNTL
68+
this.dateValue = inDateValue;
69+
}
70+
71+
/**
72+
* @see java.util.concurrent.Callable#call()
73+
*/
74+
@Override
75+
public Result call() {
76+
System.out.println(Thread.currentThread() + " started executing...");
77+
Result result = new Result();
78+
79+
// Convert date value to date 5 times
80+
for (int i = 1; i <= 5; i++) {
81+
try {
82+
// this is the statement where it is important to have the
83+
// instance of SimpleDateFormat locally
84+
// Create the date value and store it in dateList
85+
result.getDateList().add(this.df.get().parse(this.dateValue)); //TLTL
86+
// result.getDateList().add(this.df.parse(this.dateValue)); //NTLNTL
87+
} catch (Exception e) {
88+
// write the Exception to a list and continue work
89+
result.getExceptionList().add(e.getClass() + ": " + e.getMessage());
90+
}
91+
92+
}
93+
94+
System.out.println(Thread.currentThread() + " finished processing part of the thread");
95+
96+
return result;
97+
}
98+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Fiducia IT AG, All rights reserved. Use is subject to license terms.
3+
*/
4+
5+
package com.iluwatar.tls;
6+
7+
import java.util.ArrayList;
8+
import java.util.Date;
9+
import java.util.List;
10+
11+
/**
12+
* Result object that will be returned by the Callable {@link DateFormatCallable}
13+
* used in {@link App}
14+
*
15+
* @author Thomas Bauer, 2017
16+
*/
17+
public class Result {
18+
// A list to collect the date values created in one thread
19+
private List<Date> dateList = new ArrayList<Date>();
20+
21+
// A list to collect Exceptions thrown in one threads (should be none in
22+
// this example)
23+
private List<String> exceptionList = new ArrayList<String>();
24+
25+
/**
26+
*
27+
* @return List of date values collected within an thread execution
28+
*/
29+
public List<Date> getDateList() {
30+
return dateList;
31+
}
32+
33+
/**
34+
*
35+
* @return List of exceptions thrown within an thread execution
36+
*/
37+
public List<String> getExceptionList() {
38+
return exceptionList;
39+
}
40+
}

0 commit comments

Comments
 (0)