ChallengeWhat is wrong with this code

time to read 2 min | 282 words

Let us assume that we have the following piece of code. It has a big problem in it. The kind of problem that you get called at 2 AM to solve.

Can you find it? (more below)

public static void Main()
{
	while(true)
	{
		srv.ProcessMessages();
		Thread.Sleep(5000);
	}
}

public void ProcessMessages()
{
	try
	{
	   var msgs = GetMessages();
	   byte[] data = Serialize(msgs);
	   var req =  WebRequest.Create("http://some.remote.server");
	   req.Method = "PUT";
	   using(var stream = req.GetRequestStream())
	   {
		   stream.Write(data,0,data.Length);
	   }
	   var resp = req.GetResponse();
	   resp.Close();// we only care that no exception was thrown
	   
	   MarkMessagesAsHandled(msgs); // assume this can't throw 
	}
	catch(Exception)
	{
		// bummer, but never mind,
		// we will get it the next time that ProcessMessages 
		// is called
	}
}

public Message[] GetMessages()
{
    List<Message> msgs = new List<Message>();
    using(var reader = ExecuteReader("SELECT * FROM Messages WHERE Handled = 0;"))
    while(reader.Read())
    {
        msgs.Add( HydrateMessage(reader) );
    }
    return msgs.ToArray();
}

This code is conceptual, just to make the point. It is not real code. Things that you don't have to worry about:

  • Multi threading
  • Transactions
  • Failed database

The problem is both a bit subtle and horrifying. And just to make things interesting, for most scenarios, it will work just fine.

More posts in "Challenge" series:

  1. (03 Jan 2020) Spot the bug in the stream–answer
  2. (15 Feb 2010) Where is the optimization?