Example usage for java.util.concurrent PriorityBlockingQueue PriorityBlockingQueue

List of usage examples for java.util.concurrent PriorityBlockingQueue PriorityBlockingQueue

Introduction

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

Prototype

public PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) 

Source Link

Document

Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.

Usage

From source file:com.laurencedawson.image_management.ImageManager.java

/**
 * Initialize a newly created ImageManager
 * @param context The application ofinal r activity context
 * @param cacheSize The size of the LRU cache
 * @param threads The number of threads for the pools to use
 *///from  www. j a v  a  2s  .co m
public ImageManager(final Context context, final int cacheSize, final int threads) {

    // Instantiate the three queues. The task queue uses a custom comparator to 
    // change the ordering from FIFO (using the internal comparator) to respect
    // request priorities. If two requests have equal priorities, they are 
    // sorted according to creation date
    mTaskQueue = new PriorityBlockingQueue<Runnable>(QUEUE_SIZE, new ImageThreadComparator());
    mActiveTasks = new ConcurrentLinkedQueue<Runnable>();
    mBlockedTasks = new ConcurrentLinkedQueue<Runnable>();

    // The application context
    mContext = context;

    // Create a new threadpool using the taskQueue
    mThreadPool = new ThreadPoolExecutor(threads, threads, Long.MAX_VALUE, TimeUnit.SECONDS, mTaskQueue) {

        @Override
        protected void beforeExecute(final Thread thread, final Runnable run) {
            // Before executing a request, place the request on the active queue
            // This prevents new duplicate requests being placed in the active queue
            mActiveTasks.add(run);
            super.beforeExecute(thread, run);
        }

        @Override
        protected void afterExecute(final Runnable r, final Throwable t) {
            // After a request has finished executing, remove the request from
            // the active queue, this allows new duplicate requests to be submitted
            mActiveTasks.remove(r);

            // Perform a quick check to see if there are any remaining requests in
            // the blocked queue. Peek the head and check for duplicates in the 
            // active and task queues. If no duplicates exist, add the request to
            // the task queue. Repeat this until a duplicate is found
            synchronized (mBlockedTasks) {
                while (mBlockedTasks.peek() != null && !mTaskQueue.contains(mBlockedTasks.peek())
                        && !mActiveTasks.contains(mBlockedTasks.peek())) {
                    Runnable runnable = mBlockedTasks.poll();
                    if (runnable != null) {
                        mThreadPool.execute(runnable);
                    }
                }
            }
            super.afterExecute(r, t);
        }
    };

    // Calculate the cache size
    final int actualCacheSize = ((int) (Runtime.getRuntime().maxMemory() / 1024)) / cacheSize;

    // Create the LRU cache
    // http://developer.android.com/reference/android/util/LruCache.html

    // The items are no longer recycled as they leave the cache, turns out this wasn't the right
    // way to go about this and often resulted in recycled bitmaps being drawn
    // http://stackoverflow.com/questions/10743381/when-should-i-recycle-a-bitmap-using-lrucache
    mBitmapCache = new LruCache<String, Bitmap>(actualCacheSize) {
        protected int sizeOf(final String key, final Bitmap value) {
            return value.getByteCount() / 1024;
        }
    };
}

From source file:org.springframework.integration.file.FileReadingMessageSource.java

/**
 * Creates a FileReadingMessageSource with a {@link PriorityBlockingQueue}
 * ordered with the passed in {@link Comparator}
 * <p>/*from w  ww  . jav  a2  s  .c om*/
 * The size of the queue used should be large enough to hold all the files
 * in the input directory in order to sort all of them, so restricting the
 * size of the queue is mutually exclusive with ordering. No guarantees
 * about file delivery order can be made under concurrent access.
 * <p>
 *
 * @param receptionOrderComparator
 *            the comparator to be used to order the files in the internal
 *            queue
 */
public FileReadingMessageSource(Comparator<File> receptionOrderComparator) {
    this.toBeReceived = new PriorityBlockingQueue<File>(DEFAULT_INTERNAL_QUEUE_CAPACITY,
            receptionOrderComparator);
}

