Search in sources :

Example 41 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project jphp by jphp-compiler.

the class JavaReflection method exception.

public static void exception(Environment env, Throwable e) {
    if (cachedThClasses == null)
        cachedThClasses = new ConcurrentHashMap<Class<? extends Throwable>, Class<? extends JavaException>>();
    if (constructors == null)
        constructors = new ConcurrentHashMap<Class<? extends JavaException>, Constructor<? extends JavaException>>();
    Class tmp = e.getClass();
    Class<? extends JavaException> clazz = cachedThClasses.get(tmp);
    if (clazz == null) {
        while (tmp != null) {
            clazz = env.scope.findJavaException(tmp);
            if (clazz != null) {
                cachedThClasses.put(e.getClass(), clazz);
                break;
            }
            tmp = tmp.getSuperclass();
        }
    }
    if (clazz == null) {
        ClassEntity context = env.getLastClassOnStack();
        while (context != null) {
            clazz = env.scope.findJavaExceptionForContext(context.getLowerName());
            if (clazz != null)
                break;
            context = context.getParent();
        }
    }
    JavaException exception;
    if (clazz == null) {
        exception = new JavaException(env, e);
    } else {
        try {
            Constructor<? extends JavaException> constructor = constructors.get(clazz);
            if (constructor == null) {
                constructors.put(clazz, constructor = clazz.getConstructor(Environment.class, Throwable.class));
            }
            exception = constructor.newInstance(env, e);
        } catch (InvocationTargetException e1) {
            throw new CriticalException(e1.getCause());
        } catch (Exception e1) {
            throw new CriticalException(e1);
        }
    }
    env.__throwException(exception, false);
}
Also used : ClassEntity(php.runtime.reflection.ClassEntity) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CriticalException(php.runtime.exceptions.CriticalException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CriticalException(php.runtime.exceptions.CriticalException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 42 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project jersey by jersey.

the class ManagedAsyncResourceTest method testChatResource.

@Test
public void testChatResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path("chat");
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final boolean sequentialPost = false;
    final Object sequentialGetLock = new Object();
    final Object sequentialPostLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, Integer> postResponses = new ConcurrentHashMap<Integer, Integer>();
    final Map<Integer, Message> getResponses = new ConcurrentHashMap<Integer, Message>();
    final CountDownLatch postRequestLatch = new CountDownLatch(MAX_MESSAGES);
    final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
    try {
        for (int i = 0; i < MAX_MESSAGES; i++) {
            final int requestId = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialPost) {
                        synchronized (sequentialPostLock) {
                            post();
                        }
                    } else {
                        post();
                    }
                }

                private void post() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final Response response = resourceTarget.request().post(Entity.json(new Message("" + requestId, "" + requestId)));
                                postResponses.put(requestId, response.getStatus());
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.WARNING, String.format("Error POSTING message <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error POSTING message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        postRequestLatch.countDown();
                    }
                }
            });
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final Message response = resourceTarget.request("application/json").get(Message.class);
                                getResponses.put(requestId, response);
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        getRequestLatch.countDown();
                    }
                }
            });
        }
        if (debugMode) {
            postRequestLatch.await();
            getRequestLatch.await();
        } else {
            if (!postRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all POST requests to complete has timed out.");
            }
            if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
            }
        }
    } finally {
        executor.shutdownNow();
    }
    StringBuilder messageBuilder = new StringBuilder("POST responses received: ").append(postResponses.size()).append("\n");
    for (Map.Entry<Integer, Integer> postResponseEntry : postResponses.entrySet()) {
        messageBuilder.append("POST response for message ").append(postResponseEntry.getKey()).append(": ").append(postResponseEntry.getValue()).append('\n');
    }
    messageBuilder.append('\n');
    messageBuilder.append("GET responses received: ").append(getResponses.size()).append("\n");
    for (Map.Entry<Integer, Message> getResponseEntry : getResponses.entrySet()) {
        messageBuilder.append("GET response for message ").append(getResponseEntry.getKey()).append(": ").append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, Integer> postResponseEntry : postResponses.entrySet()) {
        assertEquals("Unexpected POST notification response for message " + postResponseEntry.getKey(), 200, postResponseEntry.getValue().intValue());
    }
    final List<Integer> lost = new LinkedList<Integer>();
    final Collection<Message> getResponseValues = getResponses.values();
    for (int i = 0; i < MAX_MESSAGES; i++) {
        if (!getResponseValues.contains(new Message("" + i, "" + i))) {
            lost.add(i);
        }
    }
    if (!lost.isEmpty()) {
        fail("Detected a posted message loss(es): " + lost.toString());
    }
    assertEquals(MAX_MESSAGES, postResponses.size());
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) Response(javax.ws.rs.core.Response) ExecutorService(java.util.concurrent.ExecutorService) WebTarget(javax.ws.rs.client.WebTarget) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 43 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project jersey by jersey.

