Skip to content

Instantly share code, notes, and snippets.

@falkorichter
Created October 23, 2014 18:55
Show Gist options
  • Save falkorichter/5a579aca2179cab10e7b to your computer and use it in GitHub Desktop.
Save falkorichter/5a579aca2179cab10e7b to your computer and use it in GitHub Desktop.
a class that represents a long value that is restored from @{SharedPreferences}. It is thread safe.
package com.sensorberg.sdk.internal;
import android.content.SharedPreferences;
import com.sensorberg.sdk.Constants;
/**
* a class that represents a long value that is restored from @{SharedPreferences}. It is thread safe.
*/
public class PersistentLong {
private final SharedPreferences settingsSharedPrefs;
private long postToServiceCounter;
private final Object postToServiceCounterMonitor = new Object();
public PersistentLong(SharedPreferences settingsSharedPrefs) {
this.settingsSharedPrefs = settingsSharedPrefs;
postToServiceCounter = settingsSharedPrefs.getLong(Constants.SharedPreferencesKeys.Platform.POST_TO_SERVICE_COUNTER, 0);
}
/**
* get the next value, +1 bigger than the last.
* @return the next value, unique, thread safe unique
*/
public long next(){
synchronized (postToServiceCounterMonitor) {
postToServiceCounter++;
settingsSharedPrefs.edit()
.putLong(Constants.SharedPreferencesKeys.Platform.POST_TO_SERVICE_COUNTER, postToServiceCounter)
.apply();
return postToServiceCounter;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment