java.util.ConcurrentModificationException while using ExecutorService - java

I am working on some project in which I am using Observer design Pattern.
Subject class is :
public class Subject {
private List<Observer> observers = new ArrayList<Observer>();
private int state;
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
public void deattach(Observer observer) {
observers.remove(observer);
}
}
Observer Interface is:
public abstract class Observer implements Runnable{
protected Subject subject;
public abstract void update();
public abstract void process();
}
One of the Observer Named as HexObserver is:
public class HexaObserver extends Observer {
private ExecutorService threadpool = Executors.newFixedThreadPool(10);
public HexaObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
#Override
public void update() {
System.out.println("Hex String: "
+ Integer.toHexString(subject.getState()));
Future future = threadpool.submit(new HexaObserver(subject));
}
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("In run :D :D :D");
}
#Override
public void process() {
// TODO
}
}
Class to test this is:
public class Demo {
public static void main(String[] args) {
Subject subject = new Subject();
HexaObserver hob = new HexaObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
}
}
When I tried to run this this is giving some Error:
First state change: 15
Hex String: f
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Observer.Subject.notifyAllObservers(Subject.java:23)
at Observer.Subject.setState(Subject.java:15)
at Observer.Demo.main(Demo.java:12)
In run :D :D :D
I didn't get why I am getting this error as ConcurrentModificationException is thrown out when we try to modify some Object concurrently when it is not permissible.
Am I missing something ?

Two things are happening at the same time: you are iterating over observers and adding an element to observers. That causes your ConcurrentModificationException
In general there are at least three things you can do:
use a synchronized collection
thread-safely copy the collection and iterate on a copy
manually synchronize all access to observers with synchronized block:
 
public void attach(Observer observer){
synchronized(observers){
observers.add(observer);
}
}
public void notifyAllObservers(){
synchronized(observers){
for (Observer observer : observers) {
observer.update();
}
}
}
public void deattach(Observer observer) {
synchronized(observers){
observers.remove(observer);
}
}
you can also mark whole methods as synchronized, but then they will synchronize on an instance of Subject and not on the collection instance.
However, in your case the problem is connected to what your update() does.
Are you sure your HexaObserver's update should create a new HexaObserver? Because you are adding a new instance of the same class to a collection which already contains that instance.

ConcurrentModificationException is usually the sign that you used an Iterator on a Collection and that while iterating, you also modified the underlying Collection (remember that foreach-expression are actually a shortcut for using Iterator). The only way to solve this, is to iterate on a copy of the original collection. If you are in a multi-threaded environment, you also need to ensure that the copy of the collection is done in a thread-safe way.
So you could for example have:
public class Subject {
private List<Observer> observers = new Vector<Observer>();
private int state;
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : ((List<Observer)observers.clone())) {
observer.update();
}
}
public void deattach(Observer observer) {
observers.remove(observer);
}
}

Related

Synchronizing overlapping sets of methods

Imagine a Java class with three methods:
master()
foo()
bar()
I want to synchronize master() and foo() and also master() and bar(), without synchronizing foo() and bar(). It can be done will a separate lock for every pair of synchronized methods, but my actual code has many more than three methods so I was hoping there's a way to do it without so many lock objects.
You are essentially describing a ReadWriteLock. Every two methods are allowed to run simultaneously (a "read lock"), except for master(), which excludes all others (a "write lock"):
public class MyClass {
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock r = rwLock.readLock();
private final Lock w = rwLock.writeLock();
public void master() {
w.lock();
// do stuff
w.unlock();
}
public void foo() {
r.lock();
// do stuff
r.unlock();
}
public void bar() {
r.lock();
// do stuff
r.unlock();
}
}
You can use synchronized on any Object. So, you can create a separate lock for the methods:
public class Lock {
private final Object master_foo = null;
private final Object master_bar = null;
public void master() {
synchronized(master_foo) {
synchronized(master_bar) {
...
}
}
}
public void foo() {
synchronized(master_foo) {
...
}
}
public void bar() {
synchronized(master_bar) {
...
}
}
}
I would go with Mureinik's answer, but just for the heck of it, here's another way you can set up read/write synchronization (untested):
public class Test {
private final Semaphore semaphore = new Semaphore(Integer.MAX_VALUE);
public void master() {
semaphore.acquireUninterruptibly(Integer.MAX_VALUE);
try {
//...
} finally {
semaphore.release(Integer.MAX_VALUE);
}
}
public void foo() {
semaphore.acquireUninterruptibly();
try {
//...
} finally {
semaphore.release();
}
}
public void bar() {
semaphore.acquireUninterruptibly();
try {
//...
} finally {
semaphore.release();
}
}
}

