• Complain

Scott Oaks - Java Threads

Here you can read online Scott Oaks - Java Threads full text of the book (entire story) in english for free. Download pdf and epub, get meaning, cover and reviews about this ebook. year: 2004, publisher: OReilly Media, genre: Computer. Description of the work, (preface) as well as reviews are available. Best literature library LitArk.com created for fans of good reading and offers a wide selection of genres:

Romance novel Science fiction Adventure Detective Science History Home and family Prose Art Politics Computer Non-fiction Religion Business Children Humor

Choose a favorite category and find really read worthwhile books. Enjoy immersion in the world of imagination, feel the emotions of the characters or learn something new for yourself, make an fascinating discovery.

Scott Oaks Java Threads

Java Threads: summary, description and annotation

We offer to read an annotation, description, summary or preface (depends on what the author of the book "Java Threads" wrote himself). If you haven't found the necessary information about the book — write in the comments, we will try to find it.

Threads are essential to Java programming, but learning to use them effectively is a nontrivial task. This new edition of the classic Java Threads shows you how to take full advantage of Javas threading facilities and brings you up-to-date with the watershed changes in Java 2 Standard Edition version 5.0 (J2SE 5.0). It provides a thorough, step-by-step approach to threads programming.Javas threading system is simple relative to other threading systems. In earlier versions of Java, this simplicity came with tradeoffs: some of the advanced features in other threading systems were not available in Java. J2SE 5.0 changes all that: it provides a large number of new thread-related classes that make the task of writing multithreaded programs that much easier.Youll learn where to use threads to increase efficiency, how to use them effectively, and how to avoid common mistakes. This book discusses problems like deadlock, race conditions, and starvation in detail, helping you to write code without hidden bugs.Java Threads, Third Edition, has been thoroughly expanded and revised. It incorporates the concurrency utilities from java.util.concurrent throughout. New chapters cover thread performance, using threads with Swing, threads and Collection classes, thread pools, and threads and I/O (traditional, new, and interrupted). Developers who cannot yet deploy J2SE 5.0 can use thread utilities provided in the Appendix to achieve similar functionality with earlier versions of Java.Topics include:Lock starvation and deadlock detection Atomic classes and minimal synchronization (J2SE 5.0) Interaction of Java threads with Swing, I/O, and Collection classes Programmatically controlled locks and condition variables (J2SE 5.0) Thread performance and security Thread pools (J2SE 5.0) Thread groups Platform-specific thread scheduling Task schedulers (J2SE 5.0) Parallelizing loops for multiprocessor machines In short, this new edition of Java Threads covers everything you need to know about threads, from the simplest animation program to the most complex applications. If you plan to do any serious work in Java, you will find this book invaluable.Scott Oaks is a senior software engineer for the Java Performance Engineering group at Sun Microsystems and the author of four books in the OReilly Java series. Formerly a senior systems engineer at Sun Microsystems, Henry Wong is an independent consultant working on various Java related projects.

Scott Oaks: author's other books


Who wrote Java Threads? Find out the surname, the name of the author of the book and a list of all author's works by series.

Java Threads — read online for free the complete book (whole text) full work

Below is the text of the book, divided by pages. System saving the place of the last page read, allows you to conveniently read the book "Java Threads" online for free, without having to search again every time where you left off. Put a bookmark, and you can go to the page where you finished reading at any time.

Light

Font size:

Reset

Interval:

Bookmark:

Make

[]

[]

accessalgorithms[See also interfaces][See APIs]arrays

[]

blocks

[]

classes[See collection classes]clientscompiling[See also race condition]

[]

[]

errorsexecution

[]

flags

[]

[]

[]

I/Oimplementationsinterfaces

[]

[]

keywords

[]

loops

[]

main memorymanagementmemorymethodsmodificationmultiple threads

[]

native threads[See also wait-and-notify mechanism]

[]

Swingoperating system (OS)[See operating system]

[]

patternsprinting

