This method starts the bench progress with the registered classes.

@throws SocketViewException
if runs can not be communicated
@return if run succeeds or not
492073
public boolean runBenchmark() throws SocketViewException {
		final BenchmarkResult res = benchmark.run();
		new TabularSummaryOutput().visitBenchmark(res);
		view.finished();
		return true;
	}
1281748
public void runBenchmark() throws Exception {
        System.out.print(HORIZONTAL_RULE);
        System.out.println(" Setup & Initialization");
        System.out.println(HORIZONTAL_RULE);

        // connect to one or more servers, loop until success
        connect(config.servers);

        // initialize using synchronous call
        // Initialize the application
        System.out.println("\nPopulating Static Tables\n");
        final PreparedStatement initializeCS = client
                .prepareCall("{call Initialize(?,?)}");
        initializeCS.setInt(1, config.contestants);
        initializeCS.setString(2, CONTESTANT_NAMES_CSV);
        initializeCS.executeUpdate();

        System.out.print(HORIZONTAL_RULE);
        System.out.println(" Starting Benchmark");
        System.out.println(HORIZONTAL_RULE);

        // create/start the requested number of threads
        Thread[] voterThreads = new Thread[config.threads];
        for (int i = 0; i < config.threads; ++i) {
            voterThreads[i] = new Thread(new VoterThread());
            voterThreads[i].start();
        }

        // Run the benchmark loop for the requested warmup time
        System.out.println("Warming up...");
        Thread.sleep(1000l * config.warmup);

        // signal to threads to end the warmup phase
        warmupComplete.set(true);

        // reset the stats after warmup
        fullStatsContext.fetchAndResetBaseline();
        periodicStatsContext.fetchAndResetBaseline();

        // print periodic statistics to the console
        benchmarkStartTS = System.currentTimeMillis();
        schedulePeriodicStats();

        // Run the benchmark loop for the requested warmup time
        System.out.println("\nRunning benchmark...");
        Thread.sleep(1000l * config.duration);

        // stop the threads
        benchmarkComplete.set(true);

        // cancel periodic stats printing
        timer.cancel();

        // block until all outstanding txns return
        // client.drain();

        // join on the threads
        for (Thread t : voterThreads) {
            t.join();
        }

        // print the summary results
        printResults();

        // close down the client connections
        client.close();
    }
1022757
@Override
	public void run()
    {
    	try
    	{
    		while (!stopRequired)
    		{
	    		waitLock.acquire();
	    		if (stopRequired)
	    			break;
	    		
	    		// Implementation notes :
	    		//-----------------------
	    		//   As Socket TCP_NODELAY is set to minimize latency,
	    		//   socket buffers are sent ASAP in TCP packets.
	    		//   In order to fill more data in actual packets we try 
	    		//   to pipeline all immediately available messages 
	    		//   before asking to flush the buffers.

	    		// De-queue pending messages and move them to the pipeline
	    		synchronized (sendQueue)
                {
                    while (!sendQueue.isEmpty() && pipeline.size() < 16)
                    {
                        AbstractPacket packet = sendQueue.removeFirst();
                        pipeline.add(packet);
                    }
                }
	    			   
	    		if (pipeline.size() > 0)
	    		{	    		    
    	    		// Write all pipelined packets to the socket buffered output stream
	    			boolean updateLastTwoWayActivityTimestamp = false;
    	    		while (pipeline.size() > 0)
    	    		{
    	    		    AbstractPacket packet = pipeline.removeFirst();
    	    		    
    	    		    // We need to serialize the packet in a side buffer in order to 
    	    		    // know its final size before writing it to the actual output stream
    	                RawDataBuffer buffer = outChannel.ioBuffer;
    	                buffer.clear();
    	                PacketSerializer.serializeTo(packet, buffer);
    	                
    	                // Write it on the stream
    	                OutputStream out = outChannel.socketOutputStream;
    	                SerializationTools.writeInt(buffer.size(),out); // Packet size
    	                buffer.writeTo(out); // Packet body
    	                
    	                if (pingInterval > 0 && packet.isResponseExpected())
    	                	updateLastTwoWayActivityTimestamp = true;
    	    		}
    	    		
    	    		// Flush output stream
    	    		outChannel.flush();
    	    		
    	    		// Update last activity timestamp only if we expect a response
    	    		if (updateLastTwoWayActivityTimestamp)
    	    			lastActivity = System.currentTimeMillis();
	    		}
    		}
    	}
    	catch (Exception e)
        {
            if (!stopRequired)
            {
            	log.error("#"+id+" transport failed : "+e.toString());
            	transport.closeTransport(true);
            }
        }
        catch (Throwable e)
        {
        	log.fatal("#"+id+" TCP packet receiver died",e);
        }
        
        log.debug("#"+id+" stopping.");
    }