Java Observer Pattern - How to remove observers during update(notify) loop/iteration?

I am very new to java so sorry in advance if anything I say sounds newbish, be gentle.
I have implemented a basic Observer Pattern. Some observers should only listen to one update and then immediately remove themselves from the observers/listeners list. However, whenever I tried doing that I got the famous java.util.concurrentmodificationexception error.
I'm obviously getting this error because I'm changing the list while still iterating over it, yet I am still unsure what is the right solution. I'm wondering if I'm even doing this the right way. If I am, what would be the needed fix to make it work? And if I'm not, I'd like to get suggestions for a better way of achieving what I'm trying to do.
Here's my code:
public interface Listener {
public void onValueChange(double newValue);
}
public class Observed {
private int value;
List<Listener> listeners = new ArrayList<>();
public void addListener(Listener toAdd) {
listeners.add(toAdd);
}
public void removeListener(Listener toRemove) {
listeners.remove(toRemove);
}
public void changeValue(double newValue) {
value = newValue;
for (Listener l : listeners) l.onValueChange(newValue);
}
}
public class SomeClassA implements Listener{
private Observed observed;
SomeClassA(Observed observed) {
this.observed = observed;
}
#Override
public void onValueChange(double newValue) {
System.out.println(newValue);
observed.removeListener(this);
}
}
public class SomeClassB implements Listener{
#Override
public void onValueChange(double newValue) {
System.out.println(newValue);
}
}
public class ObserverTest {
public static void main(String[] args) {
Observed observed = new Observed();
SomeClassA objectA = new SomeClassA(observed);
SomeClassB objectB = new SomeClassB();
observed.addListener(objectB);
observed.addListener(objectA);
observed.changeValue(4);
}
}
one ways is to go fo CopyOnWriteArraylist instead of ArrayList .
CopyOnWriteArraylist is a thread-safe variant of ArrayList in which
all mutative operations (add, set, and so on) are implemented by
making a fresh copy of the underlying array.
Reason why its thrown in your case
you are modifying a collection directly while it is iterating over the collection under method changeValue()
You can not remove items from a collection while you are iterating over it. That is, unless you use the Iterator#remove method. Since that is not a possibility in this case, an alternative is make a copy of your listener list and iterate over that instead. In that case the original listener list is free to be manipulated by the individual listeners:
public void changeValue(double newValue) {
value = newValue;
List<Listener> copyOfListeners = new ArrayList<Listener>(listeners);
for(Listener l : copyOfListeners) {
l.onValueChange(newValue);
}
}
the code below works, so you can try whatever it does.
import java.util.Observable;
import java.util.Observer;
class Model extends Observable {
public void setX(double x) {
this.x=x;
System.out.println("setting x to "+x);
setChanged();
notifyObservers();
}
double x;
}
class A implements Observer {
A(Model model) {
this.model=model;
}
#Override public void update(Observable arg0,Object arg1) {
System.out.println(getClass().getName()+" "+((Model)arg0).x);
((Model)arg0).deleteObserver(this);
}
Model model;
}
class B implements Observer {
#Override public void update(Observable arg0,Object arg1) {
System.out.println(getClass().getName()+" "+((Model)arg0).x);
}
}
public class So19197579 {
public static void main(String[] arguments) {
Model model=new Model();
model.addObserver(new A(model));
model.addObserver(new B());
model.setX(4);
model.setX(8);
}
}

Read and write into shared thread variables

