Gestation stalls can be beneficial because sows are large (300-600 lb), and can be quite violent when hungry, which is most of the time, but more so right after weaning off the piglets. It is not uncommon in group housed situations for them to injure each other badly enough to require medical interventions and very occasionally euthanasia. Also, these fights occurs most right after breeding, and the stress can lead to reduced viability of the delicate embryos. Fewer piglets per litter is both an indicator of reduced welfare AND a sign of reduced economic potential. The best is a hybrid situation where sows are kept in gestation stalls for a few weeks after weaning to ensure a calm dry off period, and a good start for the embryos, and then moving them into group housing.
Castration of boars, cuts down on off flavor (called boat taint), reduces aggression toward each other and their handlers (worker safety matter too), unexpected pregnancies at the slaughter house when males and females are housed together (very common), and rape. Yes, boats when housed together will rape each other. More recently a company has developed a non-surgical way to castrate pigs later in the growth phase (beneficial because boars are more feed efficient than barrows), but it is dangerous to male employees (the shot works on human males as well), and the industry doesn't yet know how consumers will perceive the technology called improvest.
These management decisions are not made lightly, and usually are made to optimize several different, and occasionally conflicting objectives.