Author: oheger
Date: Sun Feb 23 18:33:36 2014
New Revision: 1571046
URL: http://svn.apache.org/r1571046
Log:
Implemented a thread-safe update mechanism.
Updates are now done using the compareAndSet() method of the atomic reference
storing the current data of the model.
Modified:
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/InMemoryNodeModel.java
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/ModelTransaction.java
commons/proper/configuration/branches/immutableNodes/src/test/java/org/apache/commons/configuration/tree/TestInMemoryNodeModel.java
Modified:
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/InMemoryNodeModel.java
URL:
http://svn.apache.org/viewvc/commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/InMemoryNodeModel.java?rev=1571046&r1=1571045&r2=1571046&view=diff
==============================================================================
---
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/InMemoryNodeModel.java
(original)
+++
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/InMemoryNodeModel.java
Sun Feb 23 18:33:36 2014
@@ -190,27 +190,24 @@ public class InMemoryNodeModel implement
* @param values the values to be added at the position defined by the key
* @param resolver the {@code NodeKeyResolver}
*/
- public void addProperty(String key, Iterable<?> values,
- NodeKeyResolver resolver)
+ public void addProperty(final String key, final Iterable<?> values,
+ final NodeKeyResolver resolver)
{
if (valuesNotEmpty(values))
{
- TreeData currentStructure = getTreeData();
- ModelTransaction tx = new ModelTransaction(this);
- NodeAddData<ImmutableNode> addData =
- resolver.resolveAddKey(currentStructure.getRoot(), key,
- this);
- if (addData.isAttribute())
- {
- addAttributeProperty(tx, addData, values);
- }
- else
- {
- addNodeProperty(tx, addData, values);
- }
-
- // TODO handle concurrency
- structure.set(tx.execute());
+ updateModel(new TransactionInitializer() {
+ public boolean initTransaction(ModelTransaction tx) {
+ NodeAddData<ImmutableNode> addData =
+
resolver.resolveAddKey(tx.getCurrentData().getRoot(), key,
+ InMemoryNodeModel.this);
+ if (addData.isAttribute()) {
+ addAttributeProperty(tx, addData, values);
+ } else {
+ addNodeProperty(tx, addData, values);
+ }
+ return true;
+ }
+ });
}
}
@@ -222,34 +219,30 @@ public class InMemoryNodeModel implement
* @param key the key selecting the properties to be removed
* @param resolver the {@code NodeKeyResolver}
*/
- public void clearTree(String key, NodeKeyResolver resolver)
+ public void clearTree(final String key, final NodeKeyResolver resolver)
{
- TreeData currentStructure = getTreeData();
- ModelTransaction tx = new ModelTransaction(this);
- for (QueryResult<ImmutableNode> result : resolver.resolveKey(
- currentStructure.getRoot(), key, this))
- {
- if (result.isAttributeResult())
- {
- tx.addRemoveAttributeOperation(result.getNode(),
- result.getAttributeName());
- }
- else
- {
- if (result.getNode() == currentStructure.getRoot())
- {
- // the whole model is to be cleared
- clear();
- return;
+ updateModel(new TransactionInitializer() {
+ public boolean initTransaction(ModelTransaction tx) {
+ TreeData currentStructure = tx.getCurrentData();
+ for (QueryResult<ImmutableNode> result : resolver.resolveKey(
+ tx.getCurrentData().getRoot(), key,
InMemoryNodeModel.this)) {
+ if (result.isAttributeResult()) {
+ tx.addRemoveAttributeOperation(result.getNode(),
+ result.getAttributeName());
+ } else {
+ if (result.getNode() == currentStructure.getRoot()) {
+ // the whole model is to be cleared
+ clear();
+ return false;
+ }
+ tx.addRemoveNodeOperation(
+ currentStructure.getParent(result.getNode()),
+ result.getNode());
+ }
}
- tx.addRemoveNodeOperation(
- currentStructure.getParent(result.getNode()),
- result.getNode());
+ return true;
}
- }
-
- // TODO handle concurrency
- structure.set(tx.execute());
+ });
}
/**
@@ -481,6 +474,33 @@ public class InMemoryNodeModel implement
}
/**
+ * Performs a non-blocking, thread-safe update of this model based on a
+ * transaction initialized by the passed in initializer. This method uses
+ * the atomic reference for the model's current data to ensure that an
+ * update was successful even if the model is concurrently accessed.
+ *
+ * @param txInit the {@code TransactionInitializer}
+ */
+ private void updateModel(TransactionInitializer txInit)
+ {
+ boolean done;
+
+ do
+ {
+ ModelTransaction tx = new ModelTransaction(this);
+ if (!txInit.initTransaction(tx))
+ {
+ done = true;
+ }
+ else
+ {
+ TreeData newData = tx.execute();
+ done = structure.compareAndSet(tx.getCurrentData(), newData);
+ }
+ } while (!done);
+ }
+
+ /**
* Checks whether the specified collection with values is not empty.
*
* @param values the collection with node values
@@ -637,4 +657,25 @@ public class InMemoryNodeModel implement
return inverseMapping;
}
}
+
+ /**
+ * An interface used internally for handling concurrent updates. An
+ * implementation has to populate the passed in {@code ModelTransaction}.
+ * The transaction is then executed, and an atomic update of the model's
+ * {@code TreeData} is attempted. If this fails - because another update
+ * came across -, the whole operation has to be tried anew.
+ */
+ private static interface TransactionInitializer
+ {
+ /**
+ * Initializes the specified transaction for an update operation. The
+ * return value indicates whether the transaction should be executed. A
+ * result of <b>false</b> means that the update is to be aborted (maybe
+ * another update method was called).
+ *
+ * @param tx the transaction to be initialized
+ * @return a flag whether the update should continue
+ */
+ boolean initTransaction(ModelTransaction tx);
+ }
}
Modified:
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/ModelTransaction.java
URL:
http://svn.apache.org/viewvc/commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/ModelTransaction.java?rev=1571046&r1=1571045&r2=1571046&view=diff
==============================================================================
---
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/ModelTransaction.java
(original)
+++
commons/proper/configuration/branches/immutableNodes/src/main/java/org/apache/commons/configuration/tree/ModelTransaction.java
Sun Feb 23 18:33:36 2014
@@ -116,8 +116,8 @@ class ModelTransaction
{
model = nodeModel;
currentData = model.getTreeData();
- replacedNodes = currentData.copyReplacementMapping();
- parentMapping = currentData.copyParentMapping();
+ replacedNodes = getCurrentData().copyReplacementMapping();
+ parentMapping = getCurrentData().copyParentMapping();
operations = new TreeMap<Integer, Map<ImmutableNode, Operations>>();
addedNodes = new LinkedList<ImmutableNode>();
removedNodes = new LinkedList<ImmutableNode>();
@@ -206,6 +206,14 @@ class ModelTransaction
}
/**
+ * Returns the current {@code TreeData} object this transaction operates
on.
+ * @return the associated {@code TreeData} object
+ */
+ public InMemoryNodeModel.TreeData getCurrentData() {
+ return currentData;
+ }
+
+ /**
* Returns the parent node of the given node.
*
* @param node the node in question
@@ -213,7 +221,7 @@ class ModelTransaction
*/
ImmutableNode getParent(ImmutableNode node)
{
- return currentData.getParent(node);
+ return getCurrentData().getParent(node);
}
/**
@@ -256,12 +264,12 @@ class ModelTransaction
*/
private int level(ImmutableNode node)
{
- ImmutableNode current = currentData.getParent(node);
+ ImmutableNode current = getCurrentData().getParent(node);
int level = 0;
while (current != null)
{
level++;
- current = currentData.getParent(current);
+ current = getCurrentData().getParent(current);
}
return level;
}
Modified:
commons/proper/configuration/branches/immutableNodes/src/test/java/org/apache/commons/configuration/tree/TestInMemoryNodeModel.java
URL:
http://svn.apache.org/viewvc/commons/proper/configuration/branches/immutableNodes/src/test/java/org/apache/commons/configuration/tree/TestInMemoryNodeModel.java?rev=1571046&r1=1571045&r2=1571046&view=diff
==============================================================================
---
commons/proper/configuration/branches/immutableNodes/src/test/java/org/apache/commons/configuration/tree/TestInMemoryNodeModel.java
(original)
+++
commons/proper/configuration/branches/immutableNodes/src/test/java/org/apache/commons/configuration/tree/TestInMemoryNodeModel.java
Sun Feb 23 18:33:36 2014
@@ -37,6 +37,9 @@ import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
@@ -867,4 +870,80 @@ public class TestInMemoryNodeModel
assertTrue("Replacement mapping too big: " + replacementMapping.size(),
replacementMapping.size() < numberOfOperations);
}
+
+ /**
+ * Tests whether concurrent updates of the model are handled correctly.
This
+ * test adds a number of authors in parallel. Then it is checked whether
all
+ * authors have been added correctly.
+ */
+ @Test
+ public void testConcurrentUpdate() throws InterruptedException
+ {
+ final NodeKeyResolver resolver =
+ EasyMock.createMock(NodeKeyResolver.class);
+ final InMemoryNodeModel model =
+ new InMemoryNodeModel(NodeStructureHelper.ROOT_AUTHORS_TREE);
+ EasyMock.expect(
+ resolver.resolveAddKey(EasyMock.anyObject(ImmutableNode.class),
+ EasyMock.eq(KEY), EasyMock.eq(model)))
+ .andAnswer(new IAnswer<NodeAddData<ImmutableNode>>()
+ {
+ public NodeAddData<ImmutableNode> answer() throws Throwable
+ {
+ ImmutableNode addParent =
+ (ImmutableNode)
EasyMock.getCurrentArguments()[0];
+ return new NodeAddData<ImmutableNode>(addParent,
+ "name", false,
Collections.singleton("author"));
+ }
+ }).anyTimes();
+ EasyMock.replay(resolver);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ final String authorPrefix = "newAuthor";
+ final int threadCount = 32;
+ Thread[] threads = new Thread[threadCount];
+ for (int i = 0; i < threadCount; i++)
+ {
+ final String authorName = authorPrefix + i;
+ threads[i] = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ latch.await();
+ model.addProperty(KEY,
+ Collections.singleton(authorName), resolver);
+ }
+ catch (InterruptedException iex)
+ {
+ // ignore
+ }
+ }
+ };
+ threads[i].start();
+ }
+ latch.countDown();
+ for (Thread t : threads)
+ {
+ t.join();
+ }
+
+ Pattern patternAuthorName =
+ Pattern.compile(Pattern.quote(authorPrefix) + "(\\d+)");
+ Set<Integer> indices = new HashSet<Integer>();
+ for (int i = 0; i < threadCount; i++)
+ {
+ ImmutableNode node = nodeForKey(model, "author(" + i + ")/name");
+ Matcher m =
+ patternAuthorName.matcher(String.valueOf(node.getValue()));
+ assertTrue("Wrong value: " + node.getValue(), m.matches());
+ int idx = Integer.parseInt(m.group(1));
+ assertTrue("Invalid index: " + idx, idx >= 0 && idx < threadCount);
+ indices.add(idx);
+ }
+ assertEquals("Not all authors were created", threadCount,
+ indices.size());
+ }
}