Example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean.

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:com.netflix.conductor.core.execution.TestWorkflowExecutor.java

@Test
public void test() throws Exception {

    AtomicBoolean httpTaskExecuted = new AtomicBoolean(false);
    AtomicBoolean http2TaskExecuted = new AtomicBoolean(false);

    new Wait();//from  w  ww  . j av a 2 s.c  om
    new WorkflowSystemTask("HTTP") {
        @Override
        public boolean isAsync() {
            return true;
        }

        @Override
        public void start(Workflow workflow, Task task, WorkflowExecutor executor) throws Exception {
            httpTaskExecuted.set(true);
            task.setStatus(Status.COMPLETED);
            super.start(workflow, task, executor);
        }

    };

    new WorkflowSystemTask("HTTP2") {

        @Override
        public void start(Workflow workflow, Task task, WorkflowExecutor executor) throws Exception {
            http2TaskExecuted.set(true);
            task.setStatus(Status.COMPLETED);
            super.start(workflow, task, executor);
        }

    };

    Workflow workflow = new Workflow();
    workflow.setWorkflowId("1");

    TestConfiguration config = new TestConfiguration();
    MetadataDAO metadata = mock(MetadataDAO.class);
    ExecutionDAO edao = mock(ExecutionDAO.class);
    QueueDAO queue = mock(QueueDAO.class);
    ObjectMapper om = new ObjectMapper();

    WorkflowExecutor executor = new WorkflowExecutor(metadata, edao, queue, om, config);
    List<Task> tasks = new LinkedList<>();

    WorkflowTask taskToSchedule = new WorkflowTask();
    taskToSchedule.setWorkflowTaskType(Type.USER_DEFINED);
    taskToSchedule.setType("HTTP");

    WorkflowTask taskToSchedule2 = new WorkflowTask();
    taskToSchedule2.setWorkflowTaskType(Type.USER_DEFINED);
    taskToSchedule2.setType("HTTP2");

    WorkflowTask wait = new WorkflowTask();
    wait.setWorkflowTaskType(Type.WAIT);
    wait.setType("WAIT");
    wait.setTaskReferenceName("wait");

    Task task1 = SystemTask.userDefined(workflow, IDGenerator.generate(), taskToSchedule, new HashMap<>(), null,
            0);
    Task task2 = SystemTask.waitTask(workflow, IDGenerator.generate(), taskToSchedule, new HashMap<>());
    Task task3 = SystemTask.userDefined(workflow, IDGenerator.generate(), taskToSchedule2, new HashMap<>(),
            null, 0);

    tasks.add(task1);
    tasks.add(task2);
    tasks.add(task3);

    when(edao.createTasks(tasks)).thenReturn(tasks);
    AtomicInteger startedTaskCount = new AtomicInteger(0);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            startedTaskCount.incrementAndGet();
            return null;
        }
    }).when(edao).updateTask(any());

    AtomicInteger queuedTaskCount = new AtomicInteger(0);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            String queueName = invocation.getArgumentAt(0, String.class);
            System.out.println(queueName);
            queuedTaskCount.incrementAndGet();
            return null;
        }
    }).when(queue).push(any(), any(), anyInt());

    boolean stateChanged = executor.scheduleTask(workflow, tasks);
    assertEquals(2, startedTaskCount.get());
    assertEquals(1, queuedTaskCount.get());
    assertTrue(stateChanged);
    assertFalse(httpTaskExecuted.get());
    assertTrue(http2TaskExecuted.get());
}

From source file:com.greplin.zookeeper.EmbeddedZookeeperServer.java

public EmbeddedZookeeperServer(Integer clientPort, File dataDir, Long tickTime)
        throws QuorumPeerConfig.ConfigException, IOException {
    Preconditions.checkNotNull(dataDir);
    Preconditions.checkNotNull(clientPort);
    Preconditions.checkNotNull(tickTime);

    Preconditions.checkArgument(clientPort > 0);
    Preconditions.checkArgument(clientPort < 65536);
    Preconditions.checkArgument(tickTime > 0);

    this.shutdown = new AtomicBoolean(false);
    this.clientPort = clientPort;
    this.dataDir = dataDir;
    this.tickTime = tickTime;

    Properties properties = new Properties();
    properties.setProperty("tickTime", tickTime.toString());
    properties.setProperty("clientPort", clientPort.toString());
    properties.setProperty("dataDir", dataDir.getAbsolutePath());

    QuorumPeerConfig qpc = new QuorumPeerConfig();
    try {// w  w  w  . ja  v a2s .  c om
        qpc.parseProperties(properties);
    } catch (IOException e) {
        throw new RuntimeException(
                "This is impossible - no I/O to configure a quorumpeer from a properties object", e);
    }

    // don't ask me why ...
    ServerConfig config = new ServerConfig();
    config.readFrom(qpc);

    log.info("Starting embedded zookeeper server on port " + clientPort);
    this.zooKeeperServer = new ZooKeeperServer();
    this.zooKeeperServer.setTxnLogFactory(
            new FileTxnSnapLog(new File(config.getDataLogDir()), new File(config.getDataDir())));
    this.zooKeeperServer.setTickTime(config.getTickTime());
    this.zooKeeperServer.setMinSessionTimeout(config.getMinSessionTimeout());
    this.zooKeeperServer.setMaxSessionTimeout(config.getMaxSessionTimeout());

    this.connectionFactory = new NIOServerCnxn.Factory(config.getClientPortAddress(),
            config.getMaxClientCnxns());
    try {
        connectionFactory.startup(zooKeeperServer);
    } catch (InterruptedException e) {
        throw new RuntimeException("Server Interrupted", e);
    }

    serverThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                connectionFactory.join();
            } catch (InterruptedException e) {
                log.error("Zookeeper Connection Factory Interrupted", e);
            }
        }
    });

    serverThread.start();
}