[]

queues

[]

[See also synchronization]running

[]

scalingserverssettingsharingsizesstacksSwing

[]

terminationtestingthreadsthreadsafetimetimeoutsTimer class

[]

[]

valuesvariables

[]

A.1 The BusyFlag Class

We'll start witha BusyFlag class:

package javathreads.examples.appa;public class BusyFlag { protected Thread busyflag = null; protected int busycount = 0; public synchronized void getBusyFlag( ) { while (tryGetBusyFlag( ) == false) { try { wait( ); } catch (Exception e) {} } } public synchronized boolean tryGetBusyFlag( ) { if (busyflag == null) { busyflag = Thread.currentThread( ); busycount = 1; return true; } if (busyflag == Thread.currentThread( )) { busycount++; return true; } return false; } public synchronized void freeBusyFlag( ) { if (getBusyFlagOwner( ) == Thread.currentThread( )) { busycount--; if (busycount == 0) { busyflag = null; notify( ); } } } public synchronized Thread getBusyFlagOwner( ) { return busyflag; }}

The BusyFlag class implements a basic, no-frills,mutually exclusive lock. It also allows the locks to benestedthe owner thread can lock the busy flag multiple times.It is much simpler than the ReentrantLock class. There is no internal support forcondition variables. There is no support for timeouts. There is noconcept of fairness in granting the busy flag. And our implementationdoes not attempt to minimize synchronization.

Simplistically, the purpose of this class is to useJava's basic synchronization mechanism to achieve,well, synchronization. This allows the program to lock at any scopeor for any purpose.

The BusyFlag class contains four methods. The tryGetBusyFlag() class is used to obtain a lock(a.k.a. the busyflag ). It grabs the busy flag ifit is available while returning false if the flagis already owned by another thread. It also allows nested locks byincrementing a counter if the current thread already owns the flag.The synchronized keyword is used to protectagainst race conditions while grabbing this flag.

The getBusyFlag() method uses the tryGetBusyFlag() method to repeatedly trygrabbing the flag until it is successful. If the flag is notavailable, it uses the wait-and-notify mechanism to wait for the flagto be returned. The freeBusyFlag() methoddecrements the counter. And if the counter is zero, this methoddeclares that the flag has no owner and notifies any threads that arewaiting to grab the flag.

The getBusyFlagOwner() method is merely anadministration method that allows a thread to determine who is theowner of the busy flag. Also note that due to a race condition, theresult that is returned is only guaranteed not to change if thecurrent thread is returned as the owner of the busy flag.

A.2 The CondVar Class

Here is an implementation ofthe CondVar class:

package javathreads.examples.appa;public class CondVar { private BusyFlag SyncVar; public CondVar( ) { this(new BusyFlag( )); } public CondVar(BusyFlag sv) { SyncVar = sv; } public void cvWait( ) throws InterruptedException { cvTimedWait(SyncVar, 0); } public void cvWait(BusyFlag sv) throws InterruptedException { cvTimedWait(sv, 0); } public void cvTimedWait(int millis) throws InterruptedException { cvTimedWait(SyncVar, millis); } public void cvTimedWait(BusyFlag sv, int millis) throws InterruptedException { int i = 0; InterruptedException errex = null; synchronized (this) { // You must own the lock in order to use this method if (sv.getBusyFlagOwner( ) != Thread.currentThread( )) { throw new IllegalMonitorStateException( "current thread not owner"); } // Release the lock (Completely) while (sv.getBusyFlagOwner( ) == Thread.currentThread( )) { i++; sv.freeBusyFlag( ); } // Use wait( ) method try { if (millis == 0) { wait( ); } else { wait(millis); } } catch (InterruptedException iex) { errex = iex; } } // Obtain the lock (Return to original state) for (; i>0; i--) { sv.getBusyFlag( ); } if (errex != null) throw errex; return; } public void cvSignal( ) { cvSignal(SyncVar); } public synchronized void cvSignal(BusyFlag sv) { // You must own the lock in order to use this method if (sv.getBusyFlagOwner( ) != Thread.currentThread( )) { throw new IllegalMonitorStateException( "current thread not owner"); } notify( ); } public void cvBroadcast( ) { cvBroadcast(SyncVar); } public synchronized void cvBroadcast(BusyFlag sv) { // You must own the lock in order to use this method if (sv.getBusyFlagOwner( ) != Thread.currentThread( )) { throw new IllegalMonitorStateException( "current thread not owner"); } notifyAll( ); }}

The CondVar class implements a basic conditionvariable for use with the BusyFlag class. There isno concept of fairness in notification. It is constructed separatelyfrom the BusyFlag classas compared to Condition objects, which are generated from the Lock class via the newCondition() method. And like the BusyFlag class,the implementation doesn't attempt to minimizesynchronization.

The purpose of this class is to allow Java'swait-and-notify mechanism to work with explicit locking (locks at anyscope). This allows the program to have condition variable supportfor the BusyFlag class. It also allows a singlelock to have more than one condition variable, where thewait-and-notify mechanism needs a separate object for every type ofnotification.

The CondVar class provides four methods forwaiting for notification; three of these methods can be consideredconvenience methods. The primary method is the cvTimedWait() method. This method frees the ownership of the busy flagcompletely and then uses the standard wait() method to perform the wait. If the time to wait is zero, this methodwaits indefinitely for the notification. Otherwise, it uses thetimeout specified. Upon returning, it grabs the lock (note that itmust do that as many times as the lock was released to support thenesting semantics of our BusyFlag class). Alsonote that it may still wait upon receiving notification as it canstill block while reacquiring the flag. In fact,that's the case with all notification-basedtechniques (the Condition class, thewait-and-notify mechanism); it's just in this codethat you see the effect explicitly.

Two of the convenience methods allow the program to specify a timeoutor wait indefinitely. The last one allows you to specify an alternatebusy flag classa flag that is different from the one specifiedduring construction. Specifying an alternate busy flag is not afeature supported by the Condition classa Condition instance is tightly bound to the Lock instance from which it was obtained. Thisfeature allows notification between two groups of threads that areoperating on different locks. In terms of functionality, this is aminor enhancement for a very rare need. Using the Condition class, a common Lock object could be created just for notification between the two groupsof threads to achieve the same thing.

The cvSignal() method is used to send a singlenotificationusing the notify() method. Aswith the wait methods, it is overloaded to allow the program tospecify an alternate busy flag. The cvBroadcast() method is used to send notifications to all the waitingthreadsusing the notifyAll() method. It,too, is overloaded to allow the program to specify an alternate busyflag.

A.3 The Barrier Class

Here is an implementation ofthe Barrier class:

package javathreads.examples.appa;public class Barrier { private int threads2Wait4; private InterruptedException iex; public Barrier (int nThreads) { threads2Wait4 = nThreads; } public synchronized int waitForRest( ) throws InterruptedException { int threadNum = --threads2Wait4; if (iex != null) throw iex; if (threads2Wait4 <= 0) { notifyAll( ); return threadNum; } while (threads2Wait4 > 0) { if (iex != null) throw iex; try { wait( ); } catch (InterruptedException ex) { iex = ex; notifyAll( ); } } return threadNum; } public synchronized void freeAll( ) { iex = new InterruptedException("Barrier Released by freeAll"); notifyAll( ); }}Next page
Light

Font size:

Reset

Interval:

Bookmark:

Make

Similar books «Java Threads»

Look at similar books to Java Threads. We have selected literature similar in name and meaning in the hope of providing readers with more options to find new, interesting, not yet read works.


Reviews about «Java Threads»

Discussion, reviews of the book Java Threads and just readers' own opinions. Leave your comments, write what you think about the work, its meaning or the main characters. Specify what exactly you liked and what you didn't like, and why you think so.