From a13c54e093811a5a25cd456e2e68c70c2e39ef51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kjetil=20=C3=98rbekk?= Date: Sun, 26 Feb 2012 22:44:45 +0100 Subject: Add Variable.waitForChange() with lots of bugs. --- same/src/main/java/com/orbekk/same/Variable.java | 2 ++ .../main/java/com/orbekk/same/VariableFactory.java | 28 ++++++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) (limited to 'same') diff --git a/same/src/main/java/com/orbekk/same/Variable.java b/same/src/main/java/com/orbekk/same/Variable.java index b6d3b7f..f305f4b 100644 --- a/same/src/main/java/com/orbekk/same/Variable.java +++ b/same/src/main/java/com/orbekk/same/Variable.java @@ -13,5 +13,7 @@ public interface Variable { T get(); void set(T value) throws UpdateConflict; void update(); + void waitForChange(); + boolean waitingForUpdate(); void setOnChangeListener(OnChangeListener listener); } diff --git a/same/src/main/java/com/orbekk/same/VariableFactory.java b/same/src/main/java/com/orbekk/same/VariableFactory.java index 8c786c0..3d80e28 100644 --- a/same/src/main/java/com/orbekk/same/VariableFactory.java +++ b/same/src/main/java/com/orbekk/same/VariableFactory.java @@ -25,6 +25,7 @@ public class VariableFactory { T value; long revision = 0; OnChangeListener listener = null; + boolean waitingForUpdate; public VariableImpl(String identifier, TypeReference type) { this.identifier = identifier; @@ -37,21 +38,25 @@ public class VariableFactory { } @Override - public void set(T value) throws UpdateConflict { + public synchronized void set(T value) throws UpdateConflict { try { String serializedValue = mapper.writeValueAsString(value); client.set(identifier, serializedValue, revision); + waitingForUpdate = true; } catch (JsonGenerationException e) { logger.warn("Failed to convert to JSON: {}", value); logger.warn("Parse exception.", e); + waitingForUpdate = false; throw new RuntimeException(e); } catch (JsonMappingException e) { logger.warn("Failed to convert to JSON: {}", value); logger.warn("Parse exception.", e); + waitingForUpdate = false; throw new RuntimeException(e); } catch (IOException e) { logger.warn("Failed to cornvert to JSON: {}", value); logger.warn("Parse exception.", e); + waitingForUpdate = false; throw new RuntimeException(e); } } @@ -68,11 +73,30 @@ public class VariableFactory { } @Override - public void stateChanged(Component component) { + public synchronized void waitForChange() { + while (waitingForUpdate) { + try { + wait(); + } catch (InterruptedException e) { + waitingForUpdate = false; + return; + } + } + } + + @Override + public synchronized boolean waitingForUpdate() { + return waitingForUpdate; + } + + @Override + public synchronized void stateChanged(Component component) { if (component.getName().equals(identifier)) { if (listener != null) { listener.valueChanged(this); } + waitingForUpdate = false; + notifyAll(); } } } -- cgit v1.2.3