Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6320633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T16:00:35+00:00 2026-05-24T16:00:35+00:00

In GAE, I’ve got a table full of one offs — things like last-used

  • 0

In GAE, I’ve got a table full of “one offs” — things like “last-used sequence number” and the like that don’t really fall into other tables. It’s a simple String-key with String-value pair.

I’ve got some code to grab a named integer and increment it, like so:

@PersistenceCapable(detachable="true")
public class OneOff
{
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private String dataKey;

    @Persistent
    private String value;


    public OneOff(String kk, String vv)
    {
        this.dataKey = kk;
        this.value = vv;
    }


    public static OneOff persistOneOff(String kk, String vv)
    {
        OneOff oneoff= new OneOff(kk, vv);
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try
        {
            pm.makePersistent(oneoff);
        }
        finally
        {
            pm.close();
        }

        return oneoff;
    }


    // snip...
    @SuppressWarnings("unchecked")
    synchronized
    public static int getIntValueForKeyAndIncrement(String kk, int deFltValue)
    {
        int result = 0;
        OneOff oneOff = null;

        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(OneOff.class);
        query.setFilter("dataKey == kkParam");
        query.declareParameters("String kkParam");
        List<OneOff> oneOffs = (List<OneOff>) query.execute(kk);

        int count = oneOffs.size();
        if (count == 1)
        {
            oneOff = oneOffs.get(0);
            result = Integer.parseInt(oneOff.value);
        }
        else if (count == 0)
        {
            oneOff = new OneOff(kk, "default");
            result = deFltValue;
        }
        else
        {
                // Log WTF error.
        }

        // update object in DB.
        oneOff.value = "" + (result+1);
        try
        {
            pm.makePersistent(oneOff);
        }
        finally
        {
            pm.close();
        }

        return result;
    }
    // etc...

However, when I make these calls:

int val1 = OneOff.getIntValueForKeyAndIncrement("someKey", 100);
int val2 = OneOff.getIntValueForKeyAndIncrement("someKey", 100);
int val3 = OneOff.getIntValueForKeyAndIncrement("someKey", 100);

Sometimes I get the desired increment and sometimes I get the same value. It appears that my DB access is running asynchronously, when I’d like to lock the DB for this particular transaction.

I thought that

    synchronized
    public static

was supposed to do that for me, but apparently not (probably due to multiple instances running!)

At any rate — how do I do the thing that I want? (I want to lock my DB while I get & update this value, to make the whole thing concurrency-safe.)

Thanks!

== EDIT ==

I have accepted Robert’s as the correct answer, since transactions were, indeed, what I wanted. However, for completeness, I have added my updated code below. I think it’s correct, although I’m not sure about the if(oneOff==null) clause (the try-catch bit.)

public static int getIntValueForKeyAndIncrement(String kk, int defltValue)
{
    int result = 0;
    Entity oneOff = null;
    int retries = 3;

    // Using Datastore Transactions
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    while (true)
    {
        com.google.appengine.api.datastore.Transaction txn = datastore.beginTransaction();
        try
        {
            Key oneOffKey = KeyFactory.createKey("OneOff", kk);
            oneOff = datastore.get (oneOffKey);
            result = Integer.parseInt((String) oneOff.getProperty("value"));
            oneOff.setProperty("value",  "" + (result+1));
            datastore.put(oneOff);
            txn.commit();
            break;
        }
        catch (EntityNotFoundException ex)
        {
            result = defltValue;
        }
        catch (ConcurrentModificationException ex)
        {
            if (--retries < 0)
            {
                throw ex;
            }
        }

        if (oneOff == null)
        {
            try
            {
                Key oneOffKey = KeyFactory.createKey("OneOff", kk);
                oneOff = new Entity(oneOffKey);
                oneOff.setProperty("value",  "" + (defltValue+1));
                datastore.put(txn, oneOff);
                datastore.put(oneOff);
                txn.commit();
                break;
            }
            finally
            {
                if (txn.isActive())
                {
                    txn.rollback();
                }
            }
        }
        else
        {
            if (txn.isActive())
            {
                txn.rollback();
            }
        }
    }
return result;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T16:00:36+00:00Added an answer on May 24, 2026 at 4:00 pm

    You should be updating your values inside a transaction. App Engine’s transactions will prevent two updates from overwriting each other as long as your read and write are within a single transaction. Be sure to pay attention to the discussion about entity groups.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using GAE's high replication datastore. I previously downloaded a table in csv
I've got a GAE in Python and I am using the Channel API: https://developers.google.com/appengine/docs/python/channel/functions
GAE recommends using JDO/JPA. But I have serious question about using OODB like them.
Learning GAE I`ve got some issue. I want to save contact list of my
We have a GAE application that notifies users of sports goal changes and we
I have a GAE application with a database of users. When one of the
Given that gae & django persistence layers are quite similar, I'm wondering whether someone
I've ported my GAE project to django-nonrel, and now I would like to have
On my Google AppEngine (GAE) server, I'd like to do something like this: if
I am building a GAE site that uses AJAX/JSON for almost all its tasks

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.