Java Examples for java.util.ConcurrentModificationException
The following java examples will help you to understand the usage of java.util.ConcurrentModificationException. These source code samples are taken from different open source projects.
Example 1
| Project: android-libcore64-master File: OldLinkedHashMapTest.java View source code |
public void testLinkedHashMap() {
// we want to test the LinkedHashMap in access ordering mode.
LinkedHashMap map = new LinkedHashMap<String, String>(10, 0.75f, true);
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator iterator = map.keySet().iterator();
String id = (String) iterator.next();
map.get(id);
try {
iterator.next();
// A LinkedHashMap is supposed to throw this Exception when a
// iterator.next() Operation takes place after a get
// Operation. This is because the get Operation is considered
// a structural modification if the LinkedHashMap is in
// access order mode.
fail("expected ConcurrentModificationException was not thrown.");
} catch (ConcurrentModificationException expected) {
}
LinkedHashMap mapClone = (LinkedHashMap) map.clone();
iterator = map.keySet().iterator();
id = (String) iterator.next();
mapClone.get(id);
iterator.next();
try {
new LinkedHashMap<String, String>(-10, 0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
try {
new LinkedHashMap<String, String>(10, -0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
}Example 2
| Project: android-sdk-sources-for-api-level-23-master File: ConcurrentModificationExceptionTest.java View source code |
/**
* java.util.ConcurrentModificationException#ConcurrentModificationException()
*/
public void test_Constructor() {
// Test for method java.util.ConcurrentModificationException()
Collection myCollection = new LinkedList();
Iterator myIterator = myCollection.iterator();
for (int counter = 0; counter < 50; counter++) myCollection.add(new Integer(counter));
CollectionModifier cm = new CollectionModifier(myCollection);
Thread collectionSlapper = new Thread(cm);
try {
collectionSlapper.start();
while (myIterator.hasNext()) myIterator.next();
} catch (ConcurrentModificationException e) {
cm.stopNow();
return;
}
cm.stopNow();
// The exception should have been thrown--if the code flow makes it here
// the test has failed
fail("Failed to throw expected ConcurrentModificationException");
}Example 3
| Project: android_libcore-master File: ConcurrentModificationExceptionTest.java View source code |
/**
* @tests java.util.ConcurrentModificationException#ConcurrentModificationException()
*/
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "ConcurrentModificationException", args = {})
public void test_Constructor() {
// Test for method java.util.ConcurrentModificationException()
Collection myCollection = new LinkedList();
Iterator myIterator = myCollection.iterator();
for (int counter = 0; counter < 50; counter++) myCollection.add(new Integer(counter));
CollectionModifier cm = new CollectionModifier(myCollection);
Thread collectionSlapper = new Thread(cm);
try {
collectionSlapper.start();
while (myIterator.hasNext()) myIterator.next();
} catch (ConcurrentModificationException e) {
cm.stopNow();
return;
}
cm.stopNow();
// The exception should have been thrown--if the code flow makes it here
// the test has failed
fail("Failed to throw expected ConcurrentModificationException");
}Example 4
| Project: android_platform_libcore-master File: OldLinkedHashMapTest.java View source code |
public void testLinkedHashMap() {
// we want to test the LinkedHashMap in access ordering mode.
LinkedHashMap map = new LinkedHashMap<String, String>(10, 0.75f, true);
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator iterator = map.keySet().iterator();
String id = (String) iterator.next();
map.get(id);
try {
iterator.next();
// A LinkedHashMap is supposed to throw this Exception when a
// iterator.next() Operation takes place after a get
// Operation. This is because the get Operation is considered
// a structural modification if the LinkedHashMap is in
// access order mode.
fail("expected ConcurrentModificationException was not thrown.");
} catch (ConcurrentModificationException expected) {
}
LinkedHashMap mapClone = (LinkedHashMap) map.clone();
iterator = map.keySet().iterator();
id = (String) iterator.next();
mapClone.get(id);
iterator.next();
try {
new LinkedHashMap<String, String>(-10, 0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
try {
new LinkedHashMap<String, String>(10, -0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
}Example 5
| Project: ARTPart-master File: OldLinkedHashMapTest.java View source code |
public void testLinkedHashMap() {
// we want to test the LinkedHashMap in access ordering mode.
LinkedHashMap map = new LinkedHashMap<String, String>(10, 0.75f, true);
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator iterator = map.keySet().iterator();
String id = (String) iterator.next();
map.get(id);
try {
iterator.next();
// A LinkedHashMap is supposed to throw this Exception when a
// iterator.next() Operation takes place after a get
// Operation. This is because the get Operation is considered
// a structural modification if the LinkedHashMap is in
// access order mode.
fail("expected ConcurrentModificationException was not thrown.");
} catch (ConcurrentModificationException expected) {
}
LinkedHashMap mapClone = (LinkedHashMap) map.clone();
iterator = map.keySet().iterator();
id = (String) iterator.next();
mapClone.get(id);
iterator.next();
try {
new LinkedHashMap<String, String>(-10, 0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
try {
new LinkedHashMap<String, String>(10, -0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
}Example 6
| Project: robovm-master File: OldLinkedHashMapTest.java View source code |
public void testLinkedHashMap() {
// we want to test the LinkedHashMap in access ordering mode.
LinkedHashMap map = new LinkedHashMap<String, String>(10, 0.75f, true);
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator iterator = map.keySet().iterator();
String id = (String) iterator.next();
map.get(id);
try {
iterator.next();
// A LinkedHashMap is supposed to throw this Exception when a
// iterator.next() Operation takes place after a get
// Operation. This is because the get Operation is considered
// a structural modification if the LinkedHashMap is in
// access order mode.
fail("expected ConcurrentModificationException was not thrown.");
} catch (ConcurrentModificationException expected) {
}
LinkedHashMap mapClone = (LinkedHashMap) map.clone();
iterator = map.keySet().iterator();
id = (String) iterator.next();
mapClone.get(id);
iterator.next();
try {
new LinkedHashMap<String, String>(-10, 0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
try {
new LinkedHashMap<String, String>(10, -0.75f, true);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException expected) {
}
}Example 7
| Project: ClayGen-master File: ClayUpdate.java View source code |
@SuppressWarnings("unchecked")
@Override
public synchronized void run() {
try {
if (plugin.doneblocks.size() > 0) {
LinkedList<Block> theblocks = (LinkedList<Block>) plugin.doneblocks.clone();
for (Block theblock : theblocks) {
theblock.setType(Material.CLAY);
plugin.doneblocks.remove(theblock);
}
}
} catch (ConcurrentModificationException e) {
System.out.println("[ClayGen] Uhoh, this should never happen, please tell Tux2 that you met with an concurrent modification exception!");
}
}Example 8
| Project: lombok-pg-master File: YieldInTryBlock.java View source code |
private boolean getNext() {
java.lang.Throwable $yieldException;
while (true) {
try {
switch($state) {
case 0:
;
$state = 1;
case 1:
;
b = true;
case 2:
;
$yieldException1 = null;
$state1 = 2;
$state = 3;
case 3:
;
if (b) {
throw new RuntimeException();
}
$next = "bar";
$state = 5;
return true;
case 4:
;
$next = "foo";
$state = 5;
return true;
case 5:
;
{
b = (!b);
}
if (($yieldException1 != null)) {
$yieldException = $yieldException1;
break;
}
$state = $state1;
continue;
case 6:
;
default:
;
return false;
}
} catch (final java.lang.Throwable $yieldExceptionCaught) {
$yieldException = $yieldExceptionCaught;
}
switch($state) {
case 3:
;
if (($yieldException instanceof RuntimeException)) {
e = (RuntimeException) $yieldException;
$state = 4;
continue;
}
case 4:
;
$yieldException1 = $yieldException;
$state = 5;
continue;
default:
;
$state = 6;
java.util.ConcurrentModificationException $yieldExceptionUnhandled = new java.util.ConcurrentModificationException();
$yieldExceptionUnhandled.initCause($yieldException);
throw $yieldExceptionUnhandled;
}
}
}Example 9
| Project: Consent2Share-master File: AuditServer.java View source code |
public void run() {
try {
logger.info("Listening on port " + port);
serverSocket = new ServerSocket(port);
serverSocketSucessfullyOpened = true;
while (!closed) {
logger.info("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
InetAddress inetAddress = socket.getInetAddress();
logger.info("Connected to client at " + inetAddress);
logger.info("Starting new socket node.");
SocketNode newSocketNode = new SocketNode(this, socket, auditEventHandler);
// java.util.ConcurrentModificationException
synchronized (socketNodeList) {
socketNodeList.add(newSocketNode);
}
new Thread(newSocketNode).start();
}
} catch (SocketException e) {
if ("socket closed".equals(e.getMessage())) {
logger.info("Audit server has been closed");
} else {
logger.info("Caught an SocketException", e);
}
} catch (IOException e) {
logger.info("Caught an IOException", e);
} catch (Exception e) {
logger.error("Caught an unexpectged exception.", e);
}
}Example 10
| Project: logback-audit-master File: AuditServer.java View source code |
public void run() {
try {
logger.info("Listening on port " + port);
serverSocket = new ServerSocket(port);
serverSocketSucessfullyOpened = true;
while (!closed) {
logger.info("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
InetAddress inetAddress = socket.getInetAddress();
logger.info("Connected to client at " + inetAddress);
logger.info("Starting new socket node.");
SocketNode newSocketNode = new SocketNode(this, socket, auditEventHandler);
// java.util.ConcurrentModificationException
synchronized (socketNodeList) {
socketNodeList.add(newSocketNode);
}
new Thread(newSocketNode).start();
}
} catch (SocketException e) {
if ("socket closed".equals(e.getMessage())) {
logger.info("Audit server has been closed");
} else {
logger.info("Caught an SocketException", e);
}
} catch (IOException e) {
logger.info("Caught an IOException", e);
} catch (Exception e) {
logger.error("Caught an unexpectged exception.", e);
}
}Example 11
| Project: com.revolsys.open-master File: BPlusTreeLeafIterator.java View source code |
@Override
protected T getNext() throws NoSuchElementException {
if (this.map.getModCount() == this.modCount) {
while (this.currentValues.isEmpty() || this.currentIndex >= this.currentValues.size()) {
if (this.nextPageId < 0) {
throw new NoSuchElementException();
} else {
this.nextPageId = this.map.getLeafValues(this.currentValues, this.nextPageId, this.key);
}
}
final T value = this.currentValues.get(this.currentIndex++);
return value;
} else {
throw new ConcurrentModificationException();
}
}Example 12
| Project: hibernate-orm-master File: HibernateAnnotationMappingTest.java View source code |
@Test
@TestForIssue(jiraKey = "HHH-7446")
public void testUniqueConstraintAnnotationOnNaturalIds() throws Exception {
Configuration configuration = new Configuration();
configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
configuration.addAnnotatedClass(Month.class);
SessionFactory sf = null;
try {
sf = configuration.buildSessionFactory();
sf.close();
} catch (ConcurrentModificationException e) {
fail(e.toString());
}
}Example 13
| Project: RadarApp-master File: RetrieveRoomDataService.java View source code |
@Override
protected void onHandleIntent(Intent intent) {
if (LocalDb.getInstance().getSelectedRoom() != null) {
try {
Room selectedRoom = LocalDb.getInstance().getSelectedRoom();
selectedRoom.fetch();
List<User> users = selectedRoom.getUsers();
for (User user : users) {
user.fetchIfNeeded();
UserDetail userDetail = user.getUserDetail();
userDetail.fetch();
}
Intent broadcastIntent = new Intent(BROADCAST_RESULT);
sendBroadcast(broadcastIntent);
} catch (ParseException e) {
Log.d(RetrieveRoomDataService.class.getSimpleName(), e.getMessage());
} catch (ConcurrentModificationException e) {
Log.d(RetrieveRoomDataService.class.getSimpleName(), "conccurency problem");
}
}
}Example 14
| Project: ServletStudyDemo-master File: ListDemo.java View source code |
public static void main(String[] args) {
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
//Iterator it=list.iterator();//´óСΪ4
//Ϊ±ÜÃâ²¢·¢ÐÞ¸ÄÒì³££¬ÎÒÃÇÕâÀïʹÓõü´úÆ÷µÄº¢×Ó£¬Ëü¾ßÓÐÔöɾ¸Ä²éµÄ¹¦ÄÜ£¬ÔÚµü´úÔªËØµÄͬʱ£¬Ôöɾ¸Ä²é²»»á³öÏÖ²¢·¢ÐÞ¸ÄÒì³£ÎÊÌâ
ListIterator it = list.listIterator();
while (it.hasNext()) {
String str = (String) it.next();
//list.add("eee");//java.util.ConcurrentModificationException¼¯ºÏµÄ²¢·¢ÐÞ¸ÄÒì³££¬ÎªÁ˱ÜÃâÕâÖÖÒì³££¬ÎÒÃÇ¿ÉÒÔµ÷Óõü´úÆ÷µÄ·½·¨Íê³ÉÌí¼ÓÔªËØµÄ²Ù×÷
//ʹÓÃ×Óµü´úÆ÷µÄ·½·¨Íê³ÉÔöɾ¸Ä²éÎÊÌ⣬ÕâÑùµü´úÆ÷»áÖªµÀÄãµÄÔöɾ¸Ä²é²Ù×÷£¬²»»áÔÙÅ׳ö²¢·¢ÐÞ¸ÄÒì³£
it.add("eee");
}
}Example 15
| Project: slide-master File: LastComments.java View source code |
public static void setCommentsSince(List<Submission> submissions) {
if (commentsSince == null) {
commentsSince = new HashMap<>();
}
KVManger m = KVStore.getInstance();
try {
for (Submission s : submissions) {
String fullname = s.getFullName();
if (!m.getByContains("comments" + fullname).isEmpty()) {
commentsSince.put(fullname, Integer.valueOf(m.get("comments" + fullname)));
}
}
} catch (ConcurrentModificationException ignored) {
}
}Example 16
| Project: valkyrie-master File: ResultsCollecter.java View source code |
/* * Attempt at an iterator that will not throw * ConcurrentModificationException when new results are appended to the * list. */ public Iterator<V> iterator() { return new Iterator<V>() { private int index = 0; private List<V> delegate; public Iterator<V> init(List<V> delegate) { this.delegate = delegate; return this; } public boolean hasNext() { return (index < delegate.size()); } public V next() { V next = null; try { next = delegate.get(index); } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(e.getMessage()); } finally { ++index; } return next; } public void remove() { } }.init(this.results); }
Example 17
| Project: zk-master File: ComodifiableIterator.java View source code |
public boolean hasNext() {
//while there is more
if (_nextAvail)
return true;
while (//isEmpty is reliable and empty is a common case
!_col.isEmpty()) {
final F o;
try {
o = _it.next();
} catch (java.util.NoSuchElementException ex) {
return false;
} catch (java.util.ConcurrentModificationException ex) {
_lastVisited = new LinkedList<F>(_visited);
_it = _col.iterator();
continue;
}
if (//not visited before
!removeFromLastVisited(o)) {
_visited.add(o);
_next = o;
return _nextAvail = true;
}
}
return false;
}Example 18
| Project: coding2017-master File: ArrayList.java View source code |
@Override
public Object next() {
//æ ‡è®°ç´¢å¼•å½“å‰?ä½?ç½®
int i = cursor;
if (i > size) {
throw new NoSuchElementException();
}
Object[] newData = elementData;
if (i > newData.length) {
throw new ConcurrentModificationException();
}
cursor = i + 1;
return newData[lastReset = i];
}Example 19
| Project: ceylon-ide-eclipse-master File: WarmupJob.java View source code |
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("Warming up completion processor", 100000);
Collection<Module> modules = CeylonBuilder.getProjectDeclaredSourceModules(project);
monitor.worked(10000);
try {
for (Module m : modules) {
List<Package> packages = m.getAllVisiblePackages();
for (Package p : packages) {
if (p.isShared()) {
for (Declaration d : p.getMembers()) {
if (d.isShared()) {
if (d instanceof TypedDeclaration) {
((TypedDeclaration) d).getType();
}
//this one really slows it down!
/*if (d instanceof Functional) {
((Functional) d).getParameterLists();
}*/
}
}
}
}
monitor.worked(90000 / max(modules.size(), 1));
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
}
} catch (ConcurrentModificationException cme) {
}
monitor.done();
return Status.OK_STATUS;
}Example 20
| Project: clinic-softacad-master File: HibernateAnnotationMappingTest.java View source code |
@Test
@TestForIssue(jiraKey = "HHH-7446")
public void testUniqueConstraintAnnotationOnNaturalIds() throws Exception {
Configuration configuration = new Configuration();
configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
configuration.addAnnotatedClass(Month.class);
SessionFactory sf = null;
try {
sf = configuration.buildSessionFactory();
sf.close();
} catch (ConcurrentModificationException e) {
fail(e.toString());
}
}Example 21
| Project: com.idega.core-master File: FacetsAndChildrenIterator.java View source code |
public UIComponent next() {
boolean facetsHasNext = false;
boolean childrenHasNext = false;
facetsHasNext = (this._facetsIterator != null && this._facetsIterator.hasNext());
childrenHasNext = (this._childrenIterator != null && this._childrenIterator.hasNext());
if (facetsHasNext) {
return this._facetsIterator.next();
} else if (childrenHasNext) {
try {
return this._childrenIterator.next();
} catch (NoSuchElementException nse) {
nse.printStackTrace();
return null;
} catch (ConcurrentModificationException cme) {
cme.printStackTrace();
return null;
}
} else {
throw new NoSuchElementException();
}
}Example 22
| Project: eclipselink.runtime-master File: IdentityWeakHashMapConcurrentModTest.java View source code |
public void test() {
try {
Iterator i = map.keySet().iterator();
int count = 0;
while (i.hasNext()) {
count++;
i.next();
map.get(10);
System.gc();
}
} catch (ConcurrentModificationException e) {
exception = e;
}
}Example 23
| Project: HBuilder-opensource-master File: PySetIterator.java View source code |
/**
* Returns the next item in the iteration.
*
* @return the next item in the iteration
* or null to signal the end of the iteration
*/
public PyObject __iternext__() {
if (this._iterator.hasNext()) {
this._count++;
try {
return Py.java2py(this._iterator.next());
} catch (ConcurrentModificationException e) {
throw Py.RuntimeError("dictionary changed size during iteration");
}
}
return null;
}Example 24
| Project: i2p.i2p-master File: CachedIteratorArrayList.java View source code |
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
CachedIteratorArrayList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}Example 25
| Project: JadexPlayer-master File: GraphLayoutTransition.java View source code |
// -------- LayoutTransition methods --------
public void step() {
Graph g = transitionLayout.getGraph();
try {
for (Iterator it = g.getVertices().iterator(); it.hasNext(); ) {
Object v = it.next();
Point2D tp = (Point2D) transitionLayout.transform(v);
Point2D fp = (Point2D) endLayout.transform(v);
double dx = (fp.getX() - tp.getX()) / (count - counter);
double dy = (fp.getY() - tp.getY()) / (count - counter);
transitionLayout.setLocation(v, new Point2D.Double(tp.getX() + dx, tp.getY() + dy));
}
} catch (ConcurrentModificationException e) {
counter = count;
}
counter++;
if (counter >= count) {
done = true;
vv.setGraphLayout(endLayout);
}
vv.repaint();
}Example 26
| Project: jdk7u-jdk-master File: ComodifiedRemove.java View source code |
public static void main(String[] args) {
List list = new LinkedList();
Object o1 = new Integer(1);
list.add(o1);
ListIterator e = list.listIterator();
e.next();
Object o2 = new Integer(2);
list.add(o2);
try {
e.remove();
} catch (ConcurrentModificationException cme) {
return;
}
throw new RuntimeException("LinkedList ListIterator.remove() comodification check failed.");
}Example 27
| Project: juzu-master File: RequestFilterTestCase.java View source code |
@Test
public void testFailing() throws Exception {
MockApplication<?> app = application("plugin.controller.requestfilter.failing").init();
MockClient client = app.client();
MockViewBridge render = null;
try {
render = client.render();
fail("Was expecting " + ConcurrentModificationException.class + " to be thrown");
} catch (ConcurrentModificationException expected) {
}
}Example 28
| Project: jythonroid-master File: PySetIterator.java View source code |
/**
* Returns the next item in the iteration.
*
* @return the next item in the iteration
* or null to signal the end of the iteration
*/
public PyObject __iternext__() {
if (this._iterator.hasNext()) {
this._count++;
try {
return Py.java2py(this._iterator.next());
} catch (ConcurrentModificationException e) {
throw Py.RuntimeError("dictionary changed size during iteration");
}
}
return null;
}Example 29
| Project: Lightweight-Stream-API-master File: IteratorIssueTest.java View source code |
@Test(expected = ConcurrentModificationException.class)
public void testArrayListIterator() {
final int count = 5;
final List<Integer> data = new ArrayList<Integer>();
for (int i = 0; i < count; i++) {
data.add(i);
}
Stream stream = Stream.of(data.iterator()).filter(Functions.remainder(2));
for (int i = 0; i < count; i++) {
data.add(count + i);
}
assertEquals(count, stream.count());
}Example 30
| Project: ManagedRuntimeInitiative-master File: ComodifiedRemove.java View source code |
public static void main(String[] args) {
List list = new LinkedList();
Object o1 = new Integer(1);
list.add(o1);
ListIterator e = list.listIterator();
e.next();
Object o2 = new Integer(2);
list.add(o2);
try {
e.remove();
} catch (ConcurrentModificationException cme) {
return;
}
throw new RuntimeException("LinkedList ListIterator.remove() comodification check failed.");
}Example 31
| Project: mishima-master File: TodoTagDeleteController.java View source code |
/* (é?ž Javadoc)
* @see jp.co.nemuzuka.core.controller.JsonController#execute()
*/
@Override
@TokenCheck
protected Object execute() throws Exception {
String key = asString("keyString");
Long version = asLong("version");
try {
//削除�る
todoTagService.delete(key, version, userService.getCurrentUser().getEmail());
} catch (ConcurrentModificationException e) {
logger.info(userService.getCurrentUser().getEmail() + e.getMessage());
}
JsonResult result = new JsonResult();
result.getInfoMsg().add(ApplicationMessage.get("info.success"));
return result;
}Example 32
| Project: myeslib-master File: HzUnitOfWorkJournal.java View source code |
/*
* (non-Javadoc)
* @see org.myeslib.core.storage.UnitOfWorkJournal#append(java.lang.Object, org.myeslib.core.data.UnitOfWork)
*/
public void append(final K id, final UnitOfWork uow) {
checkNotNull(id);
checkNotNull(uow);
final AggregateRootHistory history = getHistoryFor(id);
if (!history.getLastVersion().equals(uow.getTargetVersion())) {
throw new ConcurrentModificationException(String.format("version %s does not match the expected %s ****", history.getLastVersion().toString(), uow.getTargetVersion().toString()));
}
log.info("will set {}", id);
history.add(uow);
// hazelcast optimization --> set instead of put since is void
pastTransactionsMap.set(id, history);
}Example 33
| Project: openjdk-master File: ComodifiedRemove.java View source code |
public static void main(String[] args) {
List list = new LinkedList();
Object o1 = new Integer(1);
list.add(o1);
ListIterator e = list.listIterator();
e.next();
Object o2 = new Integer(2);
list.add(o2);
try {
e.remove();
} catch (ConcurrentModificationException cme) {
return;
}
throw new RuntimeException("LinkedList ListIterator.remove() comodification check failed.");
}Example 34
| Project: openjdk8-jdk-master File: ComodifiedRemove.java View source code |
public static void main(String[] args) {
List list = new LinkedList();
Object o1 = new Integer(1);
list.add(o1);
ListIterator e = list.listIterator();
e.next();
Object o2 = new Integer(2);
list.add(o2);
try {
e.remove();
} catch (ConcurrentModificationException cme) {
return;
}
throw new RuntimeException("LinkedList ListIterator.remove() comodification check failed.");
}Example 35
| Project: polly-master File: FixedSizeStack.java View source code |
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int i = sp;
private int modc = modcount;
@Override
public boolean hasNext() {
return this.i > 0;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (modc != modcount) {
throw new ConcurrentModificationException();
}
return stack[--i];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}Example 36
| Project: qcadoo-master File: FilterValueHolderImplTest.java View source code |
@Test
public final void shouldClearContentsWithoutException() {
// given
filterValueHolder.put("someBoolean", true);
filterValueHolder.put("someDecimal", BigDecimal.ONE);
filterValueHolder.put("someString", "stringValue");
// when & then
try {
// I know that this is ugly..
ReflectionTestUtils.invokeMethod(filterValueHolder, "clearHolder");
} catch (ConcurrentModificationException cme) {
Assert.fail();
}
}Example 37
| Project: RMaps-xavPatch-master File: MapTileMemCache.java View source code |
public void Free() {
try {
Iterator<Entry<String, Bitmap>> it = mHardCachedTiles.entrySet().iterator();
while (it.hasNext()) {
final Bitmap bmpHard = it.next().getValue();
if (bmpHard != null) {
if (!bmpHard.isRecycled()) {
bmpHard.recycle();
}
}
}
} catch (ConcurrentModificationException e) {
}
mHardCachedTiles.clear();
mSize = 0;
}Example 38
| Project: rocoto-master File: PropertiesIteratorTestCase.java View source code |
/**
* Test thread safety of properties iterator.
*
* @throws InterruptedException
*/
@Test
public void verifyThreadSafety() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
// Callable iterating over System.getProperties()
Future<Void> future = service.submit(new Callable<Void>() {
public Void call() throws Exception {
try {
while (true) {
Iterator<Entry<String, String>> it = newPropertiesIterator(System.getProperties());
while (it.hasNext()) {
it.next();
}
Thread.sleep(10L);
}
} catch (InterruptedException e) {
return null;
}
}
});
// Runnable updating System.getProperties()
service.execute(new Runnable() {
public void run() {
while (true) {
String key = "new key " + System.nanoTime();
System.getProperties().setProperty(key, "test");
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
return;
}
System.getProperties().remove(key);
}
}
});
// Process for 2 seconds
Thread.sleep(2000L);
service.shutdownNow();
try {
future.get();
} catch (ExecutionException e) {
assertFalse(e.getCause() instanceof ConcurrentModificationException);
}
}Example 39
| Project: scaleDOM-master File: ChildNodeList.java View source code |
@Override
public Node item(final int index) {
// Invalid indices must return null
if (index < 0 || index > getLength()) {
return null;
}
// Create new iterator starting on given index if this is the first call to #item() or index is unexpected
if (iterator == null || iterator.nextIndex() != index) {
iterator = children.listIterator(index);
}
try {
// Return next iterator element
return iterator.next();
} catch (final ConcurrentModificationException ex) {
iterator = children.listIterator(index);
return iterator.next();
}
}Example 40
| Project: Slim3CMS-master File: PageDAO.java View source code |
public PageEntity edit(PageEntity pageEntity) throws ConcurrentModificationException { Transaction tx = Datastore.beginTransaction(); try { Datastore.get(tx, PageEntity.class, pageEntity.getKey(), pageEntity.getVersion()); Datastore.put(tx, pageEntity); tx.commit(); } catch (ConcurrentModificationException e) { if (tx.isActive()) { tx.rollback(); } throw e; } return pageEntity; }
Example 41
| Project: TurtleKit-master File: TKDefaultViewer.java View source code |
@Override
protected void render(Graphics g) {
try {
int index = 0;
final Patch[] grid = getPatchGrid();
final int w = getWidth();
for (int j = getHeight() - 1; j >= 0; j--) {
for (int i = 0; i < w; i++) {
final Patch p = grid[index];
if (p.isEmpty()) {
paintPatch(g, p, i * cellSize, j * cellSize, index);
} else {
try {
for (final Turtle t : p.getTurtles()) {
if (t.isVisible()) {
paintTurtle(g, t, i * cellSize, j * cellSize);
break;
}
}
// paintTurtle(g, p.getTurtles().get(0), i * cellSize, j * cellSize);
} catch (NullPointerExceptionIndexOutOfBoundsException | //for the asynchronous mode
e) {
}
}
index++;
}
}
} catch (//FIXME
ConcurrentModificationException //FIXME
e) {
}
g.setColor(Color.RED);
g.drawLine(getWidth() * cellSize, getHeight() * cellSize, 0, getHeight() * cellSize);
g.drawLine(getWidth() * cellSize, getHeight() * cellSize, getWidth() * cellSize, 0);
}Example 42
| Project: vnet-sms-master File: DefaultMessageEvents.java View source code |
/**
* @see vnet.sms.gateway.nettytest.embedded.MessageEvents#allMessageEvents()
*/
@Override
public MessageEvent[] allMessageEvents() {
final int size = this.channelEvents.size();
final MessageEvent[] a = new MessageEvent[size];
for (int i = 0; i < size; i++) {
final MessageEvent product = nextMessageEvent();
if (product == null) {
throw new ConcurrentModificationException();
}
a[i] = product;
}
return a;
}Example 43
| Project: xcurator-master File: RemoveGroupingNodes.java View source code |
@Override
public void process(List<DataDocument> dataDocuments, Mapping mapping) {
System.out.println("process RemoveGroupingNodes...");
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>> Mapping");
System.out.println(mapping);
// for (String xmlTypeUri : mapping.getEntities().keySet()) {
//
// }
// TODO: we should remove blank nodes to create minimal isomorphic graph.
Iterator<Schema> it = mapping.getEntityIterator();
while (it.hasNext()) {
Schema entity = it.next();
if (entity.getAttributesCount() == 0) {
// this is equivalent to mapping.removeEntity(entity.getId()); we did that to prevent java.util.ConcurrentModificationException
it.remove();
}
}
// remove relations to the blank nodes that we just removed.
mapping.removeInvalidRelations();
}Example 44
| Project: android-1-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 45
| Project: easyrec-code-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 46
| Project: iNotes-exporter-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 47
| Project: inotes-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 48
| Project: mdrill-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 49
| Project: RPG-Items-2-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 50
| Project: solarnetwork-external-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 51
| Project: traffic-balance-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 52
| Project: trove4j-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 53
| Project: TroveP5-master File: THashPrimitiveIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 54
| Project: buck-master File: AppendableLogRecord.java View source code |
public void appendFormattedMessage(StringBuilder sb) {
try (Formatter f = new Formatter(sb, Locale.US)) {
f.format(getMessage(), getParameters());
} catch (IllegalFormatException e) {
sb.append("Invalid format string: ");
sb.append(displayLevel);
sb.append(" '");
sb.append(getMessage());
sb.append("' ");
Object[] params = getParameters();
if (params == null) {
params = new Object[0];
}
sb.append(Arrays.asList(params).toString());
} catch (ConcurrentModificationException originalException) {
throw new ConcurrentModificationException("Concurrent modification when logging for message " + getMessage(), originalException);
}
}Example 55
| Project: capedwarf-blue-master File: ClusteredTxTracker.java View source code |
public void track(Key currentRoot) {
final Transaction current = CapedwarfTransaction.currentTransaction();
final String key = mask(currentRoot);
final String currentId = current.getId();
final String previousId;
final javax.transaction.Transaction tx = CapedwarfTransaction.suspendTx();
try {
previousId = getUsedRoots().putIfAbsent(key, currentId);
} finally {
CapedwarfTransaction.resumeTx(tx);
}
if (previousId != null && previousId.equals(currentId) == false) {
throw new ConcurrentModificationException("Different transactions on same entity group: " + currentRoot);
}
}Example 56
| Project: chromattic-master File: FilterIteratorTestCase.java View source code |
public void testConcurrentModification1() {
LinkedList<Integer> tmp = new LinkedList<Integer>(integers);
Bilto iterator = new Bilto(tmp.iterator());
//
tmp.removeLast();
try {
iterator.hasNext();
fail();
} catch (ConcurrentModificationException e) {
}
try {
iterator.next();
fail();
} catch (ConcurrentModificationException e) {
}
try {
iterator.remove();
fail();
} catch (ConcurrentModificationException e) {
}
}Example 57
| Project: document-viewer-master File: LoadThumbnailTask.java View source code |
@Override
protected String doInBackground(final Feed... params) {
if (LengthUtils.isEmpty(params)) {
return null;
}
for (final Feed feed : params) {
if (feed == null) {
continue;
}
while (true) {
try {
for (final Book book : feed.books) {
if (stopped.get() || adapter.currentFeed != feed) {
return null;
}
loadBookThumbnail(book);
publishProgress(book);
}
break;
} catch (ConcurrentModificationException ex) {
if (stopped.get() || adapter.currentFeed != feed) {
return null;
}
}
}
}
return null;
}Example 58
| Project: EVCache-master File: EVCacheConnection.java View source code |
public void run() {
while (running) {
try {
handleIO();
} catch (IOException e) {
if (log.isDebugEnabled())
log.debug(e.getMessage(), e);
} catch (CancelledKeyException e) {
if (log.isDebugEnabled())
log.debug(e.getMessage(), e);
} catch (ClosedSelectorException e) {
if (log.isDebugEnabled())
log.debug(e.getMessage(), e);
} catch (IllegalStateException e) {
if (log.isDebugEnabled())
log.debug(e.getMessage(), e);
} catch (ConcurrentModificationException e) {
if (log.isDebugEnabled())
log.debug(e.getMessage(), e);
} catch (Throwable e) {
log.error("SEVERE EVCACHE ISSUE.", e);
}
}
if (log.isDebugEnabled())
log.debug(toString() + " : Shutdown");
}Example 59
| Project: fresco-master File: StatefulRunnableTest.java View source code |
@Before
public void setUp() throws Exception {
mResult = new Object();
mException = new ConcurrentModificationException();
mStatefulRunnable = mock(StatefulRunnable.class, CALLS_REAL_METHODS);
// setup state - no constructor has been run
Field mStateField = StatefulRunnable.class.getDeclaredField("mState");
mStateField.setAccessible(true);
mStateField.set(mStatefulRunnable, new AtomicInteger(StatefulRunnable.STATE_CREATED));
mStateField.setAccessible(false);
}Example 60
| Project: GeekBand-Android-1501-Homework-master File: StatefulRunnableTest.java View source code |
@Before
public void setUp() throws Exception {
mResult = new Object();
mException = new ConcurrentModificationException();
mStatefulRunnable = mock(StatefulRunnable.class, CALLS_REAL_METHODS);
// setup state - no constructor has been run
Field mStateField = StatefulRunnable.class.getDeclaredField("mState");
mStateField.setAccessible(true);
mStateField.set(mStatefulRunnable, new AtomicInteger(StatefulRunnable.STATE_CREATED));
mStateField.setAccessible(false);
}Example 61
| Project: glaze-http-master File: TestErrors.java View source code |
@Test
public void exception() {
try {
throw new ConcurrentModificationException();
} catch (ConcurrentModificationException e) {
try {
throw new ErrorResponseException(new UnsupportedOperationException(e));
} catch (ErrorResponseException ne) {
Assert.assertEquals(ne.getStatusCode(), -1);
}
}
}Example 62
| Project: gst-foundation-master File: LoadAndExport.java View source code |
public String execute(final ICS ics) {
final String name = "asset" + ics.genID(true);
try {
final AssetLoadById al = new AssetLoadById();
al.setName(name);
al.setAssetType(assetType);
al.setAssetId(assetId);
// al.setEditable(true);
al.setOption(AssetLoadById.OPTION_READ_ONLY_COMPLETE);
al.execute(ics);
new AssetScatter(name, "as", "PubList").execute(ics);
new AssetScatter(name, "as", true).execute(ics);
new AssetExport(name, "as", "xml").execute(ics);
final String xml = ics.GetVar("xml");
ics.RemoveVar("xml");
return xml;
} finally {
// cleaning up
// clear obj from ics
ics.SetObj(name, null);
final List<String> toClean = new ArrayList<String>();
for (final Enumeration<?> e = ics.GetVars(); e.hasMoreElements(); ) {
final String k = (String) e.nextElement();
if (k.startsWith("as:")) {
toClean.add(k);
}
}
// preventing java.util.ConcurrentModificationException
for (String n : toClean) {
ics.RemoveVar(n);
}
}
}Example 63
| Project: igv-master File: DefaultExceptionHandler.java View source code |
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof ConcurrentModificationException) {
// Ignore these, they are logged elsewhere
} else {
//JOptionPane.showMessageDialog(findActiveFrame(),
// "An unexpected error occured: " + e.toString(), "Exception Occurred", JOptionPane.OK_OPTION);
log.error("Unhandled exception", e);
}
}Example 64
| Project: JCommon-master File: ColtLongHashSet.java View source code |
@Override
public Long next() {
synchronized (ColtLongHashSet.this) {
if (versionSnapshot != version) {
throw new ConcurrentModificationException();
}
if (index >= mapKeyList.size()) {
throw new NoSuchElementException();
}
long value = mapKeyList.getQuick(index);
index++;
canRemove = true;
return value;
}
}Example 65
| Project: jeql-master File: DataPanel.java View source code |
public void update() {
if (model == null)
return;
List<MonitorItem> items = model.getItems();
try {
int i = 0;
for (MonitorItem item : items) {
if (i < tabPane.getTabCount()) {
RowListDataPanel rldp = (RowListDataPanel) tabPane.getComponentAt(i);
if (rldp.getMonitorItem() != item) {
insertItem(item, i);
} else {
rldp.update();
}
} else {
addItem(item);
}
i++;
}
} catch (ConcurrentModificationException e) {
}
}Example 66
| Project: mylyn.incubator-master File: InterestDebuggingDecorator.java View source code |
public void decorate(Object element, IDecoration decoration) {
AbstractContextStructureBridge bridge = null;
try {
if (ContextCorePlugin.getDefault() == null) {
return;
}
bridge = ContextCore.getStructureBridge(element);
} catch (ConcurrentModificationException cme) {
}
try {
IInteractionElement node = null;
if (element instanceof InteractionContextRelation) {
decoration.setForegroundColor(ColorMap.RELATIONSHIP);
} else if (element instanceof IInteractionElement) {
node = (IInteractionElement) element;
} else {
if (bridge != null && bridge.getContentType() != null) {
node = ContextCore.getContextManager().getElement(bridge.getHandleIdentifier(element));
}
}
if (node != null) {
decoration.addSuffix(" {" + node.getInterest().getValue() + " [" + node.getInterest().getEncodedValue() + "] " + "}");
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.WARNING, MylynDevPlugin.ID_PLUGIN, "Decoration failed", e));
}
}Example 67
| Project: nuxeo-tycho-osgi-master File: DirtyUpdateChecker.java View source code |
public static void check(DocumentModel doc) {
ThreadContext ctx = DirtyUpdateInvokeBridge.getThreadContext();
if (ctx == null) {
// invoked on server, no cache
return;
}
long modified;
try {
Property modifiedProp = doc.getProperty("dc:modified");
if (modifiedProp == null) {
return;
}
Date modifiedDate = modifiedProp.getValue(Date.class);
if (modifiedDate == null) {
return;
}
modified = modifiedDate.getTime();
} catch (Exception e) {
throw new ClientRuntimeException("cannot fetch dc modified for doc " + doc, e);
}
long tag = ctx.tag.longValue();
if (tag >= modified) {
// client cache is freshest than doc
return;
}
long invoked = ctx.invoked.longValue();
if (invoked <= modified) {
// modified by self user
return;
}
String message = String.format("%s is outdated : cache %s - op start %s - doc %s", doc.getId(), new Date(tag), new Date(invoked), new Date(modified));
throw new ConcurrentModificationException(message);
}Example 68
| Project: ocr-tools-master File: LockFileHandler.java View source code |
public void createOrOverwriteLock(boolean overwriteLock) {
// need to synchronize on static object because of the Web Service
synchronized (monitor) {
try {
if (overwriteLock) {
// the lock is deleted here, but a new one is created later
hotfolder.deleteIfExists(lockUri);
}
boolean lockExists = hotfolder.exists(lockUri);
if (lockExists) {
throw new ConcurrentModificationException("Another client instance is running! See the lock file at " + lockUri);
}
writeLockFile();
} catch (IOException e) {
logger.error("Error with server lock file: " + lockUri, e);
}
}
}Example 69
| Project: org.eclipse.ecr-master File: DirtyUpdateChecker.java View source code |
public static void check(DocumentModel doc) {
ThreadContext ctx = DirtyUpdateInvokeBridge.getThreadContext();
if (ctx == null) {
// invoked on server, no cache
return;
}
long modified;
try {
Property modifiedProp = doc.getProperty("dc:modified");
if (modifiedProp == null) {
return;
}
Date modifiedDate = modifiedProp.getValue(Date.class);
if (modifiedDate == null) {
return;
}
modified = modifiedDate.getTime();
} catch (Exception e) {
throw new ClientRuntimeException("cannot fetch dc modified for doc " + doc, e);
}
long tag = ctx.tag.longValue();
if (tag >= modified) {
// client cache is freshest than doc
return;
}
long invoked = ctx.invoked.longValue();
if (invoked <= modified) {
// modified by self user
return;
}
String message = String.format("%s is outdated : cache %s - op start %s - doc %s", doc.getId(), new Date(tag), new Date(invoked), new Date(modified));
throw new ConcurrentModificationException(message);
}Example 70
| Project: orientdb-master File: OObjectLazyListIterator.java View source code |
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
try {
list.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException(e);
}
if (sourceRecord != null) {
((OObjectProxyMethodHandler) sourceRecord.getHandler()).setDirty();
}
}Example 71
| Project: osgi-in-action-master File: Activator.java View source code |
public void start(BundleContext context) throws Exception {
File policyFile = getPolicyFile(context);
List<String> encodedInfos = readPolicyFile(policyFile);
encodedInfos.add(0, "ALLOW {" + "[org.osgi.service.condpermadmin.BundleLocationCondition \"" + context.getBundle().getLocation() + "\"]" + "(java.security.AllPermission \"*\" \"*\")" + "} \"Management Agent Policy\"");
ConditionalPermissionAdmin cpa = getConditionalPermissionAdmin(context);
ConditionalPermissionUpdate u = cpa.newConditionalPermissionUpdate();
List infos = u.getConditionalPermissionInfos();
infos.clear();
for (String encodedInfo : encodedInfos) {
infos.add(cpa.newConditionalPermissionInfo(encodedInfo));
}
if (!u.commit()) {
throw new ConcurrentModificationException("Permissions changed during update");
}
}Example 72
| Project: osgi-in-action-rosebud-master File: Activator.java View source code |
public void start(BundleContext context) throws Exception {
File policyFile = getPolicyFile(context);
List<String> encodedInfos = readPolicyFile(policyFile);
encodedInfos.add(0, "ALLOW {" + "[org.osgi.service.condpermadmin.BundleLocationCondition \"" + context.getBundle().getLocation() + "\"]" + "(java.security.AllPermission \"*\" \"*\")" + "} \"Management Agent Policy\"");
ConditionalPermissionAdmin cpa = getConditionalPermissionAdmin(context);
ConditionalPermissionUpdate u = cpa.newConditionalPermissionUpdate();
List infos = u.getConditionalPermissionInfos();
infos.clear();
for (String encodedInfo : encodedInfos) {
infos.add(cpa.newConditionalPermissionInfo(encodedInfo));
}
if (!u.commit()) {
throw new ConcurrentModificationException("Permissions changed during update");
}
}Example 73
| Project: platform_build-master File: AppendableLogRecord.java View source code |
public void appendFormattedMessage(StringBuilder sb) {
try (Formatter f = new Formatter(sb, Locale.US)) {
f.format(getMessage(), getParameters());
} catch (IllegalFormatException e) {
sb.append("Invalid format string: ");
sb.append(displayLevel);
sb.append(" '");
sb.append(getMessage());
sb.append("' ");
Object[] params = getParameters();
if (params == null) {
params = new Object[0];
}
sb.append(Arrays.asList(params).toString());
} catch (ConcurrentModificationException originalException) {
throw new ConcurrentModificationException("Concurrent modification when logging for message " + getMessage(), originalException);
}
}Example 74
| Project: RxDiffUtil-master File: RxDiffResultTest.java View source code |
@Test
public void applyDiff_concurrently() throws Exception {
rxDiffResult.applyDiff(action).subscribe(subscriber);
rxDiffResult.applyDiff(action).subscribe(subscriber);
emitResult(1);
verify(action).call(adapter, 1);
subscriber.assertError(ConcurrentModificationException.class);
subscriber.assertNotCompleted();
subscriber.assertNoValues();
}Example 75
| Project: snaptree-master File: ComodifiedRemove.java View source code |
public static void main(String[] args) {
List list = new LinkedList();
Object o1 = new Integer(1);
list.add(o1);
ListIterator e = list.listIterator();
e.next();
Object o2 = new Integer(2);
list.add(o2);
try {
e.remove();
} catch (ConcurrentModificationException cme) {
return;
}
throw new RuntimeException("LinkedList ListIterator.remove() comodification check failed.");
}Example 76
| Project: SPREAD-master File: AnalyzeTree.java View source code |
// END: Constructor
public void run() throws ConcurrentModificationException {
try {
// attributes parsed once per tree
double currentTreeNormalization = Utils.getTreeLength(currentTree, currentTree.getRootNode());
double[] precisionArray = Utils.getTreeDoubleArrayAttribute(currentTree, precisionString);
for (Node node : currentTree.getNodes()) {
if (!currentTree.isRoot(node)) {
// attributes parsed once per node
Node parentNode = currentTree.getParent(node);
double nodeHeight = Utils.getNodeHeight(currentTree, node);
double parentHeight = Utils.getNodeHeight(currentTree, parentNode);
double[] location = Utils.getDoubleArrayNodeAttribute(node, coordinatesName);
double[] parentLocation = Utils.getDoubleArrayNodeAttribute(parentNode, coordinatesName);
double rate = Utils.getDoubleNodeAttribute(node, rateString);
for (int i = 0; i < sliceHeights.length; i++) {
double sliceHeight = sliceHeights[i];
if (nodeHeight < sliceHeight && sliceHeight <= parentHeight) {
double[] imputedLocation = Utils.imputeValue(location, parentLocation, sliceHeight, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray);
// calculate key
int days = (int) (sliceHeight * DaysInYear * timescaler);
double sliceTime = mrsd.minus(days);
// grow map entry if key exists
if (slicesMap.containsKey(sliceTime)) {
slicesMap.get(sliceTime).add(// longitude
new Coordinates(imputedLocation[1], // latitude
imputedLocation[0], // altitude
0.0));
// start new entry if no such key in the map
} else {
List<Coordinates> coords = new ArrayList<Coordinates>();
coords.add(new // longitude
Coordinates(// longitude
imputedLocation[1], // latitude
imputedLocation[0], // altitude
0.0));
slicesMap.put(sliceTime, coords);
// END: key check
}
// END: sliceTime check
}
}
// END: numberOfIntervals loop
}
// END: root node check
}
// END: node loop
} catch (Exception e) {
e.printStackTrace();
}
// END: try-caych block
}Example 77
| Project: spyjar-master File: RingBufferTest.java View source code |
@SuppressWarnings("unchecked")
public void testIterator() {
int cap = 256;
ArrayList<Integer> a = new ArrayList<Integer>(cap * 2);
for (int i = 0; i < cap * 2; i++) {
a.add(i);
}
RingBuffer<Integer> rb = new RingBuffer<Integer>(cap, a);
Iterator itmp = rb.iterator();
rb.add(1);
try {
itmp.hasNext();
} catch (ConcurrentModificationException e) {
}
for (itmp = rb.iterator(); itmp.hasNext(); ) {
itmp.next();
try {
itmp.remove();
fail("RingBuffer iterator allowed me to remove an item");
} catch (UnsupportedOperationException e) {
}
}
try {
itmp.next();
fail("RingBuffer iterator allowed me to get more than it had");
} catch (NoSuchElementException e) {
}
}Example 78
| Project: test4XXX-master File: test4HashMap.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
MyClass myClass = new MyClass("123");
HashMap<Integer, SoftReference<MyClass>> map = new HashMap<>();
map.put(myClass.hashCode(), new SoftReference<>(myClass));
map.put(myClass.hashCode(), new SoftReference<>(myClass));
myClass = new MyClass("456");
map.put(myClass.hashCode(), new SoftReference<>(myClass));
System.out.println(map.size());
Iterator<Entry<Integer, SoftReference<MyClass>>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Integer, SoftReference<MyClass>> entry = iterator.next();
SoftReference<MyClass> val = entry.getValue();
MyClass item = val.get();
if (null != item) {
System.out.println(item.mString);
}
//
// map.remove(item.hashCode());
// Exception in thread "main" java.util.ConcurrentModificationException
// at java.util.HashMap$HashIterator.nextNode(Unknown Source)
// at java.util.HashMap$EntryIterator.next(Unknown Source)
// at java.util.HashMap$EntryIterator.next(Unknown Source)
// at test4HashMap.main(test4HashMap.java:30)
}
map.remove(myClass.hashCode());
// System.out.println(map.size());
listHashMap();
listHashMap1();
}Example 79
| Project: universal-java-matrix-package-master File: UpdateIconTimerTask.java View source code |
@Override
public void run() {
try {
for (MatrixGUIObject matrixGuiObject : list) {
if (!matrixGuiObject.isIconUpToDate()) {
matrixGuiObject.setIconUpToDate(true);
BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
MatrixHeatmapRenderer.paintMatrix(image.getGraphics(), matrixGuiObject, 16, 16, 0, 0);
matrixGuiObject.setIcon(image);
}
}
} catch (ConcurrentModificationException e) {
}
}Example 80
| Project: v7cr-master File: Versioning.java View source code |
/**
* updates an object, but only if the base version has not been changed in
* the meantime. The object must have an _id field. The _version field if
* present is ignored, and set to baseVersion+1.
*/
public static WriteResult update(DBCollection collection, final int baseVersion, DBObject object) {
object.put(VERSION, baseVersion + 1);
Object id = object.get("_id");
WriteResult result = collection.update(new BasicDBObject("_id", id).append(VERSION, baseVersion), object);
if (result.getN() != 1)
throw new ConcurrentModificationException("baseVersion has changed");
return result;
}Example 81
| Project: wildfly-core-master File: BasicResource.java View source code |
@SuppressWarnings({ "CloneDoesntCallSuperClone" })
@Override
public Resource clone() {
final BasicResource clone = new BasicResource(isRuntime(), getOrderedChildTypes());
for (; ; ) {
try {
clone.writeModel(model);
break;
} catch (ConcurrentModificationException ignore) {
}
}
cloneProviders(clone);
return clone;
}Example 82
| Project: wooki-master File: History.java View source code |
@OnEvent(value = "restore")
public void restorePublication(String revision) {
try {
chapterManager.restoreRevision(getChapterId(), revision);
message = messages.get("revision-restored");
} catch (ConcurrentModificationException cmEx) {
message = messages.get("revision-restore-error");
} catch (PublicationXmlException pxEx) {
message = messages.get("revision-restore-error");
}
}Example 83
| Project: XSched-master File: SimpleNodeManager.java View source code |
@Override
public Iterator<T> iterateNodes(final IntSet s) {
return new Iterator<T>() {
private final IntIterator it = s.intIterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public T next() {
int next = it.next();
return nodes.get(next);
}
@Override
public void remove() {
throw new ConcurrentModificationException();
}
};
}Example 84
| Project: yoursway-ide-master File: TestFastArrayList1.java View source code |
public void testIterateModify2() {
List list = makeEmptyList();
list.add("A");
list.add("B");
list.add("C");
assertEquals(3, list.size());
ListIterator it = list.listIterator();
assertEquals("A", it.next());
// change via Iterator interface
it.add("M");
assertEquals(4, list.size());
// change via List interface
list.add(2, "Z");
assertEquals(5, list.size());
assertEquals("B", it.next());
try {
// fails as previously changed via List interface
it.set("N");
fail();
} catch (ConcurrentModificationException ex) {
}
try {
it.remove();
fail();
} catch (ConcurrentModificationException ex) {
}
try {
it.add("N");
fail();
} catch (ConcurrentModificationException ex) {
}
assertEquals("C", it.next());
assertEquals(false, it.hasNext());
}Example 85
| Project: AdvancedRocketry-master File: CableTickHandler.java View source code |
@SubscribeEvent
public void chunkLoadedEvent(ChunkEvent.Load event) {
Map map = event.getChunk().chunkTileEntityMap;
Iterator<Entry> iter = map.entrySet().iterator();
try {
while (iter.hasNext()) {
Object obj = iter.next().getValue();
if (obj instanceof TilePipe) {
((TilePipe) obj).markForUpdate();
}
}
} catch (ConcurrentModificationException e) {
AdvancedRocketry.logger.warn("You have been visited by the rare pepe.. I mean error of pipes not loading, this is not good, some pipe systems may not work right away. But it's better than a corrupt world");
}
}Example 86
| Project: aether-core-master File: DefaultVersionFilterContext.java View source code |
public void remove() {
if (count != DefaultVersionFilterContext.this.count) {
throw new ConcurrentModificationException();
}
if (index < 0 || deleted[index] == 1) {
throw new IllegalStateException();
}
deleted[index] = 1;
count = --DefaultVersionFilterContext.this.count;
}Example 87
| Project: afc-master File: BroadFirstForestIterator.java View source code |
@Override
public TreeNode<D, ?> next() {
if (!this.isStarted) {
startIterator();
}
if (this.availableNodes.isEmpty()) {
throw new NoSuchElementException();
}
final TreeNode<D, ?> current = this.availableNodes.poll();
if (current == null) {
throw new ConcurrentModificationException();
}
// Add the children of the polled element
final int childCount = current.getChildCount();
for (int i = 0; i < childCount; ++i) {
try {
final TreeNode<D, ?> child = current.getChildAt(i);
if (child != null) {
this.availableNodes.offer(child);
}
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException(e);
}
}
return current;
}Example 88
| Project: alg-vis-master File: Screen.java View source code |
@Override
public void paintComponent(Graphics g) {
check_size();
clear();
if (D != null) {
V.startDrawing();
try {
panel.scene.move();
panel.scene.draw(V);
} catch (final ConcurrentModificationException ignored) {
}
V.endDrawing();
// V.resetView();
} else {
System.err.println("[DS null !]");
}
g.drawImage(I, 0, 0, null);
}Example 89
| Project: appengine-pipelines-master File: StringUtils.java View source code |
public static void logRetryMessage(Logger logger, Task task, int retryCount, Exception e) {
String message = "Will retry task: " + task + ". retryCount=" + retryCount;
if (e instanceof ConcurrentModificationException) {
// Don't print stack trace in this case.
logger.log(Level.INFO, message + " " + e.getMessage());
} else {
logger.log(Level.INFO, message, e);
}
}Example 90
| Project: apps2org-master File: TIterator.java View source code |
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
} finally {
_hash.reenableAutoCompaction(false);
}
_expectedSize--;
}Example 91
| Project: appsatori-pipes-master File: DatastoreHelper.java View source code |
static <V> V call(Operation<V> op, V defaultValue, TransactionOptions txops) {
int attempt = 1;
while (attempt <= RETRIES) {
String oldNs = NamespaceManager.get();
NamespaceManager.set(FLOW_NAMESPACE);
DatastoreServiceConfig config = DatastoreServiceConfig.Builder.withImplicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.AUTO).readPolicy(new ReadPolicy(ReadPolicy.Consistency.STRONG));
DatastoreService ds = DatastoreServiceFactory.getDatastoreService(config);
Transaction tx = ds.beginTransaction();
try {
V result = op.run(ds);
tx.commit();
return result;
} catch (ConcurrentModificationException e) {
attempt++;
} finally {
if (tx.isActive()) {
tx.rollback();
}
NamespaceManager.set(oldNs);
}
}
return defaultValue;
}Example 92
| Project: ares-studio-master File: ValidateJob.java View source code |
/* (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected IStatus run(IProgressMonitor monitor) {
// 2012-06-25 sundl Ìí¼ÓÒì³£ConcurrentModificationExceptionÌØÊâ´¦Àí£¬ÖØÐ½øÐдíÎó¼ì²é
monitor.beginTask("check", IProgressMonitor.UNKNOWN);
while (true) {
Object resource = context.get(IValidateConstant.KEY_RESOUCE);
if (resource != null && resource instanceof IARESResource) {
IARESResource aresResource = (IARESResource) resource;
if (ErrorCheckPreferenceHelper.getInstance().isErrorCheck(aresResource.getType())) {
try {
for (IValidateUnit unit : units) {
unit.updateProblemPool(problempool, context);
monitor.worked(1);
}
} catch (ConcurrentModificationException e) {
continue;
} catch (Exception e) {
e.printStackTrace();
return new Status(Status.ERROR, ARESEditorPlugin.PLUGIN_ID, "´íÎó¼ì²é·¢ÉúÒì³£", e);
} finally {
monitor.done();
}
}
}
return Status.OK_STATUS;
}
}Example 93
| Project: atlas-lb-master File: AbstractAtomHopperThread.java View source code |
@Override
public void run() {
Calendar startTime = AtomHopperUtil.getNow();
LOG.info(String.format("Load Balancer Atom Hopper USL Task Started at %s (Timezone: %s)", startTime.getTime().toString(), startTime.getTimeZone().getDisplayName()));
AHRecordHelper ahelper = null;
try {
String authToken = identityAuthClient.getAuthToken();
ahelper = new AHRecordHelper(configuration.getString(AtomHopperConfigurationKeys.ahusl_log_requests).equals("ENABLED"), client, loadBalancerEventRepository, alertRepository);
for (Usage usageRecord : usages) {
Map<Object, Object> entryMap = generateAtomHopperEntry(usageRecord);
failedRecords = ahelper.handleUsageRecord(usageRecord, authToken, entryMap);
}
LOG.info(String.format("Batch updating: %d " + "Atom Hopper usage entries in the database...", usages.size()));
updatePushedRecords(usages);
LOG.info(String.format("Successfully batch updated: %d " + "Atom Hopper entries in the database...", usages.size()));
} catch (ConcurrentModificationException cme) {
System.out.printf("Exception: %s\n", getExtendedStackTrace(cme));
LOG.warn(String.format("Warning: %s\n", getExtendedStackTrace(cme)));
LOG.warn(String.format("Job attempted to access usage already being processed, " + "continue processing next data set..."));
} catch (Throwable t) {
LOG.error(String.format("Exception during Atom-Hopper processing: %s\n", getExtendedStackTrace(t)));
ahelper.generateSevereAlert("Severe Failure processing Atom Hopper requests: ", getExtendedStackTrace(t));
}
Double elapsedMins = ((AtomHopperUtil.getNow().getTimeInMillis() - startTime.getTimeInMillis()) / 1000.0) / 60.0;
LOG.info(String.format("Load Balancer Atom Hopper USL Task: %s Completed at '%s' (Total Time: %f mins)", getThreadName(), AtomHopperUtil.getNow().getTime().toString(), elapsedMins));
LOG.debug(String.format("Load Balancer Atom Hopper USL Task: %s Failed tasks count: %d out of %d", getThreadName(), failedRecords.size(), usages.size()));
}Example 94
| Project: bigpetstore-master File: TestFileCreationEmpty.java View source code |
/** * This test creates three empty files and lets their leases expire. * This triggers release of the leases. * The empty files are supposed to be closed by that * without causing ConcurrentModificationException. */ public void testLeaseExpireEmptyFiles() throws Exception { final Thread.UncaughtExceptionHandler oldUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { if (e instanceof ConcurrentModificationException) { FSNamesystem.LOG.error("t=" + t, e); isConcurrentModificationException = true; } } }); System.out.println("testLeaseExpireEmptyFiles start"); final long leasePeriod = 1000; final int DATANODE_NUM = 3; final Configuration conf = new Configuration(); conf.setInt("heartbeat.recheck.interval", 1000); conf.setInt("dfs.heartbeat.interval", 1); // create cluster MiniDFSCluster cluster = new MiniDFSCluster(conf, DATANODE_NUM, true, null); try { cluster.waitActive(); DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem(); // create a new file. TestFileCreation.createFile(dfs, new Path("/foo"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo2"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo3"), DATANODE_NUM); // set the soft and hard limit to be 1 second so that the // namenode triggers lease recovery cluster.setLeasePeriod(leasePeriod, leasePeriod); // wait for the lease to expire try { Thread.sleep(5 * leasePeriod); } catch (InterruptedException e) { } assertFalse(isConcurrentModificationException); } finally { Thread.setDefaultUncaughtExceptionHandler(oldUEH); cluster.shutdown(); } }
Example 95
| Project: BigSack-master File: TailSetKVIterator.java View source code |
public Object next() {
synchronized (bTree) {
try {
// move nextelem to retelem, search nextelem, get nextelem
if (nextKey == null)
throw new NoSuchElementException("No next element in TailSetKVIterator");
retKey = nextKey;
retElem = nextElem;
if (!bTree.search(nextKey).atKey)
throw new ConcurrentModificationException("Next TailSetKVIterator element rendered invalid");
if (bTree.gotoNextKey() == 0) {
nextKey = bTree.getCurrentKey();
nextElem = bTree.getCurrentObject();
} else {
nextKey = null;
nextElem = null;
bTree.clearStack();
}
bTree.getIO().deallocOutstanding();
return new KeyValuePair(retKey, retElem);
} catch (IOException ioe) {
throw new RuntimeException(ioe.toString());
}
}
}Example 96
| Project: bug-osgi-master File: FastListIterator.java View source code |
/**
* Retrieve the next item in the list. The item will be a
* <code>TemplateModel</code> containing the underlying value.
*
* @return the next item in the list
* @throws TemplateModelException
* the next item couldn't be retrieved, or we're at the end of
* the list
*/
public TemplateModel next() throws TemplateModelException {
try {
return (TemplateModel) iterator.next();
} catch (NoSuchElementException e) {
throw new TemplateModelException("No more elements", e);
} catch (ClassCastException e) {
throw new TemplateModelException("Element is not a TemplateModel", e);
} catch (ConcurrentModificationException e) {
throw new TemplateModelException("List has been structurally modified", e);
}
}Example 97
| Project: cdh-mesos-master File: TestFileCreationEmpty.java View source code |
/** * This test creates three empty files and lets their leases expire. * This triggers release of the leases. * The empty files are supposed to be closed by that * without causing ConcurrentModificationException. */ public void testLeaseExpireEmptyFiles() throws Exception { final Thread.UncaughtExceptionHandler oldUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { if (e instanceof ConcurrentModificationException) { FSNamesystem.LOG.error("t=" + t, e); isConcurrentModificationException = true; } } }); System.out.println("testLeaseExpireEmptyFiles start"); final long leasePeriod = 1000; final int DATANODE_NUM = 3; final Configuration conf = new Configuration(); conf.setInt("heartbeat.recheck.interval", 1000); conf.setInt("dfs.heartbeat.interval", 1); // create cluster MiniDFSCluster cluster = new MiniDFSCluster(conf, DATANODE_NUM, true, null); try { cluster.waitActive(); DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem(); // create a new file. TestFileCreation.createFile(dfs, new Path("/foo"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo2"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo3"), DATANODE_NUM); // set the soft and hard limit to be 1 second so that the // namenode triggers lease recovery cluster.setLeasePeriod(leasePeriod, leasePeriod); // wait for the lease to expire try { Thread.sleep(5 * leasePeriod); } catch (InterruptedException e) { } assertFalse(isConcurrentModificationException); } finally { Thread.setDefaultUncaughtExceptionHandler(oldUEH); cluster.shutdown(); } }
Example 98
| Project: cdh3u3-with-mesos-master File: TestFileCreationEmpty.java View source code |
/** * This test creates three empty files and lets their leases expire. * This triggers release of the leases. * The empty files are supposed to be closed by that * without causing ConcurrentModificationException. */ public void testLeaseExpireEmptyFiles() throws Exception { final Thread.UncaughtExceptionHandler oldUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { if (e instanceof ConcurrentModificationException) { FSNamesystem.LOG.error("t=" + t, e); isConcurrentModificationException = true; } } }); System.out.println("testLeaseExpireEmptyFiles start"); final long leasePeriod = 1000; final int DATANODE_NUM = 3; final Configuration conf = new Configuration(); conf.setInt("heartbeat.recheck.interval", 1000); conf.setInt("dfs.heartbeat.interval", 1); // create cluster MiniDFSCluster cluster = new MiniDFSCluster(conf, DATANODE_NUM, true, null); try { cluster.waitActive(); DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem(); // create a new file. TestFileCreation.createFile(dfs, new Path("/foo"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo2"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo3"), DATANODE_NUM); // set the soft and hard limit to be 1 second so that the // namenode triggers lease recovery cluster.setLeasePeriod(leasePeriod, leasePeriod); // wait for the lease to expire try { Thread.sleep(5 * leasePeriod); } catch (InterruptedException e) { } assertFalse(isConcurrentModificationException); } finally { Thread.setDefaultUncaughtExceptionHandler(oldUEH); cluster.shutdown(); } }
Example 99
| Project: cdo-master File: Bugzilla_324635_Test.java View source code |
@Requires(IRepositoryConfig.CAPABILITY_BRANCHING)
public void testTargetGoalDeltaVersion() throws Exception {
skipStoreWithoutChangeSets();
// setup 2 transactions.
final CDOSession session1 = openSession();
final CDOTransaction s1Tr1 = session1.openTransaction();
s1Tr1.options().addChangeSubscriptionPolicy(CDOAdapterPolicy.ALL);
final CDOTransaction s1Tr2 = session1.openTransaction();
s1Tr2.options().addChangeSubscriptionPolicy(CDOAdapterPolicy.ALL);
// create resource, container and 2 elements using transaction 1.
final CDOResource resource = s1Tr1.createResource(getResourcePath("/test1"));
RefMultiContained container = getModel4Factory().createRefMultiContained();
resource.getContents().add(container);
MultiContainedElement element1 = getModel4Factory().createMultiContainedElement();
container.getElements().add(element1);
MultiContainedElement element2 = getModel4Factory().createMultiContainedElement();
container.getElements().add(element2);
commitAndSync(s1Tr1, s1Tr2);
// access container on transaction 2 to have it updated with a RevisionDelta.
RefMultiContained container2 = s1Tr2.getObject(container);
// setup another branch.
final CDOBranch otherBranch = s1Tr1.getBranch().createBranch("other");
final CDOTransaction s1Tr3 = session1.openTransaction(otherBranch);
RefMultiContained otherContainer = s1Tr3.getObject(container);
assertNotSame(null, otherContainer);
assertEquals(true, otherContainer.getElements().size() > 0);
// remove an element on the other branch.
otherContainer.getElements().remove(0);
commitAndSync(s1Tr3, s1Tr1);
// merge the other branch to main (this creates the targetGoalDelta for the RevisionDelta).
s1Tr1.merge(s1Tr3.getBranch().getHead(), new DefaultCDOMerger.PerFeature.ManyValued());
commitAndSync(s1Tr1, s1Tr2);
// check the change on tr2 and do another change.
assertEquals(false, s1Tr1.isDirty());
container2.getElements().remove(0);
// <--- this commit will throw the following exception:
commitAndSync(s1Tr2, s1Tr1);
// java.util.ConcurrentModificationException:
// Attempt by Transaction[2:2] to modify historical revision: RefMultiContained@OID4:0v1
assertEquals(false, s1Tr1.isDirty());
// check revision versions.
assertEquals(CDOUtil.getCDOObject(container).cdoRevision().getVersion(), CDOUtil.getCDOObject(container2).cdoRevision().getVersion());
}Example 100
| Project: circuitbreaker-master File: CircuitBreakerEventEmitterTest.java View source code |
@Test
public void testEmitter() throws IOException {
CircuitBreakerConfig config = CircuitBreakerConfig.custom().ringBufferSizeInClosedState(3).ringBufferSizeInHalfOpenState(2).failureRateThreshold(66).waitDurationInOpenState(Duration.ofSeconds(1)).recordFailure( e -> !(e instanceof IllegalArgumentException)).build();
CircuitBreaker circuitBreaker = CircuitBreakerRegistry.ofDefaults().circuitBreaker("test", config);
Runnable run = decorateRunnable(circuitBreaker, () -> System.out.println("."));
Runnable fail = decorateRunnable(circuitBreaker, () -> {
throw new ConcurrentModificationException();
});
Runnable ignore = decorateRunnable(circuitBreaker, () -> {
throw new IllegalArgumentException();
});
SseEmitter sseEmitter = createSseEmitter(circuitBreaker.getEventStream());
TestHandler handler = new TestHandler();
sseEmitter.initialize(handler);
exec(run, 2);
exec(ignore, 1);
exec(fail, 3);
sseEmitter.complete();
assert handler.isCompleted;
exec(run, 2);
List<CircuitBreakerEvent.Type> events = handler.events.stream().map(CircuitBreakerEventDTO::getType).collect(toList());
then(events).containsExactly(SUCCESS, SUCCESS, IGNORED_ERROR, ERROR, ERROR, STATE_TRANSITION, NOT_PERMITTED);
}Example 101
| Project: Cloud-Stenography-master File: SessionTracker.java View source code |
public synchronized EditSession openSession(File file, UserSession session, EditMode mode) {
if (getSession(file, session) != null)
throw new ConcurrentModificationException("Edit session already exists");
EditSession editSession = new EditSession(file, session, mode);
getLiveSessions(file).add(editSession);
getLiveSessions(session).add(editSession);
return editSession;
}