And the mentally ill homeless man gets arrested again and again.

It felt like they had chased the dream forever: to keep the homeless man in the red sneakers off the streets.

Everyone in the Dorchester courtroom this September day knew David: the judge; the defense attorneys and the prosecutors; the caseworker from the state mental health department. For months, for years — even for decades — he had been a familiar figure here, arrested a staggering 150 times, usually on drug charges or for breaking and entering.

He was 56 now, his beard wild and grayed. His thinking was frequently confused. He believed, at times, that his medications made him taller, or that children he saw on the street were undercover police. He had long suffered from delusions, mania, and depression — symptoms that resembled schizoaffective disorder, one psychiatrist who examined him said.

David himself described his condition more simply. “Sometime, my mind don’t work,” he told a court officer in Roxbury one day this fall.

Homeless people are largely ignored by the public: living on the margins; often in the grips of mental illness and addiction; adrift in a world that has given up on them.

But, in some quarters, the Davids loom like giants, challenging and often overwhelming the frontline workers charged with sorting out their problems. Among the city’s 7,500 homeless people, at least 900 have lived that way for years, unable to break out of the cycle. For police and courts and caseworkers who manage mental health care, those are the toughest cases, and they are anything but forgotten.

It’s just that the costly attempts to help them so often fail.

On this autumn day, David’s situation — a complicated tangle of mental illness, homelessness, addiction, and criminal history — would once again frustrate the best efforts of the court. Clinicians at the state-run hospital where he had been sent for evaluation had concluded that he was incompetent to stand trial — but not a danger to himself or others, so they could not keep him against his will. That left the judge to answer a perplexing question: Where could, where should, David go next?

Against the prosecutor’s advice, Judge Lisa Grant sent David back to the hospital, hoping he would voluntarily agree to stay there. “You take good care of yourself, OK?” she told him kindly as he left the courtroom.

But once a caseworker dropped him off at the hospital, David decided not to stay, and he vanished into the city.

Back on the street that night, he was arrested again for breaking and entering — just as the prosecutor had warned he would be.

A few days later, in another Boston courtroom, the same hard questions would once again need answers: Where could David go? How long would he stay there?

John Blanding/Globe Staff/File People lined up outside Pine Street Inn in 1979. Over the next decade, the shelter and others across Boston were forced to absorb thousands of men and women with mental illness who had been let out of state-run hospitals.

Decades ago, state officials made a decision to care for people like David in the community, not in state mental hospitals, closing the old Victorian institutions one after another. But the care they substituted fell far short of what was needed to help many patients manage. Thousands of people with mental illness wound up on the streets — or crowded into shelters meant to house and feed them, not to offer treatment.

By 1990, the problem was so bad that the city and its best-known shelter for the homeless, the Pine Street Inn, sued the state Department of Mental Health for failing to provide decent community mental health care.

But the state’s highest court ruled the state had no legal obligation to care for people discharged from its hospitals. Homeless shelters became “the new asylums,” along with jails and prisons. By 1991, the Pine Street Inn had essentially become the largest mental institution in the state, with 50 percent of the men and 90 percent of the women at the 735-bed shelter reporting mental illness, according to news accounts at the time.

A political and systemic failure spawned a predictable humanitarian crisis.

Among 1,500 chronically homeless people statewide whose cases were assessed by the Massachusetts Housing & Shelter Alliance in the last two years, 85 percent said they suffer from mental health problems. About half reported struggles with addiction.

For many, like David, problems once managed at state hospitals are now worked out in police stations, courtrooms, and shelters. That system has proven ineffective, as David’s case makes clear. And it is exceedingly expensive.

The state pays $37,400, on average, per year to care for a chronically homeless person who spends an average amount of time in homeless shelters, detox centers, jails, and hospitals, according to data collected by the housing alliance, a Boston-based advocacy group.

And that sum doesn’t factor in police or court costs.

In the last four years alone, David has been arrested some 50 times, costing the city of Boston an estimated $100,000 for bookings alone. He spent at least three months in jail, at a cost to the public of about $12,000, and at least six months in state hospitals, which cost about $500 per day. In total, that works out to $50,000 a year on services that have failed to turn David’s life around — not including the cost of his frequent court appearances.

By contrast, providing one homeless person with permanent, long-term housing — and the support services to help them succeed — costs about $15,500 per year, according to the shelter alliance.