From source file:eu.stratosphere.nephele.io.channels.DistributedChannelWithAccessInfo.java

DistributedChannelWithAccessInfo(final FileSystem fs, final Path checkpointFile, final int bufferSize,
        final boolean deleteOnClose) throws IOException {

    this.fs = fs;
    this.checkpointFile = checkpointFile;
    this.channel = new FileChannelWrapper(fs, checkpointFile, bufferSize, (short) 2);
    this.reservedWritePosition = new AtomicLong(0L);
    this.referenceCounter = new AtomicInteger(0);
    this.deleteOnClose = new AtomicBoolean(deleteOnClose);
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.SystemMetricSet.java

public SystemMetricSet() {
    Map<String, Metric> metricsByNames = new HashMap<>();

    this.operatingSystemMetricSet = new OperatingSystemMetricSet();
    metricsByNames.put("os", operatingSystemMetricSet);

    this.jvmMetricSet = new JvmMetricSet();
    metricsByNames.put("jvm", jvmMetricSet);

    this.metricsByNames = metricsByNames;

    this.shutdown = new AtomicBoolean(false);
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from  w w w .j  a  v  a 2s .  c o m
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:com.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java

@Test
public void testBasicHystrixCommand() throws Exception {

    final AtomicBoolean done = new AtomicBoolean(false);
    final AtomicReference<String> result = new AtomicReference<>(null);

    // kick off async command
    Observable<String> observable = new TestCommand().observe();

    // Sleep to test what happens if command finishes before subscription
    Thread.sleep(2000);//from  w  ww.j a v  a 2s . c  o m

    // Add handler
    observable.subscribe(new Observer<String>() {
        @Override
        public void onCompleted() {
            done.set(true);
        }

        @Override
        public void onError(Throwable e) {
            result.set("error!!");
            done.set(true);
        }

        @Override
        public void onNext(String args) {
            result.set(args);
            done.set(true);
        }
    });

    // spin until done
    while (!done.get()) {
        Thread.sleep(100);
    }

    Assert.assertEquals(resultString, result.get());
}

From source file:actor4j.core.XActorThread.java

public XActorThread(ActorSystemImpl system) {
    super(system);

    directiveQueue = new MpscArrayQueue<>(system.getQueueSize());
    priorityQueue = new PriorityBlockingQueue<>(system.getQueueSize());
    serverQueueL2 = new MpscArrayQueue<>(system.getQueueSize());
    serverQueueL1 = new ArrayDeque<>(system.getBufferQueueSize());
    outerQueueL2B = new MpscLinkedQueue8<>();
    outerQueueL2A = new MpscArrayQueue<>(system.getQueueSize());
    outerQueueL1 = new ArrayDeque<>(system.getBufferQueueSize());
    innerQueueL2 = new LinkedList<>();
    innerQueueL1 = new CircularFifoQueue<>(system.getQueueSize());

    antiFloodingEnabled = new AtomicBoolean(false);

    newMessage = new AtomicBoolean(true);
}

From source file:org.apache.axis2.transport.http.server.HttpServiceProcessor.java

public HttpServiceProcessor(final AxisHttpService httpservice, final AxisHttpConnection conn,
        final IOProcessorCallback callback) {
    super();/*from www.  ja va  2  s  .c  om*/
    this.httpservice = httpservice;
    this.conn = conn;
    this.callback = callback;
    this.terminated = new AtomicBoolean(false);

    id = counter.incrementAndGet();
}

From source file:io.redlink.solrlib.standalone.SolrServerConnector.java

public SolrServerConnector(Set<SolrCoreDescriptor> coreDescriptors,
        SolrServerConnectorConfiguration configuration, ExecutorService executorService) {
    super(coreDescriptors, executorService);
    this.configuration = configuration;
    prefix = StringUtils.defaultString(configuration.getPrefix());
    solrBaseUrl = StringUtils.removeEnd(configuration.getSolrUrl(), "/");
    initialized = new AtomicBoolean(false);
}

From source file:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>//  w  w  w .  jav a  2  s.c  om
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}