Suppose I have an immutable Model class:
class Model {
final String id;
Model(String id) {
this.id = id;
}
}
And I have a custom Task class:
class Task extends BlaBlaTask {
final Model model;
Task(Model model) {
this.model = model;
}
// runs on a background thread
void doInBackground() {
// do smth with model, e.g.:
String id = model.id;
}
}
And both Model and Task instances are created on the main UI thread. However doInBackground() is run on another thread. Is this code wrong? Should I add synchronization, e.g. something like this:
class Task extends BlaBlaTask {
Model model;
Task(Model model) {
setModel(model);
}
// runs on a background thread
void doInBackground() {
// do smth with model, e.g.:
String id = getModel().id;
}
private synchronized void setModel(Model m) {
model = m;
}
private synchronized Model getModel() {
return model;
}
}
P.S. I am working on Java 1.4, and the code probably can be run on a multi-core CPU.
I’m not familiar anymore with the Java memory model of Java 1.4, but I don’t see why you would need synchronization.
If you’re starting a thread, then the new thread will see everything you have written before starting the thread.
And if you’re passing the task to an existing thread, the publishing mechanism should have all the necessary synchronization in place to make sure that the thread sees everything that has been written before the publication. That shouldn’t be the task’s job to synchronize anything, it should be the Queue’s job (or any other way you use to pass the task from one thread to the other)