So I have a class that extends Thread, and when I start the thread, it changes some variable values in a static class then uses them in some methods from that class. Whoever wrote the static class did not synchronize this code, so If I start both threads right away, they will overwrite the static values in each thread and muck everything up.
/* BAD */
Test a = new Test();
Test b = new Test();
a.start();
b.start();
As a fix, I added an init method (due to requirements it can't be in the constructor) so that code block will run serially before multiple threads start.
/* Okay, but ugly */
Test a = new Test();
Test b = new Test();
a.init();
b.init();
a.start();
b.start();
To me this is ugly and seems kind of fragile if someone else decides to use this same class later (might not understand the behavior and overlook this). I'm not sure if in my run method I could do a synchronized code block because there are two different instances of the same class and the separate threads won't really care if it's synchronized (I may be wrong about this).
I'm sure there is a simple solution to this problem because it seems like it might occur fairly often, but it's late and I'm tired of screwing with this code quite frankly.
Any advice?
/* BAD */
Test a = new Test();
Test b = new Test();
a.start();
b.start();
As a fix, I added an init method (due to requirements it can't be in the constructor) so that code block will run serially before multiple threads start.
/* Okay, but ugly */
Test a = new Test();
Test b = new Test();
a.init();
b.init();
a.start();
b.start();
To me this is ugly and seems kind of fragile if someone else decides to use this same class later (might not understand the behavior and overlook this). I'm not sure if in my run method I could do a synchronized code block because there are two different instances of the same class and the separate threads won't really care if it's synchronized (I may be wrong about this).
I'm sure there is a simple solution to this problem because it seems like it might occur fairly often, but it's late and I'm tired of screwing with this code quite frankly.
Any advice?