298521
public void run() {
    String hostName = host != null ? host : "localhost";
    ServerTools.print("Starting LanguageTool " + JLanguageTool.VERSION +
            " (build date: " + JLanguageTool.BUILD_DATE + ", " + JLanguageTool.GIT_SHORT_ID + ") server on " + getProtocol() + "://" + hostName + ":" + port  + "...");
    server.start();
    isRunning = true;
    ServerTools.print("Server started");
  }
293979
public void startup() {
        if (isRunning) return;

        Executors.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                DispatcherHandler handler = new DispatcherHandler(AndServer.getContext());
                ComponentRegister register = new ComponentRegister(AndServer.getContext());
                register.register(handler, mGroup);

                mHttpServer = ServerBootstrap.bootstrap()
                    .setSocketConfig(SocketConfig.custom()
                        .setSoKeepAlive(true)
                        .setSoReuseAddress(true)
                        .setSoTimeout(mTimeout)
                        .setTcpNoDelay(true)
                        .build())
                    .setConnectionConfig(
                        ConnectionConfig.custom().setBufferSize(4 * 1024).setCharset(Charsets.UTF_8).build())
                    .setLocalAddress(mInetAddress)
                    .setListenerPort(mPort)
                    .setSslContext(mSSLContext)
                    .setSslSetupHandler(new SSLInitializerWrapper(mSSLInitializer))
                    .setServerInfo("AndServer/2.0.0")
                    .registerHandler("*", handler)
                    .setExceptionLogger(ExceptionLogger.NO_OP)
                    .create();
                try {
                    isRunning = true;
                    mHttpServer.start();

                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onStarted();
                        }
                    });
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            mHttpServer.shutdown(3, TimeUnit.SECONDS);
                        }
                    });
                } catch (final Exception e) {
                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onException(e);
                        }
                    });
                }
            }
        });
    }
574894
public synchronized void start() throws IOException {
    if (running) {
      throw new IllegalStateException("Monitor is already running");
    }
    for (final PathAlterationObserver observer : observers) {
      observer.initialize();
    }

    if (interval > 0) {
        running = true;
        this.executionResult = executor.scheduleWithFixedDelay(this, initialDelay, interval, TimeUnit.MILLISECONDS);
    } else {
        LOGGER.info("Not starting due to non-positive scheduling interval:" + interval);
    }
  }
669566
def run( self ):
        

        self.handshake()

        try:
            self.loop()
        except socket.error, se:
            if self.finished:
                return True
            else:
                raise
