Support class used to handle threads
Inheritance: IThreadRunnable
 public virtual void  Init(IndexReader reader)
 {
     this.reader = reader;
     timeElapsed = 0;
     t           = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
     t.Start();
 }
Exemple #2
0
        public virtual void  TestRAMDirectorySize()
        {
            MockRAMDirectory ramDir = new MockRAMDirectory(indexDir.FullName);
            IndexWriter      writer = new IndexWriter(ramDir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED);

            writer.Optimize();

            Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());

            SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[numThreads];
            for (int i = 0; i < numThreads; i++)
            {
                int num = i;
                threads[i] = new AnonymousClassThread(num, writer, ramDir, this);
            }
            for (int i = 0; i < numThreads; i++)
            {
                threads[i].Start();
            }
            for (int i = 0; i < numThreads; i++)
            {
                threads[i].Join();
            }

            writer.Optimize();
            Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());

            writer.Close();
        }
        public static void  Main(System.String[] args)
        {
            if (args.Length != 2)
            {
                System.Console.Out.WriteLine("Usage: Genetibase.NuGenHL7.app.Initiator host port");
            }

            try
            {
                //set up connection to server
                System.String host = args[0];
                int           port = System.Int32.Parse(args[1]);

                Parser             parser     = new PipeParser();
                LowerLayerProtocol llp        = LowerLayerProtocol.makeLLP();
                NuGenConnection    connection = new NuGenConnection(parser, llp, new System.Net.Sockets.TcpClient(host, port));
                NuGenInitiator     initiator  = connection.Initiator;
                System.String      outText    = "MSH|^~\\&|||||||ACK^^ACK|||R|2.4|\rMSA|AA";

                //get a bunch of threads to send messages
                for (int i = 0; i < 1000; i++)
                {
                    SupportClass.ThreadClass sender = new SupportClass.ThreadClass(new System.Threading.ThreadStart(new AnonymousClassRunnable(parser, outText, initiator).Run));
                    sender.Start();
                }
            }
            catch (System.Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
Exemple #4
0
 /// <summary> Creates a new thread used to run the audio player.
 /// </summary>
 /// <returns> A new Thread that, once started, runs the audio player.
 ///
 /// </returns>
 protected internal virtual SupportClass.ThreadClass createPlayerThread()
 {
     SupportClass.ThreadClass temp_Thread;
     temp_Thread      = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
     temp_Thread.Name = "Audio player thread";
     return(temp_Thread);
 }
Exemple #5
0
        /// <summary> Initially sets up server sockets and starts separate threads to accept connections
        /// on them.  Then loops, calling this.accept() super.newConnection().
        /// </summary>
        public override void Run()
        {
            try
            {
                AcceptThread             inAccept  = new AcceptThread(this, inboundPort, inSockets);
                AcceptThread             outAccept = new AcceptThread(this, outboundPort, outSockets);
                SupportClass.ThreadClass inThread  = new SupportClass.ThreadClass(new System.Threading.ThreadStart(inAccept.Run));
                SupportClass.ThreadClass outThread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(outAccept.Run));
                inThread.Start();
                outThread.Start();

                while (keepRunning())
                {
                    NuGenConnection conn = accept(3000);
                    if (conn != null)
                    {
                        newConnection(conn);
                    }
                }

                inAccept.stop();
                outAccept.stop();
            }
            catch (System.Exception)
            {
            }
        }
		/// <summary> Starts the server listening for connections in a new thread.  This continues 
		/// until <code>stop()</code> is called.  
		/// </summary>
		public virtual void  start()
		{
			thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
			this.keepRunning_Renamed_Field = true;
			thd.Start();            
			//Fix for bug 960101:  Don't start the cleaner thread until the server is started.
			SupportClass.ThreadClass cleaner = new SupportClass.ThreadClass(new System.Threading.ThreadStart(new NuGenHL7Service.ConnectionCleaner(this, this).Run));
			cleaner.Start();
		}
 /// <summary> Starts the server listening for connections in a new thread.  This continues
 /// until <code>stop()</code> is called.
 /// </summary>
 public virtual void  start()
 {
     thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
     this.keepRunning_Renamed_Field = true;
     thd.Start();
     //Fix for bug 960101:  Don't start the cleaner thread until the server is started.
     SupportClass.ThreadClass cleaner = new SupportClass.ThreadClass(new System.Threading.ThreadStart(new NuGenHL7Service.ConnectionCleaner(this, this).Run));
     cleaner.Start();
 }
Exemple #8
0
            /// <summary> Starts waiting in a separate thread for connections to the given
            /// ServerSocket from the given IP address.
            /// </summary>
            /// <param name="theServer">
            /// </param>
            /// <param name="theAddress">IP address from which to accept connections (null
            /// means any)
            /// </param>
            public Acceptor(System.Net.Sockets.TcpListener theServer, System.String theAddress)
            {
                Acceptor a = this;

                IThreadRunnable r = new AnonymousClassRunnable(a, theServer, theAddress, this);

                SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(r.Run));
                thd.Start();
            }
