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.