Image caption The judges ruled that overcrowding 'violates prisoners' constitutional rights'

The US Supreme Court has upheld an order for California to free thousands of prisoners because of overcrowding.

Federal judges had ordered 40,000 prisoners be released within two years. The state says it has 148,000 inmates, in prisons designed for 80,000 people.

California appealed to the Supreme Court, arguing that the prisoners could pose a risk to public safety.

But the court ruled the limit was necessary "to remedy the violation of prisoners' constitutional rights".

Judges rejected the state's appeal by a 5-4 vote, and upheld the 2009 federal court order.

Funding shortage

The method for reducing overcrowding "is at the discretion of state officials," the Supreme Court ruling read.

"But absent compliance through new construction, out-of-state transfers, or other means... the state will be required to release some number of prisoners before their full sentences have been served," it said.

The ruling comes after at least two inmates were stabbed on Friday when 150 prisoners rioted at a maximum security prison in the state capital, Sacramento.

Guards used pepper spray and fired a live round to gain control, prison officials said.

California has the largest state prison population in the US, with 33 prisons.

But its prisons have been overcrowded and underfunded for many years.

Among the remedies suggested, former Governor Arnold Schwarzenegger proposed in 2010 that the state could reduce prison spending by housing undocumented inmates in Mexican jails.