Codon usage bias is the nonrandom use of synonymous codons for the same amino acid. Most population genetic models of codon usage evolution assume that the population is at mutation-selection-drift equilibrium. Natural populations, however, frequently deviate from equilibrium, often because of recent demographic changes. Here, we construct a matrix model that includes the effects of a recent change in population size on estimates of selection on preferred vs. unpreferred codons. Our results suggest that patterns of synonymous polymorphisms affecting codon usage can be quite erratic after such a change; statistical methods that fail to take demographic effects into account can then give incorrect estimates of important parameters. We propose a new method that can accurately estimate both demographic and codon usage parameters. The method also provides a simple way of testing for the effects of covariates such as gene length and level of gene expression on the intensity of selection, which we apply to a large Drosophila melanogaster polymorphism data set. Our analyses of twofold degenerate codons reveal that (i) selection acts in favor of preferred codons, (ii) there is mutational bias in favor of unpreferred codons, (iii) shorter genes and genes with higher expression levels are under stronger selection, and (iv) there is little evidence for a recent change in population size in the Zimbabwe population of D. melanogaster.