first of all i am new to threads and shared variables. So please be kind with me ;-)
I'm having a class called Routing. This class recieves and handles messages. If a message is of type A the Routing-Object should pass it to the ASender Object which implements the Runnable Interface. If the message is of type B the Routing-Class should pass it to the BSender Object.
But the ASender and BSender Objects have common variables, that should be stored into the Routing-Object.
My idea now is to declare the variables as synchronized/volatile in the Routing-Object and the getter/setter also.
Is this the right way to synchronize the code? Or is something missing?
Edit: Added the basic code idea.
RoutingClass
public class Routing {
private synchronized Hashtable<Long, HashSet<String>> reverseLookup;
private ASender asender;
private BSender bsender;
public Routing() {
//Constructor work to be done here..
reverseLookup = new Hashtable<Long, HashSet<String>>();
}
public void notify(TopicEvent event) {
if (event.getMessage() instanceof AMessage) {
asender = new ASender(this, event.getMessage())
} else if (event.getMessage() instanceof BMessage) {
bsender = new BSender(this, event.getMessage())
}
}
public synchronized void setReverseLookup(long l, Hashset<String> set) {
reverseLookup.put(l, set);
}
public synchronized Hashtable<Long, Hashset<String>> getReverseLookup() {
return reverseLookup;
}
}
ASender Class
public class ASender implements Runnable {
private Routing routing;
private RoutingMessage routingMessage;
public ASender(Routing r, RoutingMessage rm) {
routing = r;
routingMessage = rm;
this.run();
}
public void run() {
handleMessage();
}
private void handleMessage() {
// do some stuff and extract data from the routing message object
routing.setReverseLookup(somethingToSet)
}
}
Some comments:
Hashtable is a thread-safe implementation, you do not need another "synchronized" keyword see this and this for more information
Avoid coupling, try to work with interfaces or pass the hashtable to your senders, see this for more information
Depending on the amount of senders, you might want to use a ConcurrentHashMap, it greatly improves the performance, see ConcurrentHashMap and Hashtable in Java and Java theory and practice: Concurrent collections classes
This would conclude something like...:
public interface IRoutingHandling {
void writeMessage(Long key, HashSet<String> value);
}
public class Routing implements IRoutingHandling {
private final Hashtable<Long, HashSet<String>> reverseLookup;
private ASender asender;
private BSender bsender;
public Routing() {
//Constructor work to be done here..
reverseLookup = new Hashtable<Long, HashSet<String>>();
}
public void notify(TopicEvent event) {
if (event.getMessage() instanceof AMessage) {
asender = new ASender(this, event.getMessage())
} else if (event.getMessage() instanceof BMessage) {
bsender = new BSender(this, event.getMessage())
}
}
#Override
public void writeMessage(Long key, HashSet<String> value) {
reverseLookup.put(key, value);
}
}
public class ASender implements Runnable {
private IRoutingHandling _routingHandling;
public ASender(IRoutingHandling r, RoutingMessage rm) {
_routingHandling = r;
routingMessage = rm;
this.run();
}
public void run() {
handleMessage();
}
private void handleMessage() {
// do some stuff and extract data from the routing message object
_routingHandling.writeMessage(somethingToSetAsKey, somethingToSetAsValue)
}
}

Making a Class Threadsafe using Inheritance

Suppose I have a class like this:
package com.spotonsystems.bulkadmin.cognosSDK.util.Logging;
public class RecordLogging implements LittleLogging{
private LinkedList <String> logs;
private boolean startNew;
public RecordLogging() {
logs = new LinkedList<String>();
}
public void log(String log) {
logHelper(log);
startNew = true;
}
public void logPart(String log) {
logHelper(log);
startNew = false;
}
private void logHelper(String log){
// DO STUFF
}
public LinkedList<String> getResults() {
return logs;
}
}
Now suppose that I need a thread safe version of this code. I need the tread safe version to implement LittleLogging. I want the thread safe copy to have the same behavior as this class except I would like it to be thread safe. Is it safe to do this:
package com.spotonsystems.bulkadmin.cognosSDK.util.Logging;
public class SyncRecordLogging extends RecordLogging {
public SyncRecordLoging() {
super();
}
public syncronized void log(String log) {
super.log(log);
}
public syncronized void logPart(String log) {
super.log(log);
}
public syncronized LinkedList<String> getResults() {
return logs;
}
}
Bonus Question: Where should I look for documentation about syncronization and threading
You can use composition instead. Also note that getResults creates a copy of the list:
public class SyncRecordLogging implements LittleLogging{
private final RecordLogging _log;
public SyncRecordLogging() {
_log = new RecordLogging();
}
public synchronized void log(String log) {
_log.log(log);
}
public synchronized void logPart(String log) {
_log.logPart(log);
}
public synchronized LinkedList<String> getResults() {
// returning copy to avoid 'leaking' the enderlying reference
return new LinkedList(_log.getResults());
}
}
Best read: Java Concurrency In Practice

Having trouble getting the observer pattern working