From source file:com.mobilyzer.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("MeasurementScheduler -> onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());

    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();

    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.mainQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.waitingTasksQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new WaitingTasksComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult[]>>();
    this.tasksStatus = new ConcurrentHashMap<String, MeasurementScheduler.TaskStatus>();
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    this.serverTasks = new HashMap<String, Date>();
    // this.currentSchedule = new HashMap<String, MeasurementTask>();

    this.idToClientKey = new ConcurrentHashMap<String, String>();

    messenger = new Messenger(new APIRequestHandler(this));

    gcmManager = new GCMManager(this.getApplicationContext());

    this.setCurrentTask(null);
    this.setCurrentTaskStartTime(null);

    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.batteryThreshold = -1;
    this.checkinIntervalSec = -1;
    this.dataUsageProfile = DataUsageProfile.NOTASSIGNED;

    //    loadSchedulerState();//TODO(ASHKAN)

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
    filter.addAction(UpdateIntent.GCM_MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.PLT_MEASUREMENT_ACTION);

    broadcastReceiver = new BroadcastReceiver() {

        @Override/*from w ww. j ava 2 s .  com*/
        public void onReceive(Context context, Intent intent) {
            Logger.d(intent.getAction() + " RECEIVED");
            if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)) {
                handleMeasurement();

            } else if (intent.getAction().equals(UpdateIntent.GCM_MEASUREMENT_ACTION)) {
                try {
                    JSONObject json = new JSONObject(
                            intent.getExtras().getString(UpdateIntent.MEASUREMENT_TASK_PAYLOAD));
                    Logger.d("MeasurementScheduler -> GCMManager: json task Value is " + json);
                    if (json != null && MeasurementTask.getMeasurementTypes().contains(json.get("type"))) {

                        try {
                            MeasurementTask task = MeasurementJsonConvertor.makeMeasurementTaskFromJson(json);
                            task.getDescription().priority = MeasurementTask.GCM_PRIORITY;
                            task.getDescription().startTime = new Date(System.currentTimeMillis() - 1000);
                            task.getDescription().endTime = new Date(System.currentTimeMillis() + (600 * 1000));
                            task.generateTaskID();
                            task.getDescription().key = Config.SERVER_TASK_CLIENT_KEY;
                            submitTask(task);
                        } catch (IllegalArgumentException e) {
                            Logger.w("MeasurementScheduler -> GCM : Could not create task from JSON: " + e);
                        }
                    }

                } catch (JSONException e) {
                    Logger.e(
                            "MeasurementSchedule -> GCMManager : Got exception during converting GCM json to MeasurementTask",
                            e);
                }

            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                String taskid = intent.getStringExtra(UpdateIntent.TASKID_PAYLOAD);
                String taskKey = intent.getStringExtra(UpdateIntent.CLIENTKEY_PAYLOAD);
                int priority = intent.getIntExtra(UpdateIntent.TASK_PRIORITY_PAYLOAD,
                        MeasurementTask.INVALID_PRIORITY);

                Logger.e(
                        intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD) + " " + taskid + " " + taskKey);
                if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_FINISHED)) {
                    tasksStatus.put(taskid, TaskStatus.FINISHED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);

                        for (Object obj : results) {
                            try {
                                MeasurementResult result = (MeasurementResult) obj;
                                /**
                                 * Nullify the additional parameters in MeasurmentDesc, or the results won't be
                                 * accepted by GAE server
                                 */
                                result.getMeasurementDesc().parameters = null;
                                String jsonResult = MeasurementJsonConvertor.encodeToJson(result).toString();
                                saveResultToFile(jsonResult);
                            } catch (JSONException e) {
                                Logger.e("Error converting results to json format", e);
                            }
                        }
                    }
                    handleMeasurement();
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_PAUSED)) {
                    tasksStatus.put(taskid, TaskStatus.PAUSED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STOPPED)) {
                    tasksStatus.put(taskid, TaskStatus.SCHEDULED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_CANCELED)) {
                    tasksStatus.put(taskid, TaskStatus.CANCELLED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);
                    }
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STARTED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_RESUMED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                }
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)) {
                Logger.d("Checkin intent received");
                handleCheckin();
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
}

From source file:uk.ac.bbsrc.tgac.miso.tools.run.FileQueueMessageSource.java

/**
 * Creates a FileReadingMessageSource with a {@link PriorityBlockingQueue}
 * ordered with the passed in {@link Comparator}
 * <p/>//from w  w  w.  j  a  v  a  2 s.  co  m
 * The size of the queue used should be large enough to hold all the files
 * in the input directory in order to sort all of them, so restricting the
 * size of the queue is mutually exclusive with ordering. No guarantees
 * about file delivery order can be made under concurrent access.
 * <p/>
 *
 * @param receptionOrderComparator the comparator to be used to order the files in the internal
 *                                 queue
 */
