Example usage for java.util Collections synchronizedList

List of usage examples for java.util Collections synchronizedList

Introduction

In this page you can find the example usage for java.util Collections synchronizedList.

Prototype

public static <T> List<T> synchronizedList(List<T> list) 

Source Link

Document

Returns a synchronized (thread-safe) list backed by the specified list.

Usage

From source file:com.gemini.provision.network.openstack.NetworkProviderOpenStackImpl.java

@Override
public List<ProvisioningProviderResponseType> bulkCreateNetwork(GeminiTenant tenant, GeminiEnvironment env,
        List<GeminiNetwork> networks) {
    List<ProvisioningProviderResponseType> retValues = Collections.synchronizedList(new ArrayList());
    //TODO: Only the first element is set ... NEED to research whether it is possible to get the current position from the stream
    networks.stream().forEach(n -> createNetwork(tenant, env, n));
    return retValues;
}

From source file:com.emc.ecs.sync.CasMigrationTest.java

protected String summarize(FPPool pool, List<String> clipIds) throws Exception {
    List<String> summaries = Collections.synchronizedList(new ArrayList<String>());

    ExecutorService service = Executors.newFixedThreadPool(CAS_THREADS);

    System.out.print("Summarizing clips");

    for (String clipId : clipIds) {
        service.submit(new ClipReader(pool, clipId, summaries));
    }/*  ww w .  j  a v  a 2 s  . c  o  m*/

    service.shutdown();
    service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES);
    service.shutdownNow();

    System.out.println();

    Collections.sort(summaries);
    StringBuilder out = new StringBuilder();
    for (String summary : summaries) {
        out.append(summary);
    }
    return out.toString();
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionCollectionList.java

/**
 * test unique action/*  ww w . j  a  v  a  2 s. c om*/
 */
