我有一个应用程序不时在日志中有这个堆栈跟踪:
java.lang.ArrayIndexOutOfBoundsException: 514
at sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(BaseCalendar.java:436)
at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2081)
at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:1996)
at java.util.Calendar.complete(Calendar.java:1312)
at java.util.Calendar.get(Calendar.java:1093)
at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:917)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:824)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:796)
at java.text.DateFormat.format(DateFormat.java:314)
at me.myself.i.Message.toString(Message.java:203)
at java.lang.String.valueOf(String.java:2615)
at java.lang.StringBuilder.append(StringBuilder.java:116)
我认为问题可能出在这些方面:
public class Message{
private transient DateFormat logDateFormat;
@Override
public String toString() {
final StringBuilder result = new StringBuilder(getClass().getSimpleName());
result.append("Time=").append(logDateFormat.format(new Date(getExpireTime())));
return result.toString();
}
}
我认为多个线程同时调用 toString() ,但我在本地机器上复制它时遇到了麻烦:
@Before
public void setUp() {
message = new Message();
pool = Executors.newFixedThreadPool(numOfThreads);
}
@Test
public void multiThreadTest() {
for (int i=0; i<numOfThreads; i++) {
TestJob j = new TestJob(message);
pool.submit(j);
}
pool.shutdown();
while(!pool.isTerminated()){
}
}
class TestJob implements Runnable{
private Message message;
private int n=100;
public TestJob(Message message) {
this.message= message;
}
public void run() {
for (int i=0; i<n; i++) {
try{
System.out.println(message.toString());
} catch(Exception e){
e.printStackTrace();
}
}
}
}
我如何编写正确的junit测试来重现这个问题?