the class ManagedAsyncResourceTest method testLongRunningResource.

@Test
public void testLongRunningResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path(App.ASYNC_LONG_RUNNING_MANAGED_OP_PATH);
    final String expectedResponse = SimpleJerseyExecutorManagedLongRunningResource.NOTIFICATION_RESPONSE;
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final Object sequentialGetLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
    final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
    try {
        for (int i = 0; i < MAX_MESSAGES; i++) {
            final int requestId = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final String response = resourceTarget.queryParam("id", requestId).request().get(String.class);
                                getResponses.put(requestId, response);
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        getRequestLatch.countDown();
                    }
                }
            });
        }
        if (debugMode) {
            getRequestLatch.await();
        } else {
            if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
            }
        }
    } finally {
        executor.shutdownNow();
    }
    StringBuilder messageBuilder = new StringBuilder("GET responses received: ").append(getResponses.size()).append("\n");
    for (Map.Entry<Integer, String> getResponseEntry : getResponses.entrySet()) {
        messageBuilder.append("GET response for message ").append(getResponseEntry.getKey()).append(": ").append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, String> entry : getResponses.entrySet()) {
        assertTrue("Unexpected GET notification response for message " + entry.getKey(), entry.getValue().contains(expectedResponse));
    }
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) WebTarget(javax.ws.rs.client.WebTarget) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 44 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project jersey by jersey.

the class AsyncResourceTest method testLongRunningResource.

@Test
public void testLongRunningResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path(App.ASYNC_LONG_RUNNING_OP_PATH);
    final String expectedResponse = SimpleLongRunningResource.NOTIFICATION_RESPONSE;
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 25 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final Object sequentialGetLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%02d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
    final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
    try {
        for (int i = 0; i < MAX_MESSAGES; i++) {
            final int requestId = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final String response = resourceTarget.request().get(String.class);
                                getResponses.put(requestId, response);
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        getRequestLatch.countDown();
                    }
                }
            });
        }
        if (debugMode) {
            getRequestLatch.await();
        } else {
            if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
            }
        }
    } finally {
        executor.shutdownNow();
    }
    final ArrayList<Map.Entry<Integer, String>> responseEntryList = new ArrayList<Map.Entry<Integer, String>>(getResponses.entrySet());
    Collections.sort(responseEntryList, new Comparator<Map.Entry<Integer, String>>() {

        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    StringBuilder messageBuilder = new StringBuilder("GET responses received: ").append(responseEntryList.size()).append("\n");
    for (Map.Entry<Integer, String> getResponseEntry : responseEntryList) {
        messageBuilder.append(String.format("GET response for message %02d: ", getResponseEntry.getKey())).append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, String> entry : responseEntryList) {
        assertEquals(String.format("Unexpected GET notification response for message %02d", entry.getKey()), expectedResponse, entry.getValue());
    }
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) WebTarget(javax.ws.rs.client.WebTarget) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 45 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project k-9 by k9mail.

the class Storage method doInTransaction.

void doInTransaction(Runnable dbWork) {
    ConcurrentMap<String, String> newStorage = new ConcurrentHashMap<String, String>();
    newStorage.putAll(storage);
    workingStorage.set(newStorage);
    SQLiteDatabase mDb = openDB();
    workingDB.set(mDb);
    List<String> changedKeys = new ArrayList<String>();
    workingChangedKeys.set(changedKeys);
    mDb.beginTransaction();
    try {
        dbWork.run();
        mDb.setTransactionSuccessful();
        storage = newStorage;
    } finally {
        workingDB.remove();
        workingStorage.remove();
        workingChangedKeys.remove();
        mDb.endTransaction();
        mDb.close();
    }
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) ArrayList(java.util.ArrayList) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)420 Map (java.util.Map)106 Test (org.junit.Test)102 HashMap (java.util.HashMap)75 ArrayList (java.util.ArrayList)73 CountDownLatch (java.util.concurrent.CountDownLatch)53 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)49 IOException (java.io.IOException)47 List (java.util.List)38 Set (java.util.Set)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)33 HashSet (java.util.HashSet)31 AtomicLong (java.util.concurrent.atomic.AtomicLong)29 ConcurrentMap (java.util.concurrent.ConcurrentMap)28 Random (java.util.Random)25 ExecutorService (java.util.concurrent.ExecutorService)23 Collection (java.util.Collection)20 UUID (java.util.UUID)20 Iterator (java.util.Iterator)19 Configuration (org.apache.hadoop.conf.Configuration)17