Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I come across this problem usually (especially when dealing with certain frameworks) where I would like once piece of code to execute once and only once however the provided method e.g (something like an onComplete function) that I wish to place this instruction in will in reality execute multiple times.

I am just wondering does anybody know of the best way that would get around this problem, one programmer friend of mine told me to use a flag (boolean) to check whether or not this code has already run but I feel like this is not a suitable solution and I would not like to introduce global variables for the sake of checking a condition once and only once.

Has anybody ever come across a problem like this before, I am wondering is there any good practice out there to keep in mind when dealing with code like this.

share|improve this question

closed as too broad by MichaelT, Bart van Ingen Schenau, gnat, Ixrec, GlenH7 Feb 24 at 0:19

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

What are you using? It depends a lot on the language and environment, Javascript on a web page is quite different from Java/Tomcat. – Jaydee Aug 15 '12 at 8:36
Would totally depend on language and environment. In C++ a static variable local to the function could hold the information, in Ruby you would do something like @listings ||= get_listings! – thorsten müller Aug 15 '12 at 8:38
I am struggling to think of a situation where you would need code to execute only once, especially in an event function. It sounds like the code doesn't belong there in the first place, and would be better moved to a constructor or another function, rather than introduce a boolean flag to enforce only running the code once. It may be worth posting an example, so we can better advise how to solve the problem. – Gavin Coates Aug 15 '12 at 11:13
Lazy initialization, for example. Initialization might be expensive, and you don't want to do it If the event never happens. – Stuart Marks Aug 15 '12 at 15:45

In C, I used to use function pointers for this. The first time the function was called, the initialization function was called. At the end of the initialization function, it changed the function pointer to point at the code that was to be called the rest of the time. There are various ways to do this in other languages, with various levels of efficiency.

share|improve this answer
assuming you take care of concurrency where necessary, that's a good way to deal with it. It's essentially the State pattern from OO - it starts in the "uninitialized" state and calling the function transitions it into the "ready" state. – user4051 Aug 15 '12 at 13:05
How is this different from using a global? You function effectively becomes the global. – Pieter B Feb 20 at 23:16

these notes might be useful:

  1. You can create an idempotent function, which means that no matter how many times you call that method, you still get the same result.
  2. Using an if statement to check an external condition, and run the code only if that condition is not met. (Maybe another implementation of idempotency)
  3. As you said, inject this dependency into your method. Your method is dependent upon an external state to tell it how many times it's been executed. Thus if another manager (container) manage this for your method, things get easier.
share|improve this answer
+1 for idempotence. Instead of making it insert, make it insert or update, and you suddenly don't care how many times it runs. – EricBoersma Aug 15 '12 at 13:44

The way it's done in Grand Central Dispatch is to use a semaphore type called a "once token". Your code would look something like this:

void do_something_once(once_token *token, void (*work)()) {
  if(atomic_read(token) == 0) {

void initialize() {/* the work */}

static once_token do_once = 0;
do_something_once(&do_once, initialize);

Where the details of atomically reading and incrementing the token depend on your platform.

share|improve this answer
But most certainly not like that. First, it's slow. Second, it doesn't work. Or better, the other way round. (Multiple threads can read the token as 0). GCD uses a variable with three states: 0 = Never examined, > 0 = somebody is running the once only code. < 0 = Once only code has been executed. You do a fast non-atomic check whether token < 0 first. – gnasher729 Feb 21 at 20:13

A boolean flag indicating the method ran would be the right solution.

Not sure why you think this needs to be a global variable though - it can be declared outside the loop before it starts running.

If you do need to ensure that the method only ever runs once during the lifetime of the program run, there are several different ways to do this, depending on the language, but they do all essentially boil down to a global boolean (though in some languages that can be encapsulated).

For example in C#:

You can have the method live in a static class with a private static boolean - this would only be visible to the class itself and you can set it once the method executes the first time. Next time through, since the flag is set, you don't execute the body of the method. Statics are global state, but as a private member, the flag is not visible to other classes.

share|improve this answer
The method may be called from different places. Makes sense in some situations, Rails even comes with a class to cache expensive method calls. (A boolean flag would work if your language has them, anyway you still need to store the results from previous call) – thorsten müller Aug 15 '12 at 8:40

In C# you might use a class like this:

public sealed class DoOnce
    private Action _action;

    public DoOnce(Action action)
        _action = action;

    public void Invoke()
        var action = Interlocked.Exchange(ref _action, null);


Then to use it:

var doOnce = new DoOnce(() => Console.WriteLine("Just the one time"));
doOnce.Invoke(); // prints
doOnce.Invoke(); // doesn't print
doOnce.Invoke(); // doesn't print

This will perform the action only one time, and is free from race conditions (it is thread safe).

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.