Exemple #9
0
 /// <summary> Stops the audio player. If the player is already stopped
 /// this method is a no-op.
 /// </summary>
 protected internal virtual void  stopPlayer()
 {
     if (player != null)
     {
         player.close();
         player       = null;
         playerThread = null;
     }
 }
Exemple #10
0
        public virtual void  TestDuringAddDelete()
        {
            Directory   dir1   = new MockRAMDirectory();
            IndexWriter writer = new IndexWriter(dir1, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);

            writer.SetInfoStream(infoStream);
            writer.SetMergeFactor(2);

            // create the index
            CreateIndexNoClose(false, "test", writer);
            writer.Commit();

            IndexReader r = writer.GetReader();

            int   NUM_THREAD = 5;
            float SECONDS    = 3;

            long endTime = (long)((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000.0 * SECONDS);

            System.Collections.IList excs = (System.Collections.IList)System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(new System.Collections.ArrayList()));

            SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[NUM_THREAD];
            for (int i = 0; i < NUM_THREAD; i++)
            {
                threads[i] = new AnonymousClassThread1(endTime, writer, excs, this);
                threads[i].IsBackground = true;
                threads[i].Start();
            }

            int sum = 0;

            while ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) < endTime)
            {
                IndexReader r2 = r.Reopen();
                if (r2 != r)
                {
                    r.Close();
                    r = r2;
                }
                Query q = new TermQuery(new Term("indexname", "test"));
                sum += new IndexSearcher(r).Search(q, 10).totalHits;
            }

            for (int i = 0; i < NUM_THREAD; i++)
            {
                threads[i].Join();
            }
            Assert.IsTrue(sum > 0);

            Assert.AreEqual(0, excs.Count);
            writer.Close();

            _TestUtil.CheckIndex(dir1);
            r.Close();
            dir1.Close();
        }
Exemple #11
0
        /// <summary> Starts accepting connections in a new Thread.  Note that this can be
        /// called multiple times with separate addresses.  The stop() method ends
        /// all Threads started here.
        ///
        /// </summary>
        /// <param name="theAddress">IP address from which connections are accepted (null
        /// means any address is OK)
        /// </param>
        public virtual void  start(System.String theAddress)
        {
            NuGenHL7Server  server   = this;
            IThreadRunnable acceptor = new AnonymousClassRunnable(server, theAddress, this);

            myIsRunning = true;

            SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(acceptor.Run));
            thd.Start();
        }
Exemple #12
0
 public void  Listen()
 {
     listening = true;
     if (serverThread == null)
     {
         IThreadRunnable runnable = new FastServerThread(this);
         serverThread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(runnable.Run), "FastServer");
     }
     serverThread.Start();
 }
Exemple #13
0
        /// <summary> Decompresses audio data from an InputStream and plays it
        /// back through an AudioDevice. The playback is run on a newly
        /// created thread.
        ///
        /// </summary>
        /// <param name="in	The">InputStream that provides the MPEG audio data.
        /// </param>
        /// <param name="dev	The">AudioDevice to use to sound the decompressed data.
        ///
        /// @throws JavaLayerException if there was a problem decoding
        /// or playing the audio data.
        ///
        /// </param>
        protected internal virtual void  play(System.IO.Stream @in, AudioDevice dev)
        {
            stopPlayer();

            if (@in != null && dev != null)
            {
                player       = new Player(@in, dev);
                playerThread = createPlayerThread();
                playerThread.Start();
            }
        }
Exemple #14
0
        /// <summary> Sets up the FilterManager singleton.</summary>
        protected internal FilterManager()
        {
            cache          = new System.Collections.Hashtable();
            cacheCleanSize = DEFAULT_CACHE_CLEAN_SIZE;             // Let the cache get to 100 items
            cleanSleepTime = DEFAULT_CACHE_SLEEP_TIME;             // 10 minutes between cleanings

            filterCleaner = new FilterCleaner(this);
            SupportClass.ThreadClass fcThread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(filterCleaner.Run));
            // setto be a Daemon so it doesn't have to be stopped
            fcThread.IsBackground = true;
            fcThread.Start();
        }
Exemple #15
0
 private void  ListenForMessages()
 {
     if (listeningThread == null)
     {
         IThreadRunnable messageReader = new SessionThread(this);
         listeningThread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(messageReader.Run), "FAST Session Message Reader");
     }
     if (listeningThread.IsAlive)
     {
         return;
     }
     listeningThread.Start();
 }