1047038
public void run() {
        // Unique nr that identifies this request.
        int thisRequest = compilerPool.startRequest();
        long start = System.currentTimeMillis();
        int numClasses = 0;
        StringBuilder compiledPkgs = new StringBuilder();
        use();

        PrintWriter out = null;
        try {
            javacServer.log("<"+thisRequest+"> Connect from "+socket.getRemoteSocketAddress()+" activethreads="+compilerPool.numActiveRequests());
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                                       socket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(
                                                  socket.getOutputStream()));
            if (!expect(in, JavacServer.PROTOCOL_COOKIE_VERSION)) {
                javacServer.log("<"+thisRequest+"> Bad protocol from ip "+socket.getRemoteSocketAddress());
                return;
            }

            String cookie = in.readLine();
            if (cookie == null || !cookie.equals(""+javacServer.getCookie())) {
                javacServer.log("<"+thisRequest+"> Bad cookie from ip "+socket.getRemoteSocketAddress());
                return;
            }
            if (!expect(in, JavacServer.PROTOCOL_CWD)) {
                return;
            }
            String cwd = in.readLine();
            if (cwd == null)
                return;
            if (!expect(in, JavacServer.PROTOCOL_ID)) {
                return;
            }
            id = in.readLine();
            if (id == null)
                return;
            if (!expect(in, JavacServer.PROTOCOL_ARGS)) {
                return;
            }
            ArrayList<String> the_options = new ArrayList<String>();
            ArrayList<File> the_classes = new ArrayList<File>();
            Iterable<File> path = Arrays.<File> asList(new File(cwd));

            for (;;) {
                String l = in.readLine();
                if (l == null)
                    return;
                if (l.equals(JavacServer.PROTOCOL_SOURCES_TO_COMPILE))
                    break;
                if (l.startsWith("--server:"))
                    continue;
                if (!l.startsWith("-") && l.endsWith(".java")) {
                    the_classes.add(new File(l));
                    numClasses++;
                } else {
                    the_options.add(l);
                }
                continue;
            }

            // Load sources to compile
            Set<URI> sourcesToCompile = new HashSet<URI>();
            for (;;) {
                String l = in.readLine();
                if (l == null)
                    return;
                if (l.equals(JavacServer.PROTOCOL_VISIBLE_SOURCES))
                    break;
                try {
                    sourcesToCompile.add(new URI(l));
                    numClasses++;
                } catch (URISyntaxException e) {
                    return;
                }
            }
            // Load visible sources
            Set<URI> visibleSources = new HashSet<URI>();
            boolean fix_drive_letter_case =
                StringUtils.toLowerCase(System.getProperty("os.name")).startsWith("windows");
            for (;;) {
                String l = in.readLine();
                if (l == null)
                    return;
                if (l.equals(JavacServer.PROTOCOL_END))
                    break;
                try {
                    URI u = new URI(l);
                    if (fix_drive_letter_case) {
                        // Make sure the driver letter is lower case.
                        String s = u.toString();
                        if (s.startsWith("file:/") &&
                            Character.isUpperCase(s.charAt(6))) {
                            u = new URI("file:/"+Character.toLowerCase(s.charAt(6))+s.substring(7));
                        }
                    }
                    visibleSources.add(u);
                } catch (URISyntaxException e) {
                    return;
                }
            }

            // A completed request has been received.

            // Now setup the actual compilation....
            // First deal with explicit source files on cmdline and in at file.
            com.sun.tools.javac.util.ListBuffer<JavaFileObject> compilationUnits =
                new com.sun.tools.javac.util.ListBuffer<JavaFileObject>();
            for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(the_classes)) {
                compilationUnits.append(i);
            }
            // Now deal with sources supplied as source_to_compile.
            com.sun.tools.javac.util.ListBuffer<File> sourcesToCompileFiles =
                new com.sun.tools.javac.util.ListBuffer<File>();
            for (URI u : sourcesToCompile) {
                sourcesToCompileFiles.append(new File(u));
            }
            for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(sourcesToCompileFiles)) {
                compilationUnits.append(i);
            }
            // Log the options to be used.
            StringBuilder options = new StringBuilder();
            for (String s : the_options) {
                options.append(">").append(s).append("< ");
            }
            javacServer.log(id+" <"+thisRequest+"> options "+options.toString());

            forcedExitCode = 0;
            // Create a new logger.
            StringWriter stdoutLog = new StringWriter();
            StringWriter stderrLog = new StringWriter();
            stdout = new PrintWriter(stdoutLog);
            stderr = new PrintWriter(stderrLog);
            com.sun.tools.javac.main.Main.Result rc = com.sun.tools.javac.main.Main.Result.OK;
            try {
                if (compilationUnits.size() > 0) {
                    // Bind the new logger to the existing context.
                    context.put(Log.outKey, stderr);
                    Log.instance(context).setWriter(Log.WriterKind.NOTICE, stdout);
                    Log.instance(context).setWriter(Log.WriterKind.WARNING, stderr);
                    Log.instance(context).setWriter(Log.WriterKind.ERROR, stderr);
                    // Process the options.
                    com.sun.tools.javac.api.JavacTool.processOptions(context, smartFileManager, the_options);
                    fileManagerBase.setContext(context);
                    smartFileManager.setVisibleSources(visibleSources);
                    smartFileManager.cleanArtifacts();
                    smartFileManager.setLog(stdout);
                    Dependencies.instance(context).reset();

                    com.sun.tools.javac.main.Main ccompiler = new com.sun.tools.javac.main.Main("javacTask", stderr);
                    String[] aa = the_options.toArray(new String[0]);

                    // Do the compilation!
                    rc = ccompiler.compile(aa, context, compilationUnits.toList(), null);

                    while (numActiveSubTasks()>0) {
                        try { Thread.sleep(1000); } catch (InterruptedException e) { }
                    }

                    smartFileManager.flush();
                }
            } catch (Exception e) {
                stderr.println(e.getMessage());
                forcedExitCode = -1;
            }

            // Send the response..
            out.println(JavacServer.PROTOCOL_STDOUT);
            out.print(stdoutLog);
            out.println(JavacServer.PROTOCOL_STDERR);
            out.print(stderrLog);
            // The compilation is complete! And errors will have already been printed on out!
            out.println(JavacServer.PROTOCOL_PACKAGE_ARTIFACTS);
            Map<String,Set<URI>> pa = smartFileManager.getPackageArtifacts();
            for (String aPkgName : pa.keySet()) {
                out.println("+"+aPkgName);
                Set<URI> as = pa.get(aPkgName);
                for (URI a : as) {
                    out.println(" "+a.toString());
                }
            }
            Dependencies deps = Dependencies.instance(context);
            out.println(JavacServer.PROTOCOL_PACKAGE_DEPENDENCIES);
            Map<String,Set<String>> pd = deps.getDependencies();
            for (String aPkgName : pd.keySet()) {
                out.println("+"+aPkgName);
                Set<String> ds = pd.get(aPkgName);
                    // Everything depends on java.lang
                    if (!ds.contains(":java.lang")) ds.add(":java.lang");
                for (String d : ds) {
                    out.println(" "+d);
                }
            }
            out.println(JavacServer.PROTOCOL_PACKAGE_PUBLIC_APIS);
            Map<String,String> pp = deps.getPubapis();
            for (String aPkgName : pp.keySet()) {
                out.println("+"+aPkgName);
                String ps = pp.get(aPkgName);
                // getPubapis added a space to each line!
                out.println(ps);
                compiledPkgs.append(aPkgName+" ");
            }
            out.println(JavacServer.PROTOCOL_SYSINFO);
            out.println("num_cores=" + Runtime.getRuntime().availableProcessors());
            out.println("max_memory=" + Runtime.getRuntime().maxMemory());
            out.println(JavacServer.PROTOCOL_RETURN_CODE);

            // Errors from sjavac that affect compilation status!
            int rcv = rc.exitCode;
            if (rcv == 0 && forcedExitCode != 0) {
                rcv = forcedExitCode;
            }
            out.println("" + rcv);
            out.println(JavacServer.PROTOCOL_END);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
                if (!socket.isClosed()) {
                    socket.close();
                }
                socket = null;
            } catch (Exception e) {
                javacServer.log("ERROR "+e);
                e.printStackTrace();
            }
            compilerPool.stopRequest();
            long duration = System.currentTimeMillis()-start;
            javacServer.addBuildTime(duration);
            float classpersec = ((float)numClasses)*(((float)1000.0)/((float)duration));
            javacServer.log(id+" <"+thisRequest+"> "+compiledPkgs+" duration " + duration+ " ms    num_classes="+numClasses+
                             "     classpersec="+classpersec+" subtasks="+subTasks.size());
            javacServer.flushLog();
            unuse();
            compilerPool.returnCompilerThread(this);
        }
    }
