S
Shailender Bathula
Hi all,
Can anyone please confirm if using a static, pre-created Exception
object in a throw statement across multiple threads, thread-safe? I
have a need to use a pre-created Exception to improve the performance.
I use pre-created exception in production mode, where as new Exception
object in debug mode.
Line 14 in the sample test program below highlights this. Is Line 14,
thread-safe?
1 public class StaticPreCreatedExceptionTest implements Runnable
{
2 private static final Exception ex = new Exception("static
pre-created exception");
3
4 private String tid = null;
5
6 public StaticPreCreatedExceptionTest(String tid) {
7 this.tid = tid;
8 }
9
10 public void run() {
11 while ( true ) {
12 try {
13 // is this thread safe?
14 throw ex;
15 }
16 catch (Exception e) {
17 System.out.println(tid + ": caught exception");
18 }
19 }
20 }
21
22 public static void main(String args[]) throws Exception {
23 int MAXTHREADS = 5;
24
25 Thread threads[] = new Thread[MAXTHREADS];
26 for ( int i = 0; i < MAXTHREADS; i++ ) {
27 threads = new Thread(new
StaticPreCreatedExceptionTest("t" + i));
28 threads.start();
29 }
30
31 for ( int i = 0; i < MAXTHREADS; i++ ) {
32 // wait until all threads are done
33 threads.join();
34 }
35 }
36 }
I thought it was thread-safe, but current thread stack trace of the
Java core dumps in my software always points to the "throw" statement.
So wanted to confirm from someone.
Thanks,
Shailender
Can anyone please confirm if using a static, pre-created Exception
object in a throw statement across multiple threads, thread-safe? I
have a need to use a pre-created Exception to improve the performance.
I use pre-created exception in production mode, where as new Exception
object in debug mode.
Line 14 in the sample test program below highlights this. Is Line 14,
thread-safe?
1 public class StaticPreCreatedExceptionTest implements Runnable
{
2 private static final Exception ex = new Exception("static
pre-created exception");
3
4 private String tid = null;
5
6 public StaticPreCreatedExceptionTest(String tid) {
7 this.tid = tid;
8 }
9
10 public void run() {
11 while ( true ) {
12 try {
13 // is this thread safe?
14 throw ex;
15 }
16 catch (Exception e) {
17 System.out.println(tid + ": caught exception");
18 }
19 }
20 }
21
22 public static void main(String args[]) throws Exception {
23 int MAXTHREADS = 5;
24
25 Thread threads[] = new Thread[MAXTHREADS];
26 for ( int i = 0; i < MAXTHREADS; i++ ) {
27 threads = new Thread(new
StaticPreCreatedExceptionTest("t" + i));
28 threads.start();
29 }
30
31 for ( int i = 0; i < MAXTHREADS; i++ ) {
32 // wait until all threads are done
33 threads.join();
34 }
35 }
36 }
I thought it was thread-safe, but current thread stack trace of the
Java core dumps in my software always points to the "throw" statement.
So wanted to confirm from someone.
Thanks,
Shailender