public FileQueueMessageSource(Comparator<File> receptionOrderComparator) {
    this.toBeReceived = new PriorityBlockingQueue<File>(DEFAULT_INTERNAL_QUEUE_CAPACITY,
            receptionOrderComparator);
}

From source file:uk.ac.bbsrc.tgac.miso.tools.run.MultiFileQueueMessageSource.java

/**
 * Creates a MultiFileQueueMessageSource with a {@link java.util.concurrent.PriorityBlockingQueue}
 * ordered with the passed in {@link java.util.Comparator}
 * <p/>/*from w w w.  j  a va 2s.co  m*/
 * The size of the queue used should be large enough to hold all the files
 * in the input directory in order to sort all of them, so restricting the
 * size of the queue is mutually exclusive with ordering. No guarantees
 * about file delivery order can be made under concurrent access.
 * <p/>
 *
 * @param receptionOrderComparator the comparator to be used to order the files in the internal
 *                                 queue
 */
public MultiFileQueueMessageSource(Comparator<File> receptionOrderComparator) {
    this.toBeReceived = new PriorityBlockingQueue<File>(DEFAULT_INTERNAL_QUEUE_CAPACITY,
            receptionOrderComparator);
}

From source file:com.mobiperf.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("Service onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());
    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();
    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.pauseRequested = true;
    this.stopRequested = false;
    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.taskQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult>>();

    // expect it to be the same size as the queue
    this.currentSchedule = new Hashtable<String, MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE);

    this.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    restoreState();// w  w w  .  ja va  2s .  c  o  m

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.PREFERENCE_ACTION);
    filter.addAction(UpdateIntent.MSG_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);

    broadcastReceiver = new BroadcastReceiver() {
        // Handles various broadcast intents.

        // If traffic is paused by RRCTrafficControl (because a RRC test is
        // running), we do not perform the checkin, since sending interfering
        // traffic makes the RRC inference task abort and restart the current
        // test as the traffic may have altered the phone's RRC state.
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UpdateIntent.PREFERENCE_ACTION)) {
                updateFromPreference();
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)
                            && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("Checkin intent received");
                handleCheckin(false);
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)
                    && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("MeasurementIntent intent received");
                handleMeasurement();
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                Logger.d("MeasurementIntent update intent received");
                if (intent.getIntExtra(UpdateIntent.PROGRESS_PAYLOAD,
                        Config.INVALID_PROGRESS) == Config.MEASUREMENT_END_PROGRESS) {
                    if (intent.getStringExtra(UpdateIntent.ERROR_STRING_PAYLOAD) != null) {
                        failedMeasurementCnt++;
                    } else {
                        // Process result
                        completedMeasurementCnt++;
                    }
                    if (intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD) != null) {
                        Logger.d("Measurement result intent received");
                        saveResultToFile(intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD));

                    }
                    updateResultsConsole(intent);
                }
            } else if (intent.getAction().equals(UpdateIntent.MSG_ACTION)) {
                String msg = intent.getExtras().getString(UpdateIntent.STRING_PAYLOAD);
                Date now = Calendar.getInstance().getTime();
                insertStringToConsole(systemConsole, now + "\n\n" + msg);
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
    // TODO(mdw): Make this a user-selectable option
    addIconToStatusBar();
}

From source file:org.apache.hadoop.hbase.replication.regionserver.ReplicationSource.java

/**
 * Instantiation method used by region servers
 *
 * @param conf configuration to use/*from  w w w .ja v a 2 s. c  om*/
 * @param fs file system to use
 * @param manager replication manager to ping to
 * @param stopper     the atomic boolean to use to stop the regionserver
 * @param peerClusterZnode the name of our znode
 * @throws IOException
 */