“There is a cost associated with doing nothing,” said Joe Finn, the leader of the nonprofit housing alliance. “There are people who cost millions of dollars because of the way we use resources.”

While the number of David’s arrests is extraordinary, homeless people collectively account for more than 12 percent of all arrests by Boston police, based on records from 2008 to 2016. People who list the Pine Street Inn as their residence were arrested more than 5,000 times in that period.

It isn’t clear exactly what solution might help David. His stints in housing haven’t lasted, though public records don’t say much about how much oversight he got there. Boston police think he needs long-term hospitalization. Others believe he could succeed in supervised housing, if it provided an intensive daily structure. Then there are alternative approaches that aim to first provide permanent shelter, then slowly implement psychiatric care.

One thing is clear: The current way isn’t working.

“Everyone knows who he is, and nobody knows what to do with him,” said one police officer who has known David for years. “We have a lot of guys like this — he’s not alone. You can take him to the hospital, but he doesn’t want to go. You can take him to the court, and he’ll just be released. It’s a frustrating thing. . . . And it’s [bad] for the guy because he needs help.”

The frustration flared in a Roxbury courtroom in May, when Boston Police Captain Haseeb Hosein showed up unannounced to demand an explanation for David’s continued presence on the streets. Why, he asked, is there nowhere he can go, no hospital to take him, no one who can help?

Told that David could not, by law, be committed to a hospital against his will unless he could be proven dangerous, Hosein was incredulous.

“He’s going into people’s houses,” the police captain said he told the court. “Someone is going to shoot him. Isn’t that enough?”

Though David can be angry and aggressive, according to people who know him, his recent history has not been violent. His most serious convictions, for armed robbery and armed assault, happened 25 years ago.

State law provides that a person may be committed against his will if he is a danger to himself or others, or if his judgment is so impaired he can’t protect himself. In practice, observers said, the final provision is typically applied to people less skilled at survival than David: those too ill to find food or shelter from the cold.

It would be easy to dismiss his case as hopeless. But some won’t.

“If he were to get the structure he needs,” said Jillian Hira, a Suffolk County prosecutor who works with David in the mental health court in Roxbury, “I think he would grasp onto it and hold on for dear life.”

David’s early life was marked by pain and loss. One of 10 children, according to one court document, he grew up in Roxbury and Mattapan with a mother who suffered from schizophrenia and addiction. Other court documents say he was abused as a child and placed in foster care. His biological father was stabbed to death; his biological mother died of a drug overdose.

He began to suffer from mental illness as a teenager and would be diagnosed, at various times, with schizophrenia, bipolar disorder, and schizoaffective disorder.

Hospitalized dozens of times over the decades, including at least seven stays at Bridgewater State Hospital, a medium-security prison that houses mentally ill men, he has been prescribed “nearly every anti-psychotic medication available over the past 30 years,” a court report stated. He has also abused crack cocaine and other drugs.

“I’m not a menace to a society,” David said in an interview with the Globe in October at the Suffolk County jail, where he was being held on a charge of breaking and entering. “I consider myself mentally disabled. My foster mother showed me the right way [to live] before she died. . . . But sometimes I fall by the wayside.”

His demeanor was calm, his tone often plaintive. He wore his red sneakers and an orange inmate jumpsuit.

Suzanne Kreiter/Globe Staff David, a chronically homeless man who has mental illness and has racked up dozens of arrests for crimes like breaking and entering, was at the Nashua Street Jail in October following his latest arrest.

State caseworkers declined to comment on his case, citing their obligation to protect his privacy. Reporters reviewed records of his history from courts and police and observed a half dozen of his court appearances. Though his full name is a matter of public record, the Globe opted not to publish his last name.

When he commits crimes, stealing things by night, David said he is often driven by hunger. Other times, he panhandles for change to buy food, or digs through dumpsters to find something to eat.

To David, who long ago lost ties to relatives, the police are like the family he lacks.

“They treat me like a son,” he said. “They buy me sandwiches. They say, ‘David, be careful.’ ”

He has also found unexpected kindness in the courts, especially the mental health session in Roxbury District Court, a cutting-edge specialty program designed to help people with mental illness. Attorneys there stash a backpack full of canned goods in the courtroom, for days when David shows up hungry. One August morning when David came to court looking haggard and exhausted, court staff intervened as he slumped half-asleep on a bench in the hallway.

“Would you like to wait for [your caseworker] in a comfy chair, so you can rest?” one of them asked gently. David accepted and let himself be led to a less hectic corner of the courthouse.