Exemple #16
0
        /// <summary>Sends in a new thread if isThreaded, otherwise in current thread </summary>
        private void  sendAppResponse(NuGenTransportable theResponse)
        {
            NuGenProcessorImpl processor = this;
            IThreadRunnable    sender    = new AnonymousClassRunnable(processor, theResponse, this);

            if (myThreaded)
            {
                SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(sender.Run));
                thd.Start();
            }
            else
            {
                sender.Run();
            }
        }
 internal static void registerProgressWatch(SupportClass.ThreadClass t, ProgressWatch pw)
 {
     if (pw == null)
     {
         throw new System.NullReferenceException();
     }
     if (t == null)
     {
         defWatchProg = pw;
     }
     else
     {
         watchProgList[t] = pw;
     }
 }
 /// <summary> Registers the MsgLogger 'ml' as the logging facility of the
 /// thread 't'. If any other logging facility was registered with
 /// the thread 't' it is overriden by 'ml'. If 't' is null then
 /// 'ml' is taken as the default message logger that is used for
 /// threads that have no MsgLogger registered.
 ///
 /// </summary>
 /// <param name="t">The thread to associate with 'ml'
 ///
 /// </param>
 /// <param name="ml">The MsgLogger to associate with therad ml
 ///
 /// </param>
 internal static void registerMsgLogger(SupportClass.ThreadClass t, MsgLogger ml)
 {
     if (ml == null)
     {
         throw new System.NullReferenceException();
     }
     if (t == null)
     {
         defMsgLogger = ml;
     }
     else
     {
         loggerList[t] = ml;
     }
 }
Exemple #19
0
        public virtual void  TestThreadSafety()
        {
            rnd = NewRandom();
            int           numThreads = 5;
            int           numDocs    = 50;
            ByteArrayPool pool       = new ByteArrayPool(numThreads, 5);

            Directory   dir    = new RAMDirectory();
            IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);

            System.String field = "test";

            SupportClass.ThreadClass[] ingesters = new SupportClass.ThreadClass[numThreads];
            for (int i = 0; i < numThreads; i++)
            {
                ingesters[i] = new AnonymousClassThread(numDocs, field, pool, writer, this);
                ingesters[i].Start();
            }

            for (int i = 0; i < numThreads; i++)
            {
                ingesters[i].Join();
            }
            writer.Close();
            IndexReader reader = IndexReader.Open(dir);
            TermEnum    terms  = reader.Terms();

            while (terms.Next())
            {
                TermPositions tp = reader.TermPositions(terms.Term());
                while (tp.Next())
                {
                    int freq = tp.Freq();
                    for (int i = 0; i < freq; i++)
                    {
                        tp.NextPosition();
                        Assert.AreEqual(pool.BytesToString(tp.GetPayload(new byte[5], 0)), terms.Term().text_ForNUnit);
                    }
                }
                tp.Close();
            }
            terms.Close();
            reader.Close();

            Assert.AreEqual(pool.Size(), numThreads);
        }
Exemple #20
0
        /// <param name="theContext">source of supporting services
        /// </param>
        /// <param name="isThreaded">true if this class should create threads in which to call cycle(), and
        /// in which to send responses from Applications.  This is the preferred mode.  Use false
        /// if threading is not allowed, eg you are running the code in an EJB container.  In this case,
        /// the send() and receive() methods will call cycle() themselves as needed.  However, cycle()
        /// makes potentially blocking calls, so these methods may not return until the next message
        /// is received from the remote server, regardless of timeout.  Probably the worst example of this
        /// would be if receive() was called to wait for an application ACK that was specified as "RE" (ie
        /// required on error).  No response will be returned if the message is processed without error,
        /// and in a non-threaded environment, receive() will block forever.  Use true if you can, otherwise
        /// study this class carefully.
        ///
        /// TODO: write a MLLPTransport with non-blocking IO
        /// TODO: reconnect transport layers on error and retry
        /// </param>
        public NuGenProcessorImpl(NuGenProcessorContext theContext, bool isThreaded)
        {
            myContext           = theContext;
            myThreaded          = isThreaded;
            myAcceptAcks        = new System.Collections.Hashtable();
            myReservations      = new System.Collections.Hashtable();
            myAvailableMessages = new System.Collections.Hashtable();

            if (isThreaded)
            {
                ackCycler = new Cycler(this, true);
                SupportClass.ThreadClass ackThd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(ackCycler.Run));
                ackThd.Start();
                nonAckCycler = new Cycler(this, false);
                SupportClass.ThreadClass nonAckThd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(nonAckCycler.Run));
                nonAckThd.Start();
            }
        }
 private void  DoTestMultiThreads(bool withTimeout)
 {
     SupportClass.ThreadClass[]  threadArray = new SupportClass.ThreadClass[N_THREADS];
     System.Collections.BitArray success     = new System.Collections.BitArray((N_THREADS % 64 == 0?N_THREADS / 64:N_THREADS / 64 + 1) * 64);
     for (int i = 0; i < threadArray.Length; ++i)
     {
         int num = i;
         threadArray[num] = new AnonymousClassThread(withTimeout, success, num, this);
     }
     for (int i = 0; i < threadArray.Length; ++i)
     {
         threadArray[i].Start();
     }
     for (int i = 0; i < threadArray.Length; ++i)
     {
         threadArray[i].Join();
     }
     Assert.AreEqual(N_THREADS, SupportClass.BitSetSupport.Cardinality(success), "some threads failed!");
 }