public void init(final Configuration conf, final FileSystem fs, final ReplicationSourceManager manager,
        final ReplicationQueues replicationQueues, final ReplicationPeers replicationPeers,
        final Stoppable stopper, final String peerClusterZnode, final UUID clusterId) throws IOException {
    this.stopper = stopper;
    this.conf = HBaseConfiguration.create(conf);
    decorateConf();
    this.replicationQueueSizeCapacity = this.conf.getLong("replication.source.size.capacity", 1024 * 1024 * 64);
    this.replicationQueueNbCapacity = this.conf.getInt("replication.source.nb.capacity", 25000);
    this.maxRetriesMultiplier = this.conf.getInt("replication.source.maxretriesmultiplier", 10);
    this.socketTimeoutMultiplier = this.conf.getInt("replication.source.socketTimeoutMultiplier",
            maxRetriesMultiplier * maxRetriesMultiplier);
    this.queue = new PriorityBlockingQueue<Path>(this.conf.getInt("hbase.regionserver.maxlogs", 32),
            new LogsComparator());
    // TODO: This connection is replication specific or we should make it particular to
    // replication and make replication specific settings such as compression or codec to use
    // passing Cells.
    this.conn = HConnectionManager.getConnection(this.conf);
    long bandwidth = this.conf.getLong("replication.source.per.peer.node.bandwidth", 0);
    this.throttler = new ReplicationThrottler((double) bandwidth / 10.0);
    this.replicationQueues = replicationQueues;
    this.replicationPeers = replicationPeers;
    this.manager = manager;
    this.sleepForRetries = this.conf.getLong("replication.source.sleepforretries", 1000);
    this.fs = fs;
    this.metrics = new MetricsSource(peerClusterZnode);
    this.repLogReader = new ReplicationHLogReaderManager(this.fs, this.conf);
    this.clusterId = clusterId;

    this.peerClusterZnode = peerClusterZnode;
    this.replicationQueueInfo = new ReplicationQueueInfo(peerClusterZnode);
    // ReplicationQueueInfo parses the peerId out of the znode for us
    this.peerId = this.replicationQueueInfo.getPeerId();
    this.replicationSinkMgr = new ReplicationSinkManager(conn, peerId, replicationPeers, this.conf);
    this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2);
}

From source file:org.apache.hadoop.hive.llap.daemon.impl.TaskExecutorService.java

public TaskExecutorService(int numExecutors, int waitQueueSize, String waitQueueComparatorClassName,
        boolean enablePreemption, ClassLoader classLoader, final LlapDaemonExecutorMetrics metrics,
        Clock clock) {/*from ww  w . j  a  va 2  s.  c o m*/
    super(TaskExecutorService.class.getSimpleName());
    LOG.info("TaskExecutorService is being setup with parameters: " + "numExecutors=" + numExecutors
            + ", waitQueueSize=" + waitQueueSize + ", waitQueueComparatorClassName="
            + waitQueueComparatorClassName + ", enablePreemption=" + enablePreemption);

    final Comparator<TaskWrapper> waitQueueComparator = createComparator(waitQueueComparatorClassName);
    this.maxParallelExecutors = numExecutors;
    this.waitQueue = new EvictingPriorityBlockingQueue<>(waitQueueComparator, waitQueueSize);
    this.clock = clock == null ? new MonotonicClock() : clock;
    this.threadPoolExecutor = new ThreadPoolExecutor(numExecutors, // core pool size
            numExecutors, // max pool size
            1, TimeUnit.MINUTES, new SynchronousQueue<Runnable>(), // direct hand-off
            new ExecutorThreadFactory(classLoader));
    this.executorService = MoreExecutors.listeningDecorator(threadPoolExecutor);
    this.preemptionQueue = new PriorityBlockingQueue<>(numExecutors, new PreemptionQueueComparator());
    this.enablePreemption = enablePreemption;
    this.numSlotsAvailable = new AtomicInteger(numExecutors);
    this.metrics = metrics;
    if (metrics != null) {
        metrics.setNumExecutorsAvailable(numSlotsAvailable.get());
    }

    // single threaded scheduler for tasks from wait queue to executor threads
    ExecutorService wes = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat(WAIT_QUEUE_SCHEDULER_THREAD_NAME_FORMAT).build());
    this.waitQueueExecutorService = MoreExecutors.listeningDecorator(wes);

    ExecutorService executionCompletionExecutorServiceRaw = Executors.newFixedThreadPool(1,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ExecutionCompletionThread #%d").build());
    executionCompletionExecutorService = MoreExecutors
            .listeningDecorator(executionCompletionExecutorServiceRaw);
    ListenableFuture<?> future = waitQueueExecutorService.submit(new WaitQueueWorker());
    Futures.addCallback(future, new WaitQueueWorkerCallback());
}

From source file:mazewar.Mazewar.java