For a time in the spring, he lived at a Dorchester rooming house where the rent consumed 60 percent of his monthly income, a $650 disability check. That left him just $8.67 per day to cover his other expenses, including meals. Lacking the required ID cards, he could not get food stamps.

Eventually, he left the house for someplace cheaper. But that proved hard to find.

Asked by a reporter about his happiest memory, David spoke with longing of a simple life.

“When I had a job,” he said. “When I had a car and was going to church. When I worked hard and wasn’t stealing anything.”

He hopes to have a home again someday, a job, and “a real friend.”

“I’d like to feel love again,” he said.

The concept sounds hopelessly naive: Give a chronically homeless person a place to live — not a shelter bed, but a permanent residence — and hand over the keys with no strings attached. No curfew. No demand for sobriety. No required psychiatric treatment.

Advocates for “low-barrier” or “low-threshold” housing say it often works because it gives people a stable home in which to focus on other problems. The hard part is finding enough affordable housing.

“We’ve figured out what works,” said Finn, the head of the housing alliance. “We haven’t figured out how to bring it to scale.”

At Stapleton House, a small residence operated by the Pine Street Inn in the South End, 11 men have permanent housing. They come and go as they wish. When each is ready — it can take months or years — the staff is there to help them take steps to improve their own lives. Often, it is the first time they have ever received regular mental health treatment.

“I feel normal,” said Bill Warren, 72, who started seeing a psychiatrist and taking medication for schizophrenia while at Stapleton. He lived there for two years, after decades without stable housing. By August, he was doing so well he moved into his own apartment.

Suzanne Kreiter/Globe Staff Bill Warren, who has been diagnosed with schizophrenia and now has his own apartment, once lived at the Stapleton House. The innovative housing program run out of the Pine Street Inn aims to take chronically homeless men with mental illness off the street.

Every man who has come through the house — 20 to 30 since 2007, at a cost of $50,000 each per year — has eventually agreed to try medication, said Barbara Davidson, the clinician who runs the program. All have stayed on it. And in nine years, the staff has never had to call police.

“Housing itself has a tremendously stabilizing influence,” Finn said.

The Department of Mental Health, tasked with supporting David and 21,000 others with severe illness, has 461 total beds statewide in shelters and longer-term housing, many with waiting lists. DMH declined to make housing officials available to discuss the adequacy of its housing programs and could not say how many of its clients are homeless.

Some housing programs are not well-suited to people like David, who struggle with requirements that they stay sober or use their bed nightly. Too often, lacking help they need to change behaviors, they give up and go back to the street.

That’s what happened to David in the summer of 2012: He lost his bed at a halfway house in Hyde Park, according to records, because he continued to sleep outside two or three nights at a time. He returned to homelessness, then ended up in jail.

“Being housed involves a huge change in lifestyle,” said Earl Miller, a community support coordinator with the Western Mass Recovery Learning Community. “If you’ve been living outside, an apartment can feel like a coffin. You don’t trust it yet. You might need to try it for a night, and if that works, add another night.”

Other hurdles are harder. A criminal record is a barrier to housing, and a long hospitalization can be one, too: After being discharged, a patient may no longer qualify as homeless.

Housing officials in Boston have launched an ambitious, multiagency effort to find a permanent home for every chronically homeless person in the city in two years. Working from a list of 612 names, they have housed 212 individuals — people with a combined 1,221 years of homelessness.

“We’re trying to move from a system that has been very complex . . . to a system where we prioritize the most vulnerable people,” said Laila Bernstein, the city’s first-ever special adviser on chronic homelessness.

Back in court again later this fall, David trembled as he stood before the judge. He’d been in jail. His appearance was disheveled. His medication, he insisted, was not working.

“My head keeps shaking!” he complained, his quiet voice becoming a wail. “I’m not in the right state of mind!”

“I know, I know,” his lawyer told him soothingly.

“I’m a human being!” David cried, sounding close to tears. “I’m not an animal!”

A court officer escorted him out of the courtroom.

When he returned to court a few weeks later, David had a place to stay at night, at the Lindemann Mental Health Center in Boston. But he worried about staying out of trouble in the daytime, when the shelter’s residents have to stay outside.

Hope and concern mingled in the courtroom. David had a bed — but how long would it last?

The judge looked down at the man in the red sneakers. “I’ve got my fingers crossed for you,” he said.