A Southern California teenager who shot a gay classmate he believed was flirting with him entered a guilty plea on Monday to second-degree murder and has agreed to spend the next 21 years behind bars.

It was a plea deal that ended the case of Brandon McInerney, 17, who has been accused of gunning down his classmate Larry King, 15, at E.O. Green Junior High School in Oxnard in February 2008. McInerney was 14 years old at the time of the shooting.

Ventura County Chief Deputy District Attorney Mike Frawley told The Associated Press that McInerney guilty to the murder charge along with one count each of voluntary manslaughter and use of a firearm.

McInerney is expected to return to court on Dec. 19 when he will be sentenced.

The murder case drew national attention as people learn that McInerney went in to a fit of homophobic rage; pulled out a handgun from his backpack and shot King twice in the head because he was offended by King's manner of dressing and how the victim was interacting with him.

McInerney has already served approximately four years in jail and will taste freedom when he is 38, under terms of the deal.

McInerney's case was expected to go to retrial because it was ruled a mistrial in September when jurors couldn't reach a unanimous decision on whether to convict him of voluntary manslaughter or first-degree murder.

We took that into account and looked at what it would take to protect the community, Frawley told The AP. The total time in custody for 25 years will do that.

McInerney is ineligible for time served or good behavior, Frawley said, noting that this is because he has pleaded guilty to murder.

At his first trial, prosecutors said McInerney was a budding white supremacist with a hate for homosexuals.

The defense has said that McInerney came from a violent and dysfunctional home and had reached an emotional breaking point in response to King's advances.

Larry had a complicated life, but he did not deserve to be murdered, his father, Greg King, told the Los Angeles Times after a court hearing on Monday.