1043563
@Override
  public void run()
  {
    try {
      runImpl();
    } catch (final Throwable e) {
      // env/0203 vs env/0206
      if (e instanceof DisplayableException)
        log.warning(e.getMessage());
      else
        log.warning(e.toString());
      
      _exception = e;
    } finally {
      notifyComplete();
    }
  }
743678
public synchronized void start() throws SocketException {

        if (!isRunning()) {
            socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));
            startTime.set(System.currentTimeMillis());
            deliverLifecycleAnnouncement(logger, true);

            final byte[] buffer = new byte[512];
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            Thread receiver = new Thread(null, new Runnable() {
                @Override
                public void run() {
                    boolean received;
                    while (isRunning()) {
                        try {
                            if (getCurrentDevices().isEmpty()) {
                                socket.get().setSoTimeout(60000);  // We have no devices to check for timeout; block for a whole minute to check for shutdown
                            } else {
                                socket.get().setSoTimeout(1000);  // Check every second to see if a device has vanished
                            }
                            socket.get().receive(packet);
                            received = !ignoredAddresses.contains(packet.getAddress());
                        } catch (SocketTimeoutException ste) {
                            received = false;
                        } catch (IOException e) {
                            // Don't log a warning if the exception was due to the socket closing at shutdown.
                            if (isRunning()) {
                                // We did not expect to have a problem; log a warning and shut down.
                                logger.warn("Problem reading from DeviceAnnouncement socket, stopping", e);
                                stop();
                            }
                            received = false;
                        }
                        try {
                            if (received && (packet.getLength() == 54)) {
                                final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);
                                if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {
                                    // Looks like the kind of packet we need
                                    if (packet.getLength() < 54) {
                                        logger.warn("Ignoring too-short " + kind.name + " packet; expected 54 bytes, but only got " +
                                                packet.getLength() + ".");
                                    } else {
                                        if (packet.getLength() > 54) {
                                            logger.warn("Processing too-long " + kind.name + " packet; expected 54 bytes, but got " +
                                                    packet.getLength() + ".");
                                        }
                                        DeviceAnnouncement announcement = new DeviceAnnouncement(packet);
                                        final boolean foundNewDevice = isDeviceNew(announcement);
                                        updateDevices(announcement);
                                        if (foundNewDevice) {
                                            deliverFoundAnnouncement(announcement);
                                        }
                                    }
                                }
                            }
                            expireDevices();
                        } catch (Throwable t) {
                            logger.warn("Problem processing DeviceAnnouncement packet", t);
                        }
                    }
                }
            }, "beat-link DeviceFinder receiver");
            receiver.setDaemon(true);
            receiver.start();
        }
    }
