Thread issue

I have a class named FoodListDay which represents all the meals for a day.

The Set foodListMeals is not supposed to contain any null elements. But since the attribute is set through setFoodListMeals I don't know what kind of Set is assigned to foodListMeals. If it is a HashSet for instance, null is a valid element type.

To fix this I introduced one line of code in setFoodListMeals that removes any null elements. But I fear that there might be some threading issues with this approach:

Thread A calls setFoodListMeals with a Set containing a null element. It executes the first line of code (assigns the Set to the attribute foodListMeals). It gets preempted by thread B. Thread B calls getFoodListMeals and gets back the set with the null element.

I'm not sure if making the method setFoodListMeals synchronized would take care of that because I don't completely understand thread/synchronization issues.

If thread B wants to call getFoodListMeals when thread A is executing setFoodListMeals, would making setFoodListMeals synchronized make thread B to wait until thread A is done (even though thread B doesn't try to access the synchronized method)?

Do I perhaps have to synchronize both methods to avoid any thread from accessing getFoodListMeals while another thread is already executing setFoodListMeals?

publicclass FoodListDay{

private Set foodListMeals;

public Set getFoodListMeals(){

return foodListMeals;

}

publicvoid setFoodListMeals(Set foodListMeals){

this.foodListMeals = foodListMeals;

this.foodListMeals.remove(null);// suggested fix.

}

}

[2120 byte] By [mah01a] at [2007-11-27 2:36:09]
# 1
Yes. Synchronize them.
hiwaa at 2007-7-12 2:55:08 > top of Java-index,Core,Core APIs...
# 2

you need only sync on/in setFoodListMeals

it is thread-safe to sync the method if all Sets passed to it are NOT changed by other threads, e.g. a Hashset passed to setFoodListMeals cannot have be given a null by another thread

if any Set passed to setFoodListMeals can be modified by any other thread, you should synchronize on the Set, e.g.

public void setFoodListMeals(Set foodListMeals) {

if( foodListMeals == null ) {

this.foodListMeals = null;

return;

}

synchronized( foodListMeals ) {

this.foodListMeals = foodListMeals;

this.foodListMeals.remove(null);

}

}

developer_jbsa at 2007-7-12 2:55:08 > top of Java-index,Core,Core APIs...