/**
 * The place where all the pieces are put together.
 *//*  w  w w .j a v  a 2 s . com*/
public Mazewar(String zkServer, int zkPort, int port, String name, String game, boolean robot) {
    super("ECE419 Mazewar");
    consolePrintLn("ECE419 Mazewar started!");

    /* Set up parent */
    ZK_PARENT += game;

    // Throw up a dialog to get the GUIClient name.
    if (name != null) {
        clientId = name;
    } else {
        clientId = JOptionPane.showInputDialog("Enter your name");
    }
    if ((clientId == null) || (clientId.length() == 0)) {
        Mazewar.quit();
    }

    /* Connect to ZooKeeper and get sequencer details */
    List<ClientNode> nodeList = null;
    try {
        zkWatcher = new ZkWatcher();
        zkConnected = new CountDownLatch(1);
        zooKeeper = new ZooKeeper(zkServer + ":" + zkPort, ZK_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                /* Release Lock if ZooKeeper is connected */
                if (event.getState() == SyncConnected) {
                    zkConnected.countDown();
                } else {
                    System.err.println("Could not connect to ZooKeeper!");
                    System.exit(0);
                }
            }
        });
        zkConnected.await();

        /* Successfully connected, now create our node on ZooKeeper */
        zooKeeper.create(Joiner.on('/').join(ZK_PARENT, clientId),
                Joiner.on(':').join(InetAddress.getLocalHost().getHostAddress(), port).getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        /* Get Seed from Parent */
        mazeSeed = Long.parseLong(new String(zooKeeper.getData(ZK_PARENT, false, null)));

        /* Initialize Sequence Number */
        sequenceNumber = new AtomicInteger(zooKeeper.exists(ZK_PARENT, false).getVersion());

        /* Get list of nodes */
        nodeList = ClientNode.sortList(zooKeeper.getChildren(ZK_PARENT, false));
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // Create the maze
    maze = new MazeImpl(new Point(mazeWidth, mazeHeight), mazeSeed);
    assert (maze != null);

    // Have the ScoreTableModel listen to the maze to find
    // out how to adjust scores.
    ScoreTableModel scoreModel = new ScoreTableModel();
    assert (scoreModel != null);
    maze.addMazeListener(scoreModel);

    /* Initialize packet queue */
    packetQueue = new ArrayBlockingQueue<MazePacket>(QUEUE_SIZE);
    sequencedQueue = new PriorityBlockingQueue<MazePacket>(QUEUE_SIZE, new Comparator<MazePacket>() {
        @Override
        public int compare(MazePacket o1, MazePacket o2) {
            return o1.sequenceNumber.compareTo(o2.sequenceNumber);
        }
    });

    /* Inject Event Bus into Client */
    Client.setEventBus(eventBus);

    /* Initialize ZMQ Context */
    context = ZMQ.context(2);

    /* Set up publisher */
    publisher = context.socket(ZMQ.PUB);
    publisher.bind("tcp://*:" + port);
    System.out.println("ZeroMQ Publisher Bound On: " + port);

    try {
        Thread.sleep(100);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /* Set up subscriber */
    subscriber = context.socket(ZMQ.SUB);
    subscriber.subscribe(ArrayUtils.EMPTY_BYTE_ARRAY);

    clients = new ConcurrentHashMap<String, Client>();
    try {
        for (ClientNode client : nodeList) {
            if (client.getName().equals(clientId)) {
                clientPath = ZK_PARENT + "/" + client.getPath();
                guiClient = robot ? new RobotClient(clientId) : new GUIClient(clientId);
                clients.put(clientId, guiClient);
                maze.addClient(guiClient);
                eventBus.register(guiClient);
                subscriber.connect("tcp://" + new String(zooKeeper.getData(clientPath, false, null)));
            } else {
                addRemoteClient(client);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    checkNotNull(guiClient, "Should have received our clientId in CLIENTS list!");

    // Create the GUIClient and connect it to the KeyListener queue
    this.addKeyListener(guiClient);
    this.isRobot = robot;

    // Use braces to force constructors not to be called at the beginning of the
    // constructor.
    /*{
    maze.addClient(new RobotClient("Norby"));
    maze.addClient(new RobotClient("Robbie"));
    maze.addClient(new RobotClient("Clango"));
    maze.addClient(new RobotClient("Marvin"));
    }*/

    // Create the panel that will display the maze.
    overheadPanel = new OverheadMazePanel(maze, guiClient);
    assert (overheadPanel != null);
    maze.addMazeListener(overheadPanel);

    // Don't allow editing the console from the GUI
    console.setEditable(false);
    console.setFocusable(false);
    console.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder()));

    // Allow the console to scroll by putting it in a scrollpane
    JScrollPane consoleScrollPane = new JScrollPane(console);
    assert (consoleScrollPane != null);
    consoleScrollPane
            .setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Console"));

    // Create the score table
    scoreTable = new JTable(scoreModel);
    assert (scoreTable != null);
    scoreTable.setFocusable(false);
    scoreTable.setRowSelectionAllowed(false);

    // Allow the score table to scroll too.
    JScrollPane scoreScrollPane = new JScrollPane(scoreTable);
    assert (scoreScrollPane != null);
    scoreScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Scores"));

    // Create the layout manager
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    getContentPane().setLayout(layout);

    // Define the constraints on the components.
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 3.0;
    c.gridwidth = GridBagConstraints.REMAINDER;
    layout.setConstraints(overheadPanel, c);
    c.gridwidth = GridBagConstraints.RELATIVE;
    c.weightx = 2.0;
    c.weighty = 1.0;
    layout.setConstraints(consoleScrollPane, c);
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    layout.setConstraints(scoreScrollPane, c);

    // Add the components
    getContentPane().add(overheadPanel);
    getContentPane().add(consoleScrollPane);
    getContentPane().add(scoreScrollPane);

    // Pack everything neatly.
    pack();

    // Let the magic begin.
    setVisible(true);
    overheadPanel.repaint();
    this.requestFocusInWindow();
}

From source file:com.ngdata.sep.impl.fork.ForkedReplicationSource.java

/**
 * Instantiation method used by region servers
 *
 * @param conf configuration to use//from   w  w w .ja v a  2s. c om
 * @param fs file system to use
 * @param manager replication manager to ping to
 * @param stopper     the atomic boolean to use to stop the regionserver
 * @param replicating the atomic boolean that starts/stops replication
 * @param peerClusterZnode the name of our znode
 * @throws IOException
 */
public void init(final Configuration conf, final FileSystem fs, final ReplicationSourceManager manager,
        final Stoppable stopper, final AtomicBoolean replicating, final String peerClusterZnode)
        throws IOException {
    this.stopper = stopper;
    this.conf = conf;
    this.replicationQueueSizeCapacity = this.conf.getLong("replication.source.size.capacity", 1024 * 1024 * 64);
    this.replicationQueueNbCapacity = this.conf.getInt("replication.source.nb.capacity", 25000);
    this.entriesArray = new HLog.Entry[this.replicationQueueNbCapacity];
    for (int i = 0; i < this.replicationQueueNbCapacity; i++) {
        this.entriesArray[i] = new HLog.Entry();
    }
    this.maxRetriesMultiplier = this.conf.getInt("replication.source.maxretriesmultiplier", 10);
    this.socketTimeoutMultiplier = this.conf.getInt("replication.source.socketTimeoutMultiplier",
            maxRetriesMultiplier * maxRetriesMultiplier);
    this.queue = new PriorityBlockingQueue<Path>(conf.getInt("hbase.regionserver.maxlogs", 32),
            new LogsComparator());
    this.conn = HConnectionManager.getConnection(conf);
    this.zkHelper = manager.getRepZkWrapper();
    this.ratio = this.conf.getFloat("replication.source.ratio", 0.1f);
    this.currentPeers = new ArrayList<ServerName>();
    this.random = new Random();
    this.replicating = replicating;
    this.manager = manager;
    this.sleepForRetries = this.conf.getLong("replication.source.sleepforretries", 1000);
    this.fs = fs;
    this.metrics = new ReplicationSourceMetrics(peerClusterZnode);
    this.repLogReader = new ReplicationHLogReaderManager(this.fs, this.conf);
    try {
        this.clusterId = zkHelper.getUUIDForCluster(zkHelper.getZookeeperWatcher());
    } catch (KeeperException ke) {
        throw new IOException("Could not read cluster id", ke);
    }

    // Finally look if this is a recovered queue
    this.checkIfQueueRecovered(peerClusterZnode);

    registerPeerClusterListener();

    // SEP change: add an mbean to expose some replication info
    infoMBean = new ReplicationSourceInfo();
    registerMBean();
}