709375
public void run() {
        if(log.isDebugEnabled()) {
            log.debug("ListenerThread Starting.");
        }

        while(running) {
            try {
                Socket clientSocket = serverSocket.accept();

                WorkerThread worker = new WorkerThread(container, clientSocket);
                worker.start();

            } catch(SocketTimeoutException ste) {
                // Ignore. We receive one of these every second, when the accept()
                // method times out. This is done to give us the opportunity to break
                // out of the blocking accept() call in order to shut down cleanly.

            } catch(Exception e) {
                if(log.isErrorEnabled()) {
                    log.error("Error Accepting: " + e.toString(), e);
                }
            }
        }

		try {
			serverSocket.close();
			
		} catch (IOException e) {
			if(log.isErrorEnabled()) {
				log.error("Error closing the server socket: " + e.toString(), e);
			}
		}
    }
1185368
@SuppressWarnings("resource")
  public void run() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    ServerSocketChannel errsock = null;
    boolean saw_error = false;

    while( true ) {
      try {
        // Cleanup from any prior socket failures.  Rare unless we're really sick.
        if( errsock != null ) { // One time attempt a socket close
          final ServerSocketChannel tmp2 = errsock; errsock = null;
          tmp2.close();       // Could throw, but errsock cleared for next pass
        }
        if( saw_error ) Thread.sleep(100); // prevent deny-of-service endless socket-creates
        saw_error = false;

        // ---
        // More common-case setup of a ServerSocket
        if( SOCK == null ) {
          SOCK = ServerSocketChannel.open();
          SOCK.socket().setReceiveBufferSize(AutoBuffer.BBSIZE);
          SOCK.socket().bind(H2O.SELF._key);
        }

        // Block for TCP connection and setup to read from it.
        SocketChannel sock = SOCK.accept();

        // Pass off the TCP connection to a separate reader thread
        new TCPReaderThread(sock,new AutoBuffer(sock)).start();

      } catch( java.nio.channels.AsynchronousCloseException ex ) {
        break;                  // Socket closed for shutdown
      } catch( Exception e ) {
        // On any error from anybody, close all sockets & re-open
        Log.err("Retrying after IO error on TCP port "+H2O.H2O_PORT +": ",e);
        saw_error = true;
        errsock = SOCK ;  SOCK = null; // Signal error recovery on the next loop
      }
    }
  }
