Alex Gray, from Perth in Tayside, was convicted of burglary and harassment in April at Harrow Crown Court. Gray, 31, had started pursuing the star in 2008, sending abusive letters before he was banging on her door and spending nights in her back garden, reported BBC.
He was charged last October when the singer was awoken by him bursting into her bedroom in the early hours.
The singer was with her children in the room when he broke in to the flat, forcing her to leave the property for good.
Sentencing, Judge Martyn Barklem said the stalker had told police he would "cut her with a knife".
The judge said, "This was a terrifying experience for (Lily Allen), and it was extremely fortunate there was an adult male in the property who evicted Mr Gray from it.