Exemple #22
0
        public void Test()
        {
            SupportClass.ThreadClass thread = new SupportClass.ThreadClass();

            //Compare Current Thread Ids
            Assert.IsTrue(SupportClass.ThreadClass.Current().Instance.ManagedThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId);


            //Compare instances of ThreadClass
            MyThread mythread = new MyThread();

            mythread.Start();
            while (mythread.Result == null)
            {
                System.Threading.Thread.Sleep(1);
            }
            Assert.IsTrue((bool)mythread.Result);


            SupportClass.ThreadClass nullThread = null;
            Assert.IsTrue(nullThread == null);  //test overloaded operator == with null values
            Assert.IsFalse(nullThread != null); //test overloaded operator != with null values
        }
		private void  DoTestMultiThreads(bool withTimeout)
		{
			SupportClass.ThreadClass[] threadArray = new SupportClass.ThreadClass[N_THREADS];
			System.Collections.BitArray success = new System.Collections.BitArray((N_THREADS % 64 == 0?N_THREADS / 64:N_THREADS / 64 + 1) * 64);
			for (int i = 0; i < threadArray.Length; ++i)
			{
				int num = i;
				threadArray[num] = new AnonymousClassThread(withTimeout, success, num, this);
			}
			for (int i = 0; i < threadArray.Length; ++i)
			{
				threadArray[i].Start();
			}
			for (int i = 0; i < threadArray.Length; ++i)
			{
				threadArray[i].Join();
			}
			Assert.AreEqual(N_THREADS, SupportClass.BitSetSupport.Cardinality(success), "some threads failed!");
		}
		/// <summary> Starts accepting connections in a new Thread.  Note that this can be 
		/// called multiple times with separate addresses.  The stop() method ends
		/// all Threads started here.  
		/// 
		/// </summary>
		/// <param name="theAddress">IP address from which connections are accepted (null 
		/// means any address is OK) 
		/// </param>
		public virtual void  start(System.String theAddress)
		{
			NuGenHL7Server server = this;
			IThreadRunnable acceptor = new AnonymousClassRunnable(server, theAddress, this);
			
			myIsRunning = true;
			
			SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(acceptor.Run));
			thd.Start();
		}
        /// <summary> Returns the MsgLogger registered with the thread 't' (the
        /// thread that calls this method). If the thread 't' has no
        /// registered MsgLogger then the default message logger is
        /// returned.
        ///
        /// </summary>
        /// <param name="t">The thread for which to return the MsgLogger
        ///
        /// </param>
        /// <returns> The MsgLogger registerd for the current thread, or the
        /// default one if there is none registered for it.
        ///
        /// </returns>
        internal static MsgLogger getMsgLogger(SupportClass.ThreadClass t)
        {
            MsgLogger ml = (MsgLogger)loggerList[t];

            return((ml == null) ? defMsgLogger : ml);
        }
		public virtual void  TestRAMDirectorySize()
		{
			
			MockRAMDirectory ramDir = new MockRAMDirectory(indexDir.FullName);
			IndexWriter writer = new IndexWriter(ramDir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED);
			writer.Optimize();
			
			Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
			
			SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[numThreads];
			for (int i = 0; i < numThreads; i++)
			{
				int num = i;
				threads[i] = new AnonymousClassThread(num, writer, ramDir, this);
			}
			for (int i = 0; i < numThreads; i++)
				threads[i].Start();
			for (int i = 0; i < numThreads; i++)
				threads[i].Join();
			
			writer.Optimize();
			Assert.AreEqual(ramDir.SizeInBytes(), ramDir.GetRecomputedSizeInBytes());
			
			writer.Close();
		}
Exemple #27
0
        /// <summary> Decompresses audio data from an InputStream and plays it
        /// back through an AudioDevice. The playback is run on a newly
        /// created thread. 
        /// 
        /// </summary>
        /// <param name="in	The">InputStream that provides the MPEG audio data.
        /// </param>
        /// <param name="dev	The">AudioDevice to use to sound the decompressed data. 
        /// 
        /// @throws JavaLayerException if there was a problem decoding
        /// or playing the audio data.
        /// 
        /// </param>
        protected internal virtual void play(System.IO.Stream @in, AudioDevice dev)
        {
            stopPlayer();

            if (@in != null && dev != null)
            {
                player = new Player(@in, dev);
                playerThread = createPlayerThread();
                playerThread.Start();
            }
        }
		public virtual void  TestDuringAddIndexes()
		{
			Directory dir1 = new MockRAMDirectory();
			IndexWriter writer = new IndexWriter(dir1, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
			writer.SetInfoStream(infoStream);
			writer.SetMergeFactor(2);
			
			// create the index
			CreateIndexNoClose(false, "test", writer);
			writer.Commit();
			
			Directory[] dirs = new Directory[10];
			for (int i = 0; i < 10; i++)
			{
				dirs[i] = new MockRAMDirectory(dir1);
			}
			
			IndexReader r = writer.GetReader();
			
			int NUM_THREAD = 5;
			float SECONDS = 3;
			
			long endTime = (long) ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000.0 * SECONDS);
			System.Collections.IList excs = (System.Collections.IList) System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(new System.Collections.ArrayList()));
			
			SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[NUM_THREAD];
			for (int i = 0; i < NUM_THREAD; i++)
			{
				threads[i] = new AnonymousClassThread(endTime, writer, dirs, excs, this);
				threads[i].IsBackground = true;
				threads[i].Start();
			}
			
			int lastCount = 0;
			while ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) < endTime)
			{
				IndexReader r2 = r.Reopen();
				if (r2 != r)
				{
					r.Close();
					r = r2;
				}
				Query q = new TermQuery(new Term("indexname", "test"));
				int count = new IndexSearcher(r).Search(q, 10).totalHits;
				Assert.IsTrue(count >= lastCount);
				lastCount = count;
			}
			
			for (int i = 0; i < NUM_THREAD; i++)
			{
				threads[i].Join();
			}
			
			Assert.AreEqual(0, excs.Count);
			writer.Close();
			
			_TestUtil.CheckIndex(dir1);
			r.Close();
			dir1.Close();
		}
 private void Start()
 {
     go = new object();
     async = new object();
     thread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
     thread.Start();
 }
 public void Listen()
 {
     listening = true;
     if (serverThread == null)
     {
         IThreadRunnable runnable = new FastServerThread(this);
         serverThread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(runnable.Run), "FastServer");
     }
     serverThread.Start();
 }
