Using Add operation in Memcached with Java (Detailed Guide w/ Code Examples)

Use Case(s)

The add operation in Memcached is commonly used to add a new key-value pair into the cache, but only if the server doesn't already hold data for this key. It can be useful in scenarios where you want to prevent overwriting existing data in the cache.

Code Examples

Here is a simple example of adding a key-value pair to Memcached using the spymemcached client library in Java:

import net.spy.memcached.MemcachedClient; // Create a Memcached client MemcachedClient memcachedClient = new MemcachedClient(new InetSocketAddress("localhost", 11211)); // Add a key-value pair to Memcached boolean success = memcachedClient.add("key", 3600, "value").get(); System.out.println(success ? "Data added successfully" : "Failed to add data");

In this example, we're creating a connection to a Memcached server running on localhost at port 11211. We then attempt to add a new key-value pair ("key" and "value"). The second parameter 3600 is the expiry time for this key-value pair in seconds. If the data is added successfully, "Data added successfully" will be printed; otherwise, "Failed to add data" will be printed.

Best Practices

  1. Exception Handling: Always handle exceptions that may occur when performing operations with Memcached, such as connection failures or operation timeouts.
  2. Expiration Times: Avoid setting very long expiration times unless necessary, as it may lead to inefficient use of your cache. Instead, keep updating the cache with relevant data.

Common Mistakes

  • Not Checking Operation Success: Always check if add operation was successful. It's not guaranteed to be successful every time, as it depends on the current state of the cache.
  • Ignoring Return Value: The add method returns a Future object that holds the result of the operation. Ignoring this return value could lead to problems in your code, as you won't be able to handle failures properly.


Q: What happens if I try to add a key-value pair that already exists in the cache?

A: The add operation will not overwrite existing key-value pairs. If the key already exists in the cache, the operation will simply fail and return false.

Q: How can I make sure my data is added to Memcached successfully?

A: You should always check the boolean result returned by the add method to confirm if your data was added successfully.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.