787928
@Override
	public void run() {
		while (running) {
			try {
				// Read the request
				service.execute(new HttpSession(this, socket.accept()));
			} catch (IOException e) {
				// Ignore mostly.
			}
		}
	}
630236
public void run() {
    /**
     * Ensure we start fresh.
     */
    closeServerSocket();
    closeAllAcceptedSockets();

    // start the server socket
    try {
      serverSocket = new ServerSocket(port);
    } catch (Exception e) {
      getLogger().error(
        "error starting SocketReceiver (" + this.getName()
        + "), receiver did not start", e);
      active = false;

      return;
    }

    Socket socket = null;

    try {
      getLogger().debug("in run-about to enter while not interrupted loop");

      active = true;

      while (!rThread.isInterrupted()) {
        // if we have a socket, start watching it
        if (socket != null) {
          getLogger().debug(
                  "socket not null - creating and starting socketnode");
          socketList.add(socket);

          SocketNode13 node = new SocketNode13(socket, this);
          synchronized (listenerList) {
            for (Iterator iter = listenerList.iterator();
                 iter.hasNext();) {
                SocketNodeEventListener l =
                        (SocketNodeEventListener) iter.next();
                node.addSocketNodeEventListener(l);
            }
          }
          socketMap.put(socket, node);
          new Thread(node).start();
          socket = null;
        }

        getLogger().debug("waiting to accept socket");

        // wait for a socket to open, then loop to start it
        socket = serverSocket.accept();
        getLogger().debug("accepted socket");
      }
    } catch (Exception e) {
      getLogger().warn(
        "exception while watching socket server in SocketReceiver ("
        + this.getName() + "), stopping");
    }

    getLogger().debug("{} has exited the not interrupted loop", getName());

    // socket not watched because we a no longer running
    // so close it now.
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e1) {
        getLogger().warn("socket exception caught - socket closed");
      }
    }

    getLogger().debug("{} is exiting main run loop", getName());
  }
503773
void start() {
    for (int i = 0; i < threadCount; i++) {
      Runnable r = null;
      switch (config.getPayloadConfig().getPayloadCase()) {
        case SIMPLE_PARAMS: {
          if (config.getClientType() == Control.ClientType.ASYNC_CLIENT) {
            if (config.getRpcType() == Control.RpcType.UNARY) {
              r = new AsyncUnaryWorker(clients[i % clients.length]);
            } else if (config.getRpcType() == Control.RpcType.STREAMING) {
              r = new AsyncPingPongWorker(mat, clients[i % clients.length]);
            }
          }
          break;
        }
        default: {
          throw Status.UNIMPLEMENTED.withDescription(
              "Unknown payload case " + config.getPayloadConfig().getPayloadCase().name())
              .asRuntimeException();
        }
      }
      if (r == null) {
        throw new IllegalStateException(config.getRpcType().name()
            + " not supported for client type "
            + config.getClientType());
      }
      fixedThreadPool.execute(r);
    }
    if (osBean != null) {
      lastMarkCpuTime = osBean.getProcessCpuTime();
    }
  }
673559
@Benchmark
    public ExampleClass benchmarkJavassist() throws Exception {
        ProxyFactory proxyFactory = new ProxyFactory() {
            protected ClassLoader getClassLoader() {
                return newClassLoader();
            }
        };
        proxyFactory.setUseCache(false);
        proxyFactory.setUseWriteReplace(false);
        proxyFactory.setSuperclass(baseClass);
        proxyFactory.setFilter(new MethodFilter() {
            public boolean isHandled(Method method) {
                return method.getDeclaringClass() == baseClass;
            }
        });
        @SuppressWarnings("unchecked")
        Object instance = proxyFactory.createClass().getDeclaredConstructor().newInstance();
        ((javassist.util.proxy.Proxy) instance).setHandler(new MethodHandler() {
            public Object invoke(Object self,
                                 Method thisMethod,
                                 Method proceed,
                                 Object[] args) throws Throwable {
                return proceed.invoke(self, args);
            }
        });
        return (ExampleClass) instance;
    }
