When faith takes hold of God, there is hope. You can read about that in Psalm 142:7. The Psalm of loneliness ends in the gathering of a lot of people who thank the Lord. David takes hold of God and therefore knows of this future of praise and thanksgiving. We see the same thing in Psalm 22:1–31, the Psalm of Jesus. After the total loneliness (Psalm 22:1) at the cross, there will be a great congregation, coming from the ends of the world (Psalm 22:25–31). Jesus died alone so that together we may sing songs of grace.
7 Bring me out of prison, that I may give thanks to your name! The righteous will surround me, for you will deal bountifully with me.