Code example for AtomicLong

Methods: get, set

0
	 * This shouldn't be called onOpen() or onCreate() because it will cause 
	 * a recursive database get. 
	 */ 
	private void ensureCount() { 
		if (!initialCount) {
			count.set(countRows());
			initialCount = true;
		} 
	} 
	 
	@Override 
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// do nothing here for now 
	} 
 
	/** 
	 * Adds a payload to the database 
	 * @param payload  
	 */ 
	public boolean addPayload(BasePayload payload) {
		 
		ensureCount(); 
		 
		long rowCount = getRowCount();
		if (rowCount >= Analytics.getOptions().getMaxQueueSize()) {
			Logger.w("Cant add action, the database is larger than max queue size."); 
			return false; 
		} 
		 
		boolean success = false;
		 
		String json = serializer.serialize(payload);
		 
		synchronized (this) {
						 
			SQLiteDatabase db = null;
			 
			try { 
				 
				db = getWritableDatabase();
				ContentValues contentValues = new ContentValues();
				 
				contentValues.put(
						Constants.Database.PayloadTable.Fields.Payload.NAME,  
						json);
				 
				long result = db.insert(Constants.Database.PayloadTable.NAME, null,
						contentValues);
				 
				if (result == -1) {
					Logger.w("Database insert failed. Result: " + result);
				} else { 
					success = true;
					// increase the row count 
					count.addAndGet(1);
				} 
				 
			} catch (SQLiteException e) {
				 
				Logger.e("Failed to open or write to Segment.io payload db: " +  
						Log.getStackTraceString(e));
				 
			} finally { 
				if (db != null) db.close();
			} 
				 
			return success;
		} 
	} 
 
	/** 
	 * Fetches the total amount of rows in the database 
	 * @return 
	 */ 
	private long countRows() { 
		 
		String sql = String.format("SELECT COUNT(*) FROM %s", 
				Constants.Database.PayloadTable.NAME); 
		 
		long numberRows = 0;	
			 
		SQLiteDatabase db = null;
		 
		synchronized(this) {
				 
			try { 
				db = getWritableDatabase();
				SQLiteStatement statement = db.compileStatement(sql);
				numberRows = statement.simpleQueryForLong();
				 
			} catch (SQLiteException e) {
				Logger.e("Failed to ensure row count in the Segment.io payload db: " +  
						Log.getStackTraceString(e));
			} finally { 
				if (db != null) db.close();
			} 
		} 
		 
		return numberRows;
	} 
	 
	/** 
	 * Fetches the total amount of rows in the database without 
	 * an actual database query, using a cached counter. 
	 * @return 
	 */ 
	public long getRowCount() { 
		if (!initialCount) ensureCount();
		return count.get();
	} 
 
	/** 
	 * Get the next (limit) events from the database 
	 * @param limit