I have been trying to no avail to get the observer pattern working in a relatively simple application.
I have 4 GUI classes
StarterClass (contains a CompositeWordLists and a CompositeWordListData)
CompositeWordLists (contains many CompositeListItem/s and a CompositeWordListData)
CompositeListItem
CompositeWordListData (Contains a DialogWordData)
DialogWordData
Here is my Observable
interface Observable<T> {
void addObserver(T o);
void removeObserver(T o);
void removeAllObservers();
void notifyObservers();
}
And I am creating Observers like this:
public class Observers {
private Observers(){};
interface WordListsObserver {
public void update(CompositeWordLists o);
}
interface ListItemObserver {
public void update(CompositeListItem o);
}
}
Basically I am having trouble with specifying the sort of event that occurred. For example, the CompositeWordLists class needs to know when a CompositeListItem is deleted, saved edited etc but I only have one update method ... my brain hurts now!
What is a better way of doing this?
UPDATE
Still having trouble with this, I added events and changed Observable and Observers but now I have type safety problems.
public class Observers {
private Observers(){};
/**
* #param <T> the object that is passed from the Observable
*/
interface ObservableEvent<T> {
T getEventObject();
}
/**
* Get notified about Authentication Attempts
*/
interface ObserverAuthenticationAttempt {
/**
* #param e true if authentication was successful
*/
public void update(ObservableEvent<Boolean> e);
}
/**
* Get notified about a Word Deletion
*/
interface ObserverWordDeleted {
/**
* #param e the id of the word that was deleted
*/
public void update(ObservableEvent<Integer> e);
}
}
The Observable Interface now looks like this
interface Observable<T> {
void addObserver(T o);
void removeObserver(T o);
void removeAllObservers();
<K> void notifyObservers(Observers.ObservableEvent<K> e);
}
The problem is that when I implement this I get and would have to cast K to the appropriate type, not really what I want to do.
#Override
public <K> void notifyObservers(ObservableEvent<K> e) {
for(Observers.ObserverAuthenticationAttempt o : this.observers)
o.update(e);
}
What am I doing wrong?
update 2
Actually it works better with an Observable like this, but I still need to specify the correct EventType in two different places.
interface Observable<T,K> {
void addObserver(T o);
void removeObserver(T o);
void removeAllObservers();
void notifyObservers(Observers.ObservableEvent<K> e);
}
You do not need to parametrise the Observers, but you need to parametrize the events.
public interface Observer<T> {
void notify(T event);
}
An example event:
public class WordListUpateEvent {
private final int changedIndex;
public WordListUpateEvent(int changedIndex) {
this.changedIndex = changedIndex;
}
public int getChangedIndex() {
return changedIndex;
}
}
Then you can have different interface of it for example:
public interface WordListObserver extends Observer<WordListUpateEvent> {}
and its implementations
public class ConcreteWordListObserverA implements WordListObserver {
#Override
public void notify(WordListUpateEvent event) {
System.out.println("update item at index: " + event.getChangedIndex());
}
}
on the other hand you need your Observable interface, i have splitted it in two interface in order ti make the notifyObservers method not public to the observers (you will see it later):
public interface Observable<T> extends ObservableRegistration<T> {
void notifyObservers(T event);
}
public interface ObservableRegistration<T> {
void addObserver(Observer<T> o);
void removeObserver(Observer<T> o);
void removeAllObservers();
}
If you would have several observables in a subject, you can not implemnt the Observalbe interface direct to your subject, so you need a seperate implementation class:
public class ObservableImpl<T> implements Observable<T>{
private final List<Observer<T>> observers = new ArrayList<Observer<T>>();
#Override
public void addObserver(Observer<T> o) {
this.observers.add(o);
}
#Override
public void removeObserver(Observer<T> o) {
this.observers.remove(o);
}
#Override
public void removeAllObservers() {
this.observers.clear();
}
#Override
public void notifyObservers(T event) {
for(Observer<T> observer : observers) {
observer.notify(event);
}
}
}
Now you can use the implementation in your subject:
public class Subject {
private Observable<WordListUpateEvent> wordListObservable = new ObservableImpl<WordListUpateEvent>();
//private Subject<OtherEvent> otherObservable = new ObservableImpl<WordListUpateEvent>();
public ObservableRegistration<WordListUpateEvent> getWordListObservableRegistration() {
return this.wordListObservable;
}
// public ObservableRegistration<OtherEvent> getOtherRegistration() {
// return this.otherObservable;
// }
public void doSomething() {
this.wordListObservable.notifyObservers(new WordListUpateEvent(42));
}
}
And this is how you can connect the observer and the subject:
public class Start {
public static void main(String[] args) {
Subject subject = new Subject();
subject.getWordListObservableRegistration().addObserver(new ConcreteWordListObserverA());
subject.getWordListObservableRegistration().addObserver(new ConcreteWordListObserverA());
subject.doSomething();
}
}
I would create an Observer interface, containing a public void update(ObservableEvent oe) method, and an ObserverEvent interface. After that, you can create specific class for each of your events.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Observer.html
http://www.java2s.com/Code/Java/Design-Pattern/Observableandobserver.htm
The Java Observer's update method has the Object argument. You can pass any Object, thus you can create your own "UpdateMessage" Object that can contain the updated object and additional information about what happend (deleted, saved etc.).

Categories

Resources