Skip to content

Commit

Permalink
Make JSONFileBootstapStore thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
sbernard31 committed Jul 2, 2019
1 parent fd82ac1 commit 60e9c90
Showing 1 changed file with 34 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.eclipse.leshan.server.bootstrap.BootstrapConfig;
import org.eclipse.leshan.server.bootstrap.EditableBootstrapConfigStore;
Expand All @@ -43,6 +46,11 @@ public class JSONFileBootstrapStore extends InMemoryBootstrapConfigStore {

private static final Logger LOG = LoggerFactory.getLogger(JSONFileBootstrapStore.class);

// lock for the two maps
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();

// default location for persistence
public static final String DEFAULT_FILE = "data/bootstrap.json";

Expand All @@ -68,21 +76,41 @@ public JSONFileBootstrapStore(String filename) {
this.loadFromFile();
}

@Override
public Map<String, BootstrapConfig> getBootstrapConfigs() {
readLock.lock();
try {
return super.getBootstrapConfigs();
} finally {
readLock.unlock();
}
}

public void addToStore(String endpoint, BootstrapConfig config) throws InvalidConfigurationException {
super.addConfig(endpoint, config);
}

@Override
public void addConfig(String endpoint, BootstrapConfig config) throws InvalidConfigurationException {
addToStore(endpoint, config);
saveToFile();
writeLock.lock();
try {
addToStore(endpoint, config);
saveToFile();
} finally {
writeLock.unlock();
}
}

@Override
public BootstrapConfig removeConfig(String enpoint) {
BootstrapConfig res = super.removeConfig(enpoint);
saveToFile();
return res;
writeLock.lock();
try {
BootstrapConfig res = super.removeConfig(enpoint);
saveToFile();
return res;
} finally {
writeLock.unlock();
}
}

// /////// File persistence
Expand All @@ -103,7 +131,7 @@ private void loadFromFile() {
}
}

private synchronized void saveToFile() {
private void saveToFile() {
try {
// Create file if it does not exists.
File file = new File(filename);
Expand Down

0 comments on commit 60e9c90

Please sign in to comment.