Exemple #31
0
 /// <summary> Initializes and starts the ChannelListener that waits for results or
 /// errors from the Jamocha engine.
 /// 
 /// </summary>
 private void initChannelListener()
 {
     channelListener = new AnonymousClassThread(this);
     channelListener.Start();
 }
		public static void  Main(System.String[] args)
		{
			if (args.Length != 2)
			{
				System.Console.Out.WriteLine("Usage: Genetibase.NuGenHL7.app.Initiator host port");
			}
			
			try
			{
				
				//set up connection to server
				System.String host = args[0];
				int port = System.Int32.Parse(args[1]);
				
				Parser parser = new PipeParser();
				LowerLayerProtocol llp = LowerLayerProtocol.makeLLP();
				NuGenConnection connection = new NuGenConnection(parser, llp, new System.Net.Sockets.TcpClient(host, port));
				NuGenInitiator initiator = connection.Initiator;
				System.String outText = "MSH|^~\\&|||||||ACK^^ACK|||R|2.4|\rMSA|AA";
				
				//get a bunch of threads to send messages
				for (int i = 0; i < 1000; i++)
				{
					SupportClass.ThreadClass sender = new SupportClass.ThreadClass(new System.Threading.ThreadStart(new AnonymousClassRunnable(parser, outText, initiator).Run));
					sender.Start();
				}
			}
			catch (System.Exception e)
			{
				SupportClass.WriteStackTrace(e, Console.Error);
			}
		}
		public virtual void  runTest(Directory directory, bool autoCommit, MergeScheduler merger)
		{
			
			IndexWriter writer = new IndexWriter(directory, autoCommit, ANALYZER, true);
			writer.SetMaxBufferedDocs(2);
			if (merger != null)
				writer.SetMergeScheduler(merger);
			
			for (int iter = 0; iter < NUM_ITER; iter++)
			{
				int iterFinal = iter;
				
				writer.SetMergeFactor(1000);
				
				for (int i = 0; i < 200; i++)
				{
					Document d = new Document();
					d.Add(new Field("id", System.Convert.ToString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
					d.Add(new Field("contents", English.IntToEnglish(i), Field.Store.NO, Field.Index.ANALYZED));
					writer.AddDocument(d);
				}
				
				writer.SetMergeFactor(4);
				//writer.setInfoStream(System.out);
				
				int docCount = writer.DocCount();
				
				SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[NUM_THREADS];
				
				for (int i = 0; i < NUM_THREADS; i++)
				{
					int iFinal = i;
					IndexWriter writerFinal = writer;
					threads[i] = new AnonymousClassThread(writerFinal, iFinal, iterFinal, this);
				}
				
				for (int i = 0; i < NUM_THREADS; i++)
					threads[i].Start();
				
				for (int i = 0; i < NUM_THREADS; i++)
					threads[i].Join();
				
				Assert.IsTrue(!failed);
				
				int expectedDocCount = (int) ((1 + iter) * (200 + 8 * NUM_ITER2 * (NUM_THREADS / 2.0) * (1 + NUM_THREADS)));
				
				// System.out.println("TEST: now index=" + writer.segString());
				
				Assert.AreEqual(expectedDocCount, writer.DocCount());
				
				if (!autoCommit)
				{
					writer.Close();
					writer = new IndexWriter(directory, autoCommit, ANALYZER, false);
					writer.SetMaxBufferedDocs(2);
				}
				
				IndexReader reader = IndexReader.Open(directory);
				Assert.IsTrue(reader.IsOptimized());
				Assert.AreEqual(expectedDocCount, reader.NumDocs());
				reader.Close();
			}
			writer.Close();
		}
			/// <summary> Starts waiting in a separate thread for connections to the given 
			/// ServerSocket from the given IP address.  
			/// </summary>
			/// <param name="theServer">
			/// </param>
			/// <param name="theAddress">IP address from which to accept connections (null
			/// means any) 
			/// </param>
			public Acceptor(System.Net.Sockets.TcpListener theServer, System.String theAddress)
			{
				Acceptor a = this;
				
				IThreadRunnable r = new AnonymousClassRunnable(a, theServer, theAddress, this);
				
				SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(r.Run));
				thd.Start();
			}
        public virtual void TestDuringAddIndexes_LuceneNet()
        {
            MockRAMDirectory dir1   = new MockRAMDirectory();
            IndexWriter      writer = new IndexWriter(dir1, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);

            writer.SetInfoStream(infoStream);
            writer.SetMergeFactor(2);

            // create the index
            CreateIndexNoClose(false, "test", writer);
            writer.Commit();

            Directory[] dirs = new Directory[10];
            for (int i = 0; i < 10; i++)
            {
                dirs[i] = new MockRAMDirectory(dir1);
            }

            IndexReader r = writer.GetReader();

            int   NUM_THREAD = 5;
            float SECONDS    = 3;

            long endTime = (long)((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000.0 * SECONDS);

            System.Collections.IList excs = (System.Collections.IList)System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(new System.Collections.ArrayList()));

            SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[NUM_THREAD];
            for (int i = 0; i < NUM_THREAD; i++)
            {
                threads[i] = new AnonymousClassThread(endTime, writer, dirs, excs, this);
                threads[i].IsBackground = true;
                threads[i].Start();
            }

            int lastCount = 0;

            while ((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) < endTime)
            {
                using (IndexReader r2 = writer.GetReader())
                {
                    Query q     = new TermQuery(new Term("indexname", "test"));
                    int   count = new IndexSearcher(r2).Search(q, 10).TotalHits;
                    Assert.IsTrue(count >= lastCount);
                    lastCount = count;
                }
            }

            for (int i = 0; i < NUM_THREAD; i++)
            {
                threads[i].Join();
            }

            Assert.AreEqual(0, excs.Count);
            r.Close();
            Assert.AreEqual(0, dir1.GetOpenDeletedFiles().Count);
            writer.Close();

            _TestUtil.CheckIndex(dir1);

            dir1.Close();
        }
Exemple #36
0
        public virtual void  runTest(Directory directory, bool autoCommit, MergeScheduler merger)
        {
            IndexWriter writer = new IndexWriter(directory, autoCommit, ANALYZER, true);

            writer.SetMaxBufferedDocs(2);
            if (merger != null)
            {
                writer.SetMergeScheduler(merger);
            }

            for (int iter = 0; iter < NUM_ITER; iter++)
            {
                int iterFinal = iter;

                writer.SetMergeFactor(1000);

                for (int i = 0; i < 200; i++)
                {
                    Document d = new Document();
                    d.Add(new Field("id", System.Convert.ToString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    d.Add(new Field("contents", English.IntToEnglish(i), Field.Store.NO, Field.Index.ANALYZED));
                    writer.AddDocument(d);
                }

                writer.SetMergeFactor(4);
                //writer.setInfoStream(System.out);

                int docCount = writer.DocCount();

                SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[NUM_THREADS];

                for (int i = 0; i < NUM_THREADS; i++)
                {
                    int         iFinal      = i;
                    IndexWriter writerFinal = writer;
                    threads[i] = new AnonymousClassThread(writerFinal, iFinal, iterFinal, this);
                }

                for (int i = 0; i < NUM_THREADS; i++)
                {
                    threads[i].Start();
                }

                for (int i = 0; i < NUM_THREADS; i++)
                {
                    threads[i].Join();
                }

                Assert.IsTrue(!failed);

                int expectedDocCount = (int)((1 + iter) * (200 + 8 * NUM_ITER2 * (NUM_THREADS / 2.0) * (1 + NUM_THREADS)));

                // System.out.println("TEST: now index=" + writer.segString());

                Assert.AreEqual(expectedDocCount, writer.DocCount());

                if (!autoCommit)
                {
                    writer.Close();
                    writer = new IndexWriter(directory, autoCommit, ANALYZER, false);
                    writer.SetMaxBufferedDocs(2);
                }

                IndexReader reader = IndexReader.Open(directory);
                Assert.IsTrue(reader.IsOptimized());
                Assert.AreEqual(expectedDocCount, reader.NumDocs());
                reader.Close();
            }
            writer.Close();
        }
		/*
		* Wait until the reader thread ID matches the specified parameter.
		* Null = wait for the reader to terminate
		* Non Null = wait for the reader to start
		* Returns when the ID matches, i.e. reader stopped, or reader started.
		*
		* @param the thread id to match
		*/
		private void  waitForReader(SupportClass.ThreadClass thread)
		{
			// wait for previous reader thread to terminate
			System.Threading.Thread rInst;
			System.Threading.Thread tInst;
			if(reader!=null)
			{
				rInst=reader.Instance;
			}
			else
			{
				rInst=null;
			}

			if(thread!=null)
			{
				tInst=thread.Instance;
			}
			else
			{
				tInst=null;
			}
//			while (reader != thread)
			while (!Object.Equals(rInst,tInst))
			{
				// Don't initialize connection while previous reader thread still
				// active.
				try
				{
					/*
					* The reader thread may start and immediately terminate.
					* To prevent the waitForReader from waiting forever
					* for the dead to rise, we leave traces of the deceased.
					* If the thread is already gone, we throw an exception.
					*/
					if (thread == deadReader)
					{
						if (thread == null)
						/* then we wanted a shutdown */
							return ;
						System.IO.IOException lex = deadReaderException;
						deadReaderException = null;
						deadReader = null;
						// Reader thread terminated
						throw new LdapException(ExceptionMessages.CONNECTION_READER, LdapException.CONNECT_ERROR, null, lex);
					}
					lock (this)
					{
						System.Threading.Monitor.Wait(this, TimeSpan.FromMilliseconds(5));
					}
				}
				catch (System.Threading.ThreadInterruptedException ex)
				{
					;
				}
				if(reader!=null)
				{
					rInst=reader.Instance;
				}
				else
				{
					rInst=null;
				}

				if(thread!=null)
				{
					tInst=thread.Instance;
				}
				else
				{
					tInst=null;
				}

			}
			deadReaderException = null;
			deadReader = null;
			return ;
		}
		public virtual void  TestDocumentsWriterExceptionThreads()
		{
			Analyzer analyzer = new AnonymousClassAnalyzer2(this);
			
			int NUM_THREAD = 3;
			int NUM_ITER = 100;
			
			for (int i = 0; i < 2; i++)
			{
				MockRAMDirectory dir = new MockRAMDirectory();
				{
					IndexWriter writer = new IndexWriter(dir, analyzer);
					
					int finalI = i;
					
					SupportClass.ThreadClass[] threads = new SupportClass.ThreadClass[NUM_THREAD];
					for (int t = 0; t < NUM_THREAD; t++)
					{
						threads[t] = new AnonymousClassThread(NUM_ITER, writer, finalI, this);
						threads[t].Start();
					}
					
					for (int t = 0; t < NUM_THREAD; t++)
						while (true)
							try
							{
								threads[t].Join();
								break;
							}
							catch (System.Threading.ThreadInterruptedException)
							{
								SupportClass.ThreadClass.Current().Interrupt();
							}
					
					writer.Close();
				}
				
				IndexReader reader = IndexReader.Open(dir);
				int expected = (3 + (1 - i) * 2) * NUM_THREAD * NUM_ITER;
				Assert.AreEqual(expected, reader.DocFreq(new Term("contents", "here")));
				Assert.AreEqual(expected, reader.MaxDoc());
				int numDel = 0;
				for (int j = 0; j < reader.MaxDoc(); j++)
				{
					if (reader.IsDeleted(j))
						numDel++;
					else
						reader.Document(j);
					reader.GetTermFreqVectors(j);
				}
				reader.Close();
				
				Assert.AreEqual(NUM_THREAD * NUM_ITER, numDel);
				
				IndexWriter writer2 = new IndexWriter(dir, analyzer);
				writer2.SetMaxBufferedDocs(10);
				Document doc = new Document();
				doc.Add(new Field("contents", "here are some contents", Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
				for (int j = 0; j < 17; j++)
					writer2.AddDocument(doc);
				writer2.Optimize();
				writer2.Close();
				
				reader = IndexReader.Open(dir);
				expected += 17 - NUM_THREAD * NUM_ITER;
				Assert.AreEqual(expected, reader.DocFreq(new Term("contents", "here")));
				Assert.AreEqual(expected, reader.MaxDoc());
				numDel = 0;
				for (int j = 0; j < reader.MaxDoc(); j++)
				{
					if (reader.IsDeleted(j))
						numDel++;
					else
						reader.Document(j);
					reader.GetTermFreqVectors(j);
				}
				reader.Close();
				Assert.AreEqual(0, numDel);
				
				dir.Close();
			}
		}
		/// <summary>Starts the Receiver in a new thread </summary>
		public virtual void  start()
		{
			running = true;
			SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
			thd.Start();
		}
Exemple #40
0
		internal virtual void  AcquireWrite()
		{
			lock (this)
			{
				System.Diagnostics.Debug.Assert(writeThread != SupportClass.ThreadClass.Current());
				while (writeThread != null || readCount > 0)
					DoWait();
				
				// We could have been closed while we were waiting:
				EnsureOpen();
				
				writeThread = SupportClass.ThreadClass.Current();
			}
		}
Exemple #41
0
 /// <summary> Creates a new thread used to run the audio player.
 /// </summary>
 /// <returns> A new Thread that, once started, runs the audio player.
 /// 
 /// </returns>
 protected internal virtual SupportClass.ThreadClass createPlayerThread()
 {
     SupportClass.ThreadClass temp_Thread;
     temp_Thread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
     temp_Thread.Name = "Audio player thread";
     return temp_Thread;
 }
Exemple #42
0
		internal virtual void  ReleaseWrite()
		{
			lock (this)
			{
				System.Diagnostics.Debug.Assert(SupportClass.ThreadClass.Current() == writeThread);
				writeThread = null;
				System.Threading.Monitor.PulseAll(this);
			}
		}
Exemple #43
0
 /// <summary> Stops the audio player. If the player is already stopped
 /// this method is a no-op.  
 /// </summary>
 protected internal virtual void stopPlayer()
 {
     if (player != null)
     {
         player.close();
         player = null;
         playerThread = null;
     }
 }
Exemple #44
0
		// Allows one readLock to upgrade to a writeLock even if
		// there are other readLocks as long as all other
		// readLocks are also blocked in this method:
		internal virtual void  UpgradeReadToWrite()
		{
			lock (this)
			{
				System.Diagnostics.Debug.Assert(readCount > 0);
				upgradeCount++;
				while (readCount > upgradeCount || writeThread != null)
				{
					DoWait();
				}
				
				writeThread = SupportClass.ThreadClass.Current();
				readCount--;
				upgradeCount--;
			}
		}
		public virtual void  Init(IndexReader reader)
		{
			this.reader = reader;
			timeElapsed = 0;
			t = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
			t.Start();
		}
        public void Test()
        {
            SupportClass.ThreadClass thread = new SupportClass.ThreadClass();

            //Compare Current Thread Ids
            Assert.IsTrue(SupportClass.ThreadClass.Current().Instance.ManagedThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId);


            //Compare instances of ThreadClass
            MyThread mythread = new MyThread();
            mythread.Start();
            while (mythread.Result == null) System.Threading.Thread.Sleep(1);
            Assert.IsTrue((bool)mythread.Result);


            SupportClass.ThreadClass nullThread = null;
            Assert.IsTrue(nullThread == null); //test overloaded operator == with null values
            Assert.IsFalse(nullThread != null); //test overloaded operator != with null values
        }
Exemple #47
0
		public virtual void  TestThreadSafety()
		{
			rnd = NewRandom();
			int numThreads = 5;
			int numDocs = 50;
			ByteArrayPool pool = new ByteArrayPool(numThreads, 5);
			
			Directory dir = new RAMDirectory();
			IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
			System.String field = "test";
			
			SupportClass.ThreadClass[] ingesters = new SupportClass.ThreadClass[numThreads];
			for (int i = 0; i < numThreads; i++)
			{
				ingesters[i] = new AnonymousClassThread(numDocs, field, pool, writer, this);
				ingesters[i].Start();
			}
			
			for (int i = 0; i < numThreads; i++)
			{
				ingesters[i].Join();
			}
			writer.Close();
			IndexReader reader = IndexReader.Open(dir);
			TermEnum terms = reader.Terms();
			while (terms.Next())
			{
				TermPositions tp = reader.TermPositions(terms.Term());
				while (tp.Next())
				{
					int freq = tp.Freq();
					for (int i = 0; i < freq; i++)
					{
						tp.NextPosition();
						Assert.AreEqual(pool.BytesToString(tp.GetPayload(new byte[5], 0)), terms.Term().text_ForNUnit);
					}
				}
				tp.Close();
			}
			terms.Close();
			reader.Close();
			
			Assert.AreEqual(pool.Size(), numThreads);
		}
 private void ListenForMessages()
 {
     if (listeningThread == null)
     {
         IThreadRunnable messageReader = new SessionThread(this);
         listeningThread = new SupportClass.ThreadClass(new System.Threading.ThreadStart(messageReader.Run), "FAST Session Message Reader");
     }
     if (listeningThread.IsAlive)
         return ;
     listeningThread.Start();
 }
Exemple #49
0
        internal void sendMessage()
        {
            conn.writeMessage(this);
            // Start the timer thread
            if (mslimit != 0)
            {
                // Don't start the timer thread for abandon or Unbind
                switch (msg.Type)
                {

                    case LdapMessage.ABANDON_REQUEST:
                    case LdapMessage.UNBIND_REQUEST:
                        mslimit = 0;
                        break;

                    default:
                        timer = new Timeout(this, mslimit, this);
                        timer.IsBackground = true; // If this is the last thread running, allow exit.
                        timer.Start();
                        break;

                }
            }
            return ;
        }
		/// <summary>startReader
		/// startReader should be called when socket and io streams have been
		/// set or changed.  In particular after client.Connection.startTLS()
		/// It assumes the reader thread is not running.
		/// </summary>
		/* package */
		internal void  startReader()
		{
			// Start Reader Thread
			SupportClass.ThreadClass r =new SupportClass.ThreadClass(new System.Threading.ThreadStart(new ReaderThread(this).Run));
//			Thread r = new Thread(new ThreadStart(new ReaderThread(this).Run));
			r.IsBackground = true; // If the last thread running, allow exit.
			r.Start();
			waitForReader(r);
			return ;
		}
Exemple #51
0
 /// <summary>Starts the Receiver in a new thread </summary>
 public virtual void  start()
 {
     running = true;
     SupportClass.ThreadClass thd = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
     thd.Start();
 }
Exemple #52
0
			private void  InitBlock()
			{
				threads = new SupportClass.ThreadClass[NUM_THREADS];
			}
Exemple #53
0
 private void  InitBlock(TestIndexWriterReader enclosingInstance)
 {
     this.enclosingInstance = enclosingInstance;
     threads = new SupportClass.ThreadClass[NUM_THREADS];
 }
			private void  InitBlock(TestIndexWriterReader enclosingInstance)
			{
				this.enclosingInstance = enclosingInstance;
				threads = new SupportClass.ThreadClass[NUM_THREADS];
			}