1247876
public synchronized void start() throws SocketException {
        if (!isRunning()) {
            socket.set(new DatagramSocket(BEAT_PORT));
            deliverLifecycleAnnouncement(logger, true);
            final byte[] buffer = new byte[512];
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            Thread receiver = new Thread(null, new Runnable() {
                @Override
                public void run() {
                    boolean received;
                    while (isRunning()) {
                        try {
                            socket.get().receive(packet);
                            received = !DeviceFinder.getInstance().isAddressIgnored(packet.getAddress());
                        } catch (IOException e) {
                            // Don't log a warning if the exception was due to the socket closing at shutdown.
                            if (isRunning()) {
                                // We did not expect to have a problem; log a warning and shut down.
                                logger.warn("Problem reading from DeviceAnnouncement socket, stopping", e);
                                stop();
                            }
                            received = false;
                        }
                        try {
                            if (received) {
                                final Util.PacketType kind = Util.validateHeader(packet,  BEAT_PORT);
                                if (kind != null) {
                                    switch (kind) {

                                        case BEAT:
                                            if (isPacketLongEnough(packet, 96, "beat")) {
                                                deliverBeat(new Beat(packet));
                                            }
                                            break;

                                        case CHANNELS_ON_AIR:
                                            if (isPacketLongEnough(packet, 0x2d, "channels on-air")) {
                                                byte[] data = packet.getData();
                                                Set<Integer> audibleChannels = new TreeSet<Integer>();
                                                for (int channel = 1; channel <= 4; channel++) {
                                                    if (data[0x23 + channel] != 0) {
                                                        audibleChannels.add(channel);
                                                    }
                                                }
                                                audibleChannels = Collections.unmodifiableSet(audibleChannels);
                                                deliverOnAirUpdate(audibleChannels);
                                            }
                                            break;

                                        case SYNC_CONTROL:
                                            if (isPacketLongEnough(packet, 0x2c, "sync control command")) {
                                                deliverSyncCommand(packet.getData()[0x2b]);
                                            }
                                            break;

                                        case MASTER_HANDOFF_REQUEST:
                                            if (isPacketLongEnough(packet, 0x28, "tempo master handoff request")) {
                                                deliverMasterYieldCommand(packet.getData()[0x21]);
                                            }
                                            break;

                                        case MASTER_HANDOFF_RESPONSE:
                                            if (isPacketLongEnough(packet, 0x2c, "tempo master handoff response")) {
                                                byte[] data = packet.getData();
                                                deliverMasterYieldResponse(data[0x21], data[0x2b] == 1);
                                            }
                                            break;

                                        case FADER_START_COMMAND:
                                            if (isPacketLongEnough(packet, 0x28, "fader start command")) {
                                                byte[] data = packet.getData();
                                                Set<Integer> playersToStart = new TreeSet<Integer>();
                                                Set<Integer> playersToStop = new TreeSet<Integer>();
                                                for (int channel = 1; channel <= 4; channel++) {
                                                    switch (data[0x23 + channel]) {

                                                        case 0:
                                                            playersToStart.add(channel);
                                                            break;

                                                        case 1:
                                                            playersToStop.add(channel);
                                                            break;

                                                        case 2:
                                                            // Leave this player alone
                                                            break;

                                                        default:
                                                            logger.warn("Ignoring unrecognized fader start command, " +
                                                                    data[0x23 + channel] + ", for channel " + channel);
                                                    }
                                                }
                                                playersToStart = Collections.unmodifiableSet(playersToStart);
                                                playersToStop = Collections.unmodifiableSet(playersToStop);
                                                deliverFaderStartCommand(playersToStart, playersToStop);
                                            }
                                            break;

                                        default:
                                            logger.warn("Ignoring packet received on beat port with unexpected type: " + kind);
                                    }
                                }
                            }
                        } catch (Throwable t) {
                            logger.warn("Problem processing beat packet", t);
                        }
                    }
                }
            }, "beat-link BeatFinder receiver");
            receiver.setDaemon(true);
            receiver.setPriority(Thread.MAX_PRIORITY);
            receiver.start();
        }
    }