Created
October 23, 2014 18:55
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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