In my contrived example, what are the implications for thread safety with regard to the list of teamMembers?
Can I rely on the state of the list as seen by the run()
method to be consistent?
Assuming
the
setATeamMembers
method is called only once, by spring when it is creating theATeamEpisode
beanthe
init
method is called by spring (init-method) after #1the
ATeamMember
class is immutableDo I need to declare the
teamMembers
volatile
or similar?Are there any other hideous problems with this approach that I'm overlooking?
Apologies if this is obvious, or a clear failure to rtfm
Thanks and regards
Ed
package aTeam;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ATeamEpisode implements Runnable{
private List<ATeamMember> teamMembers;
/* DI by spring */
public void setATeamMembers(List<ATeamMember> teamMembers){
this.teamMembers = new ArrayList<ATeamMember>(teamMembers);
}
private Thread skirmishThread;
public synchronized void init(){
System.out.println("Starting skirmish");
destroy();
(skirmishThread = new Thread(this,"SkirmishThread")).start();
}
public synchronized void destroy(){
if (skirmishThread != null){
skirmishThread.interrupt();
skirmishThread=null;
}
}
private void firesWildlyIntoTheAir(ATeamMember teamMember){
System.out.println(teamMember.getName()+" sprays the sky..");
}
@Override
public void run() {
try {
Random rnd = new Random();
while(! Thread.interrupted()){
firesWildlyIntoTheAir(teamMembers.get(rnd.nextInt(teamMembers.size())));
Thread.sleep(1000 * rnd.nextInt(5));
}
} catch (InterruptedException e) {
System.out.println("End of skirmish");
/* edit as per Adam's suggestion */
// Thread.currentThread().interrupt();
}
}
}