@Test
public void setProcessingState() throws PersistenceException, InterruptedException {

    // Add a message unit to the database so we can change it
    em.getTransaction().begin();
    UserMessage userMsgJPA = new UserMessage(TestData.userMsg1);
    em.persist(userMsgJPA);
    final UserMessageEntity userMsg = new UserMessageEntity(userMsgJPA);
    em.getTransaction().commit();
    // Check it accidentially has not already the new value
    assertNotEquals(T_NEW_PROC_STATE_1, userMsg.getCurrentProcessingState().getState());
    // Update to a new state
    ProcUpdater updater1 = new ProcUpdater(userMsg,
                                           userMsg.getCurrentProcessingState().getState(), T_NEW_PROC_STATE_1);
    new Thread(updater1).start();
    synchronized(updater1) { updater1.wait(); }
    // Check the new processing state is set
    assertTrue(updater1.s);
    assertEquals(T_NEW_PROC_STATE_1, userMsg.getCurrentProcessingState().getState());
    assertEquals(2, userMsg.getProcessingStates().size());
    // And check database
    em.refresh(userMsgJPA);
    assertEquals(T_NEW_PROC_STATE_1, userMsgJPA.getCurrentProcessingState().getState());
    assertEquals(2, userMsgJPA.getProcessingStates().size());
    // Test that update is rejected when not in correct state
    new Thread(updater1).start();
    synchronized(updater1) { updater1.wait(); }
    assertFalse(updater1.s);
    assertEquals(T_NEW_PROC_STATE_1, userMsg.getCurrentProcessingState().getState());
    assertEquals(2, userMsg.getProcessingStates().size());
    // And check database
    em.refresh(userMsgJPA);
    assertEquals(T_NEW_PROC_STATE_1, userMsgJPA.getCurrentProcessingState().getState());
    assertEquals(2, userMsgJPA.getProcessingStates().size());
    // Test parallel update (one should be rejected)
    updater1 = new ProcUpdater(userMsg, userMsg.getCurrentProcessingState().getState(), T_NEW_PROC_STATE_2);
    ProcUpdater updater2 = new ProcUpdater(userMsg,
                                           userMsg.getCurrentProcessingState().getState(), T_NEW_PROC_STATE_2);
    new Thread(updater1).start();
    new Thread(updater2).start();
    synchronized(updater1) { updater1.wait(); }
    if (updater2.s == null)
        synchronized(updater2) { updater2.wait(); }
    // One should have failed!
    assertFalse(updater1.s && updater2.s);
    // But stat should have changed
    assertEquals(T_NEW_PROC_STATE_2, userMsg.getCurrentProcessingState().getState());
    assertEquals(3, userMsg.getProcessingStates().size());
    // And check database
    em.refresh(userMsgJPA);
    assertEquals(T_NEW_PROC_STATE_2, userMsgJPA.getCurrentProcessingState().getState());
    assertEquals(3, userMsgJPA.getProcessingStates().size());
}