@Test
public final void unique() {
    final List<ITerm> l_return = new ArrayList<>();

    new CUnique().execute(false, IContext.EMPTYPLAN,
            Stream.of(1, 1, 3, 4, 5, 5).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 1);
    Assert.assertEquals(l_return.get(0).<List<?>>raw().size(), 4);
    Assert.assertArrayEquals(l_return.get(0).<List<?>>raw().toArray(), Stream.of(1, 3, 4, 5).toArray());

    new CUnique().execute(true, null, Stream.of(1).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 2);
    Assert.assertEquals(l_return.get(1).<List<?>>raw().getClass(),
            Collections.synchronizedList(Collections.emptyList()).getClass());
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Starts controller with a special config file, and creates and starts all
 * components of PowerFolder./*from w ww  . ja  v  a2 s  .co m*/
 *
 * @param filename
 *            The filename to uses as config file (located in the
 *            "getConfigLocationBase()")
 */
public void startConfig(String filename) {
    if (started) {
        throw new IllegalStateException("Configuration already started, shutdown controller first");
    }

    additionalConnectionListeners = Collections.synchronizedList(new ArrayList<ConnectionListener>());
    started = false;
    shuttingDown = false;
    threadPool = new WrappedScheduledThreadPoolExecutor(Constants.CONTROLLER_THREADS_IN_THREADPOOL,
            new NamedThreadFactory("Controller-Thread-"));

    // Initialize resource bundle eager
    // check forced language file from commandline
    if (commandLine != null && commandLine.hasOption("f")) {
        String langfilename = commandLine.getOptionValue("f");
        try {
            ResourceBundle resourceBundle = new ForcedLanguageFileResourceBundle(langfilename);
            Translation.setResourceBundle(resourceBundle);
            logInfo("Loading language bundle from file " + langfilename);
        } catch (FileNotFoundException fnfe) {
            logSevere("forced language file (" + langfilename + ") not found: " + fnfe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        } catch (IOException ioe) {
            logSevere("forced language file io error: " + ioe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        }
    } else {
        Translation.resetResourceBundle();
    }
    Translation.getResourceBundle();

    // loadConfigFile
    if (!loadConfigFile(filename)) {
        return;
    }

    boolean isDefaultConfig = Constants.DEFAULT_CONFIG_FILE.startsWith(getConfigName());
    if (isDefaultConfig) {
        // To keep compatible with previous versions
        preferences = Preferences.userNodeForPackage(PowerFolder.class);
    } else {
        preferences = Preferences.userNodeForPackage(PowerFolder.class).node(getConfigName());

    }

    // initialize logger
    // Enabled verbose mode if in config.
    // This logs to file for analysis.
    verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
    initLogger();

    if (verbose) {
        ByteSerializer.BENCHMARK = true;
        scheduleAndRepeat(new Runnable() {
            @Override
            public void run() {
                ByteSerializer.printStats();
            }
        }, 600000L, 600000L);
        Profiling.setEnabled(false);
        Profiling.reset();
    }

    String arch = OSUtil.is64BitPlatform() ? "64bit" : "32bit";
    logFine("OS: " + System.getProperty("os.name") + " (" + arch + ')');
    logFine("Java: " + JavaVersion.systemVersion().toString() + " (" + System.getProperty("java.vendor") + ')');
    logFine("Current time: " + new Date());
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    long totalMemory = runtime.totalMemory();
    logFine("Max Memory: " + Format.formatBytesShort(maxMemory) + ", Total Memory: "
            + Format.formatBytesShort(totalMemory));
    if (!Desktop.isDesktopSupported() && isUIEnabled()) {
        logWarning("Desktop utility not supported");
    }

    // If we have a new config. clear the preferences.
    clearPreferencesOnConfigSwitch();

    // Load and set http proxy settings
    HTTPProxySettings.loadFromConfig(this);

    // #2179: Load from server. How to handle timeouts?
    // Command line option -c http://are.de
    ConfigurationLoader.loadAndMergeCLI(this);
    // Config entry in file
    ConfigurationLoader.loadAndMergeConfigURL(this);
    // Read from installer temp file
    ConfigurationLoader.loadAndMergeFromInstaller(this);

    if (verbose != ConfigurationEntry.VERBOSE.getValueBoolean(this)) {
        verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
        initLogger();
    }

    // Init paused only if user expects pause to be permanent or
    // "while I work"
    int pauseSecs = ConfigurationEntry.PAUSE_RESUME_SECONDS.getValueInt(getController());
    paused = PreferencesEntry.PAUSED.getValueBoolean(this)
            && (pauseSecs == Integer.MAX_VALUE || pauseSecs == 0);

    // Now set it, just in case it was paused in permanent mode.
    PreferencesEntry.PAUSED.setValue(this, paused);

    // Load and set http proxy settings again.
    HTTPProxySettings.loadFromConfig(this);

    // Initialize branding/preconfiguration of the client
    initDistribution();
    logFine("Build time: " + getBuildTime());
    logInfo("Program version " + PROGRAM_VERSION);

    if (getDistribution().getBinaryName().toLowerCase().contains("powerfolder")) {
        Debug.writeSystemProperties();
    }

    if (ConfigurationEntry.KILL_RUNNING_INSTANCE.getValueBoolean(this)) {
        killRunningInstance();
    }
    FolderList.removeMemberFiles(this);

    // Initialize plugins
    setupProPlugins();
    pluginManager = new PluginManager(this);
    pluginManager.init();

    // create node manager
    nodeManager = new NodeManager(this);

    // Only one task brother left...
    taskManager = new PersistentTaskManager(this);

    // Folder repository
    folderRepository = new FolderRepository(this);
    setLoadingCompletion(0, 10);

    // Create transfer manager
    // If this is a unit test it might have been set before.
    try {
        transferManager = transferManagerFactory.call();
    } catch (Exception e) {
        logSevere("Exception", e);
    }

    reconnectManager = new ReconnectManager(this);
    // Create os client
    osClient = new ServerClient(this);

    if (isUIEnabled()) {
        uiController = new UIController(this);
        if (ConfigurationEntry.USER_INTERFACE_LOCKED.getValueBoolean(this)) {
            // Don't let the user pass this step.
            new UIUnLockDialog(this).openAndWait();
        }
    }

    setLoadingCompletion(10, 20);

    // The io provider.
    ioProvider = new IOProvider(this);
    ioProvider.start();

    // Set hostname by CLI
    if (commandLine != null && commandLine.hasOption('d')) {
        String host = commandLine.getOptionValue("d");
        if (StringUtils.isNotBlank(host)) {
            InetSocketAddress addr = Util.parseConnectionString(host);
            if (addr != null) {
                ConfigurationEntry.HOSTNAME.setValue(this, addr.getHostName());
                ConfigurationEntry.NET_BIND_PORT.setValue(this, addr.getPort());
            }
        }
    }

    // initialize dyndns manager
    dyndnsManager = new DynDnsManager(this);

    setLoadingCompletion(20, 30);

    // initialize listener on local port
    if (!initializeListenerOnLocalPort()) {
        return;
    }
    if (!isUIEnabled()) {
        // Disable paused function
        paused = false;
    }

    setLoadingCompletion(30, 35);

    // Start the nodemanager
    nodeManager.init();
    if (!ProUtil.isRunningProVersion()) {
        // Nodemanager gets later (re) started by ProLoader.
        nodeManager.start();
    }

    setLoadingCompletion(35, 60);
    securityManager = new SecurityManagerClient(this, osClient);

    // init repo (read folders)
    folderRepository.init();
    logInfo("Dataitems: " + Debug.countDataitems(Controller.this));
    // init of folders takes rather long so a big difference with
    // last number to get smooth bar... ;-)
    setLoadingCompletion(60, 65);

    // start repo maintainance Thread
    folderRepository.start();
    setLoadingCompletion(65, 70);

    // Start the transfer manager thread
    transferManager.start();
    setLoadingCompletion(70, 75);

    // Initalize rcon manager
    startRConManager();

    setLoadingCompletion(75, 80);

    // Start all configured listener if not in paused mode
    startConfiguredListener();
    setLoadingCompletion(80, 85);

    // open broadcast listener
    openBroadcastManager();
    setLoadingCompletion(85, 90);

    // Controller now started
    started = true;
    startTime = new Date();

    // Now taskmanager
    taskManager.start();

    logInfo("Controller started");

    // dyndns updater
    /*
     * boolean onStartUpdate = ConfigurationEntry.DYNDNS_AUTO_UPDATE
     * .getValueBoolean(this).booleanValue(); if (onStartUpdate) {
     * getDynDnsManager().onStartUpdate(); }
     */
    dyndnsManager.updateIfNessesary();

    setLoadingCompletion(90, 100);

    // Login to OS
    if (Feature.OS_CLIENT.isEnabled()) {
        try {
            osClient.loginWithLastKnown();
        } catch (Exception e) {
            logWarning("Unable to login with last known username. " + e);
            logFiner(e);
        }
    }

    // Start Plugins
    pluginManager.start();

    // open UI
    if (isConsoleMode()) {
        logFine("Running in console");
    } else {
        logFine("Opening UI");
        openUI();
    }

    // Load anything that was not handled last time.
    loadPersistentObjects();

    setLoadingCompletion(100, 100);
    if (!isConsoleMode()) {
        uiController.hideSplash();
    }

    if (ConfigurationEntry.AUTO_CONNECT.getValueBoolean(this)) {
        // Now start the connecting process
        reconnectManager.start();
    } else {
        logFine("Not starting reconnection process. " + "Config auto.connect set to false");
    }
    // Start connecting to OS client.
    if (Feature.OS_CLIENT.isEnabled() && ConfigurationEntry.SERVER_CONNECT.getValueBoolean(this)) {
        osClient.start();
    } else {
        logInfo("Not connecting to server (" + osClient.getServerString() + "): Disabled");
    }

    // Setup our background working tasks
    setupPeriodicalTasks();

    if (MacUtils.isSupported()) {
        if (isFirstStart()) {
            MacUtils.getInstance().setPFStartup(true, this);
        }
        MacUtils.getInstance().setAppReOpenedListener(this);
    }

    if (pauseSecs == 0) {
        // Activate adaptive logic
        setPaused(paused);
    }
}

From source file:org.jpac.JPac.java

protected JPac() {
    super();//  w ww.ja va2 s. c  o  m
    setName(getClass().getSimpleName());

    tracePoint = 0;
    minRemainingCycleTime = Long.MAX_VALUE;
    maxRemainingCycleTime = 0;
    expectedCycleEndTime = 0;
    cycleStartTime = 0;
    //        nextCycleStartTime          = 0;
    status = Status.initializing;
    cycleNumber = 0;

    awaitedEventList = Collections.synchronizedSet(new HashSet<Fireable>());
    awaitedSimEventList = Collections.synchronizedSet(new HashSet<Fireable>());
    firedEventList = new HashSet<Fireable>();

    readyToShutdown = false;
    emergencyStopRequested = false;
    emergencyStopActive = false;
    emergencyStopIsToBeThrown = false;
    emergencyStopCausedBy = null;

    synchronizedTasks = Collections.synchronizedList(new ArrayList<Runnable>());
    cyclicTasks = Collections.synchronizedList(new ArrayList<CyclicTask>());

    startCycle = new Semaphore(1);
    cycleEnded = new Semaphore(1);

    startCycling = new Synchronisation();
    stopCycling = new Synchronisation();
    shutdownRequest = new Synchronisation();

    running = false;

    activeEventsLock = new CountingLock();
    awaitedEventOfLastModule = null;

    moduleList = new ArrayList<AbstractModule>(20);
    traceQueue = null;

    cycleHistogramm = null;
    systemHistogramm = null;
    modulesHistogramm = null;
    processedModule = null;

    exitCode = 0;

    incrementCounter = 0;
    decrementCounter = 0;

    try {
        propCycleTime = new LongProperty(this, "CycleTime", DEFAULTCYCLETIME, "[ns]", true);
        propCycleTimeoutTime = new LongProperty(this, "CycleTimeoutTime", DEFAULTCYCLETIMEOUTTIME, "[ns]",
                true);
        propCycleMode = new StringProperty(this, "CycleMode", CycleMode.FreeRunning.toString(),
                "[OneCycle | Bound | LazyBound | FreeRunning]", true);
        propRunningInsideAnIde = new BooleanProperty(this, "RunningInsideAnIde", false,
                "will pop up a small window to close the application", true);
        propRunningInjUnitTest = new BooleanProperty(this, "RunningInjUnitTest", false,
                "helpful, if jPac is run in a jUnit test", true);
        propEnableTrace = new BooleanProperty(this, "EnableTrace", false,
                "enables tracing of the module activity", true);
        propTraceTimeMinutes = new IntProperty(this, "TraceTimeMinutes", 0,
                "used to estimate the length of the trace buffer [min]", true);
        propPauseOnBreakPoint = new BooleanProperty(this, "pauseOnBreakPoint", false,
                "cycle is paused, until all modules enter waiting state", true);
        propRemoteSignalsEnabled = new BooleanProperty(this, "RemoteSignalsEnabled", false,
                "enable connections to/from remote JPac instances", true);
        propRemoteSignalPort = new IntProperty(this, "RemoteSignalPort", 10002,
                "server port for remote signal access", true);
        propStoreHistogrammsOnShutdown = new BooleanProperty(this, "storeHistogrammsOnShutdown", false,
                "enables storing of histogramm data on shutdown", true);
        propHistogrammFile = new StringProperty(this, "HistogrammFile", "./data/histogramm.csv",
                "file in which the histogramms are stored", true);
        propCyclicTaskShutdownTimeoutTime = new LongProperty(this, "CyclicTaskShutdownTimeoutTime",
                DEFAULTCYCLICTASKSHUTDOWNTIMEOUTTIME, "Timeout for all cyclic tasks to stop on shutdown [ns]",
                true);
        instanceIdentifier = InetAddress.getLocalHost().getHostName() + ":" + propRemoteSignalPort.get();
        cycleTime = propCycleTime.get();
        cycleTimeoutTime = propCycleTimeoutTime.get();
        cycleMode = CycleMode.valueOf(propCycleMode.get());
        runningInsideAnIde = propRunningInsideAnIde.get();
        runningInjUnitTest = propRunningInjUnitTest.get();
        enableTrace = propEnableTrace.get();
        traceTimeMinutes = propTraceTimeMinutes.get();
        pauseOnBreakPoint = propPauseOnBreakPoint.get();
        remoteSignalsEnabled = propRemoteSignalsEnabled.get();
        remoteSignalPort = propRemoteSignalPort.get();
        storeHistogrammsOnShutdown = propStoreHistogrammsOnShutdown.get();
        histogrammFile = propHistogrammFile.get();
        cyclicTaskShutdownTimeoutTime = propCyclicTaskShutdownTimeoutTime.get();
        //install configuration saver
        try {
            registerCyclicTask(Configuration.getInstance().getConfigurationSaver());
        } catch (WrongUseException exc) {
            /*cannot happen*/}
    } catch (UnknownHostException ex) {
        Log.error("Error: ", ex);
        //properties cannot be initialized
        //kill application
        System.exit(99);
    } catch (ConfigurationException ex) {
        Log.error("Error: ", ex);
        //properties cannot be initialized
        //kill application
        System.exit(99);
    }

    //install a shutdown hook to handle application shutdowns
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());
    setPriority(MAX_PRIORITY);
    //start instance of the automationController
    start();
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest3Test.java

/**
 * Tests the value of "this" in handler.
 * @throws Exception if the test fails// ww w .  j  a v a2 s  . c  o  m
 */
@Test
@Alerts("this == request")
public void thisValueInHandler() throws Exception {
    final String html = "<html>\n" + "  <head>\n" + "    <title>XMLHttpRequest Test</title>\n"
            + "    <script>\n" + "      var request;\n" + "      function testAsync() {\n"
            + "        request = " + XMLHttpRequest2Test.XHRInstantiation_ + ";\n"
            + "        request.onreadystatechange = onReadyStateChange;\n"
            + "        request.open('GET', 'foo.xml', true);\n" + "        request.send('');\n" + "      }\n"
            + "      function onReadyStateChange() {\n" + "        if (request.readyState == 4) {\n"
            + "          if (this == request)\n" + "            alert('this == request');\n"
            + "          else if (this == onReadyStateChange)\n" + "            alert('this == handler');\n"
            + "          else alert('not expected: ' + this)\n" + "        }\n" + "      }\n"
            + "    </script>\n" + "  </head>\n" + "  <body onload='testAsync()'>\n" + "  </body>\n" + "</html>";

    final WebClient client = getWebClient();
    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, html);
    conn.setDefaultResponse("");
    client.setWebConnection(conn);
    client.getPage(URL_FIRST);

    assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(1000));
    assertEquals(getExpectedAlerts(), collectedAlerts);
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionMathStatistics.java

/**
 * test exponential selection with lazy parameter
 *///w  ww . j a  va 2 s.  c o  m
@Test
public final void exponentialselectionlazy() {
    final List<ITerm> l_return = Collections.synchronizedList(new ArrayList<>());

    IntStream.range(0, 6500).parallel()
            .forEach(i -> new CExponentialSelection().execute(false, IContext.EMPTYPLAN,
                    Stream.of(Stream.of("a", "b").collect(Collectors.toList()),
                            Stream.of(4.5, 3.5).collect(Collectors.toList()), 0.5).map(CRawTerm::from)
                            .collect(Collectors.toList()),
                    l_return));

    Assert.assertEquals(
            (double) Collections.frequency(l_return.stream().map(ITerm::raw).collect(Collectors.toList()), "a")
                    / l_return.size(),
            0.73, 0.2);

    Assert.assertEquals(
            (double) Collections.frequency(l_return.stream().map(ITerm::raw).collect(Collectors.toList()), "b")
                    / l_return.size(),
            0.27, 0.2);
}

From source file:org.olat.commons.calendar.ICalFileCalendarManagerTest.java

/**
 * Test concurrent add event with two threads and code-point to control concurrency.
 *
 *//*from w w  w .j  av a  2 s .  c  o m*/
@Test
public void testConcurrentAddEvent() {
    final String TEST_EVENT_ID_1 = "id-testConcurrentAddEvent-1";
    final String TEST_EVENT_SUBJECT_1 = "testEvent1";
    final String TEST_EVENT_ID_2 = "id-testConcurrentAddEvent-2";
    final String TEST_EVENT_SUBJECT_2 = "testEvent2";

    final Identity test = JunitTestHelper.createAndPersistIdentityAsRndUser("ical-2-");
    final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>(1));
    final List<Boolean> statusList = Collections.synchronizedList(new ArrayList<Boolean>(1));

    final CountDownLatch doneSignal = new CountDownLatch(2);

    // thread 1
    Thread thread1 = new Thread() {
        public void run() {
            try {
                // 1. load calendar
                CalendarManager calManager = CalendarManagerFactory.getInstance().getCalendarManager();
                Kalendar cal = calManager.getPersonalCalendar(test).getKalendar();

                // 2. add Event1 => breakpoint hit               
                log.info("testConcurrentAddEvent thread1 addEvent1");
                calManager.addEventTo(cal,
                        new KalendarEvent(TEST_EVENT_ID_1, TEST_EVENT_SUBJECT_1, new Date(), 1));
                log.info("testConcurrentAddEvent thread1 addEvent1 DONE");
                // 3. check event1 exist
                cal = calManager.getPersonalCalendar(test).getKalendar();
                KalendarEvent event1 = cal.getEvent(TEST_EVENT_ID_1);
                assertNotNull("Did not found event with id=" + TEST_EVENT_ID_1, event1);
                assertEquals("Wrong calendar-event subject", event1.getSubject(), TEST_EVENT_SUBJECT_1);
                // 4. sleep 2sec

                // 5. check event1 still exist (event2 added in meantime)
                cal = calManager.getPersonalCalendar(test).getKalendar();
                event1 = cal.getEvent(TEST_EVENT_ID_1);
                assertNotNull("Did not found event with id=" + TEST_EVENT_ID_1, event1);
                assertEquals("Wrong calendar-event subject", event1.getSubject(), TEST_EVENT_SUBJECT_1);
                statusList.add(Boolean.TRUE);
                log.info("testConcurrentAddEvent thread1 finished");
            } catch (Exception ex) {
                exceptionHolder.add(ex);// no exception should happen
            } finally {
                doneSignal.countDown();
                DBFactory.getInstance().commitAndCloseSession();
            }
        }
    };

    // thread 2
    Thread thread2 = new Thread() {
        public void run() {
            try {
                // 1. load calendar
                CalendarManager calManager = CalendarManagerFactory.getInstance().getCalendarManager();
                Kalendar cal = calManager.getPersonalCalendar(test).getKalendar();

                // 3. add Event2 (breakpoint of thread1 blocks)
                log.info("testConcurrentAddEvent thread2 addEvent2");
                calManager.addEventTo(cal,
                        new KalendarEvent(TEST_EVENT_ID_2, TEST_EVENT_SUBJECT_2, new Date(), 1));
                log.info("testConcurrentAddEvent thread1 addEvent2 DONE");
                // 4. check event2 exist
                cal = calManager.getPersonalCalendar(test).getKalendar();
                KalendarEvent event2 = cal.getEvent(TEST_EVENT_ID_2);
                assertNotNull("Did not found event with id=" + TEST_EVENT_ID_2, event2);
                assertEquals("Wrong calendar-event subject", event2.getSubject(), TEST_EVENT_SUBJECT_2);
                // 5. check event1 exist
                cal = calManager.getPersonalCalendar(test).getKalendar();
                KalendarEvent event1 = cal.getEvent(TEST_EVENT_ID_1);
                assertNotNull("Did not found event with id=" + TEST_EVENT_ID_1, event1);
                assertEquals("Wrong calendar-event subject", event1.getSubject(), TEST_EVENT_SUBJECT_1);
                statusList.add(Boolean.TRUE);
                log.info("testConcurrentAddEvent thread2 finished");
            } catch (Exception ex) {
                exceptionHolder.add(ex);// no exception should happen
            } finally {
                doneSignal.countDown();
                DBFactory.getInstance().commitAndCloseSession();
            }
        }
    };

    thread1.start();
    thread2.start();

    try {
        boolean interrupt = doneSignal.await(10, TimeUnit.SECONDS);
        assertTrue("Test takes too long (more than 10s)", interrupt);
    } catch (InterruptedException e) {
        fail("" + e.getMessage());
    }

    // if not -> they are in deadlock and the db did not detect it
    for (Exception exception : exceptionHolder) {
        log.info("exception: " + exception.getMessage());
        exception.printStackTrace();
    }
    assertTrue("It throws an exception in test => see sysout", exceptionHolder.isEmpty());
    log.info("testConcurrentAddEvent finish successful");
}

From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java

@SuppressWarnings("unchecked")
public static List<List<File>> mainTest(String[] args, final List<Throwable> clientExceptions,
        final List<AccumulateRemoteStreamMonitor<?>> monitors) throws Exception {
    final String testFile = args[0];
    final boolean doAbort = ((args.length > 1) ? Boolean.parseBoolean(args[1]) : false);
    final boolean reverse = ((args.length > 2) ? Boolean.parseBoolean(args[2]) : false);
    final boolean doSkip = ((args.length > 3) ? Boolean.parseBoolean(args[3]) : false);
    final boolean doFastTests = ((args.length > 4) ? Boolean.parseBoolean(args[4]) : false);
    final List<List<File>> tempFiles = Arrays.asList(Collections.synchronizedList(new LinkedList<File>()),
            Collections.synchronizedList(new LinkedList<File>()));

    FileServer server = new FileServer(testFile, tempFiles, monitors);
    final RemoteFileServer stub = (RemoteFileServer) simulateRemote(
            UnicastRemoteObject.exportObject(server, 0));
    LOG.debug("Server ready");

    LOG.debug("Sleeping 3000 ms...");
    Thread.sleep(3000);//from  w  w w .  j  av  a 2s  .c o m

    LOG.debug("Running 'reliable' tests");
    Thread clientThread = new Thread(new Runnable() {
        public void run() {
            clientExceptions.addAll(FileClient.main(stub, testFile, tempFiles, doAbort, reverse, doSkip, false,
                    doFastTests, monitors));
        }
    });
    clientThread.start();
    clientThread.join();

    if (!doFastTests) {
        server.setUnreliable(true);

        LOG.debug("Running 'unreliable' tests");
        clientThread = new Thread(new Runnable() {
            public void run() {
                clientExceptions.addAll(FileClient.main(stub, testFile, tempFiles, doAbort, reverse, doSkip,
                        true, doFastTests, monitors));
            }
        });
        clientThread.start();
        clientThread.join();
    }

    LOG.debug("Unexporting server");
    UnicastRemoteObject.unexportObject(server, true);

    return tempFiles;
}

From source file:de.steilerdev.myVerein.server.model.User.java

/**
 * This function replaces the set of divisions by the stated divisions. The function guarantees that the inverse membership is handled correctly.
 * @param divisionRepository The division repository needed to save the altered divisions.
 * @param eventRepository The event repository needed to save the altered events.
 * @param divs The new list of divisions for the user.
 *//*  www . j a  v  a  2 s. c o m*/
public void replaceDivisions(DivisionRepository divisionRepository, EventRepository eventRepository,
        List<Division> divs) {
    logger.debug("[{}] Replacing division set", this);

    List<Division> finalDivisions = Division.getExpandedSetOfDivisions(divs, divisionRepository);
    List<Division> oldDivisions = divisions;

    if ((finalDivisions == null || finalDivisions.isEmpty())
            && (oldDivisions == null || oldDivisions.isEmpty())) {
        logger.debug("[{}] Division sets before and after are both empty", this);
        divisions = new ArrayList<>();
    } else if (finalDivisions == null || finalDivisions.isEmpty()) {
        logger.debug(
                "[{}] Division set after is empty, before is not. Removing membership subscription from old divisions",
                this);
        oldDivisions.stream().forEach(div -> div.removeMember(this));
        divisionRepository.save(oldDivisions);

        //Updating events, affected by division change
        oldDivisions.parallelStream().forEach(div -> {
            List<Event> changedEvents = eventRepository.findAllByInvitedDivision(div);
            changedEvents.parallelStream().forEach(event -> event.updateInvitedUser(divisionRepository));
            eventRepository.save(changedEvents);
        });
        divisions = new ArrayList<>();
    } else if (oldDivisions == null || oldDivisions.isEmpty()) {
        logger.debug(
                "[{}] Division set before is empty, after is not. Adding membership subscription to new divisions",
                this);
        finalDivisions.stream().forEach(div -> div.addMember(this));
        divisionRepository.save(finalDivisions);

        //Updating events, affected by division change
        finalDivisions.stream().forEach(div -> {
            List<Event> changedEvents = eventRepository.findAllByInvitedDivision(div);
            changedEvents.stream().forEach(event -> event.updateInvitedUser(divisionRepository));
            eventRepository.save(changedEvents);
        });
        divisions = finalDivisions;
    } else {
        logger.debug(
                "[{}] Division set after and before are not empty. Applying changed membership subscriptions",
                this);
        List<Division> intersect = finalDivisions.stream().filter(oldDivisions::contains)
                .collect(Collectors.toList()); //These items are already in the list, and do not need to be modified

        //Collecting changed division for batch save
        List<Division> changedDivisions = Collections.synchronizedList(new ArrayList<>());

        //Removing membership from removed divisions
        oldDivisions.parallelStream().filter(div -> !intersect.contains(div)).forEach(div -> {
            div.removeMember(this);
            changedDivisions.add(div);
        });

        //Adding membership to added divisions
        finalDivisions.parallelStream().filter(div -> !intersect.contains(div)).forEach(div -> {
            div.addMember(this);
            changedDivisions.add(div);
        });

        divisionRepository.save(changedDivisions);

        //Updating events, affected by division change
        changedDivisions.parallelStream().forEach(div -> {
            List<Event> changedEvents = eventRepository.findAllByInvitedDivision(div);
            changedEvents.parallelStream().forEach(event -> event.updateInvitedUser(divisionRepository));
            eventRepository.save(changedEvents);
        });
        divisions = finalDivisions;
    }
}