© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
B. Feigenbaum, Ph.D.Go for Java Programmershttps://doi.org/10.1007/978-1-4842-7199-5_12

12. Key Package Comparison

Barry Feigenbaum, Ph.D.1  
(1)
Austin, TX, USA
 

Several key (frequently and widely used) Java packages are summarized in this chapter. When practical, any equivalent Go package or function is noted. As Go and Java are not one to one in their available libraries, a full match of every Java API (method) with a Go equivalent, if it exists at all in the standard Go libraries, is impractical.

Java Lang Packages

Java Standard Edition (JSE) has many bundled packages with types and methods. The available methods (aka APIs) number into the several thousands. Go also has a set of standard packages with types and functions that number into the many hundreds. There is a significant overlap in library behavior but not the organizational structure (in which package, type, or function a behavior is located) between these sets of packages and types.

It would take 100s of pages just to list (vs. describe) all the JSE packages and their contained types with methods. This book will not attempt to do this. Instead, it will list a select subset of the JSE packages and types. For some of these, it will compare the methods available for key Java types with any Go equivalents.

The JRE has some key types in the java.lang package. The following lists describe any Go environment equivalents.

Interface Summary
  • Appendable – Can append to instances of this type; implicitly supported by a Go slice.

  • AutoCloseable – Can be closed by try with resources; no direct Go equivalent.

  • CharSequence – A sequence of characters (such as a String or StringBuilder); no direct Go equivalent.

  • Cloneable – Implements Object.clone(); no direct Go equivalent.

  • Comparable<T> – Can support a compareTo() method; no direct Go equivalent; many types are implicitly comparable.

  • Iterable<T> – Can be iterated; some Go types: array, slice, map, channel.

  • Readable – Can read characters into a buffer; io.Reader for UTF-8.

  • Runnable – Can be run as a thread body; in Go, any function can be run as a goroutine.

Class Summary
  • Boolean – Boolean wrapper; not needed on Go collections.

  • Byte – Byte wrapper; not needed on Go collections.

  • Character – Char wrapper; not needed on Go collections.

  • Class<T> – A runtime view of a class; a feature for reflection; Go has a reflection package.

  • ClassLoader – Loads/manages classes at runtime; not needed in Go, no runtime classes.

  • Double – Double wrapper; not needed on Go collections.

  • Enum<E extends Enum<E>> – Base type of all enum types; not needed in Go (int is the base of most Go enums).

  • Float – Float wrapper; not needed on Go collections.

  • Integer – Int wrapper; not needed on Go collections.

  • Long – Long wrapper; not needed on Go collections.

  • Math – A class with a set of math utilities; Go has a similar math package.

  • Module – A runtime view of a module; no direct Go equivalent.

  • Number – A superclass of numeric wrapper types; no direct Go equivalent.

  • Object – A superclass of all object types; no direct Go equivalent; interface{} is closest.

  • Package – A runtime view of a package; no direct Go equivalent.

  • Process – A runtime view of an external program; a Go exec package has similar.

  • ProcessBuilder – A helper to run an external program; a Go exec package has similar.

  • Record (new) – A structure like class; Go has the struct type.

  • Runtime – Utilities to manage a running program; Go has a runtime package.

  • RuntimePermission – Means to control access to a function in classes; Go has no equivalent.

  • SecurityManager – Means to control access to a function in classes; Go has no equivalent.

  • Short – Short wrapper; not needed on Go collections.

  • StackTraceElement – Describes a call stack element; Go has a similar struct type.

  • StackWalker – Crawls a stack; no direct Go equivalent; one can be written.

  • StrictMath – Like a Math class with more rules on how the algorithms work; no direct Go equivalent.

  • String – A string type; Go has a string type and strings, strconv, and fmt packages.

  • StringBuffer, StringBuilder – A mutable string type; Go has a strings.Builder type.

  • System – Utilities to manage a running program; Go has runtime, time, and io packages.

  • Thread – An operating system thread; no direct Go equivalent; go has goroutines.

  • ThreadGroup – A collection of related threads; no direct Go equivalent.

  • ThreadLocal<T> – A variable with thread-dependent values; no direct Go equivalent; can be made.

  • Throwable – A type that can be thrown; Go has panics.

  • Void – No Go equivalent; Go functions can return nothing (vs. void).

  • math.BigInteger – Indefinite precision integer; Go has a math.Int type.

  • math.BigDecimal – Indefinite precision decimal float value; Go has math.Float (but it is binary, not decimal).

The System class:

Static Field Summary
  • PrintStream err – STDERR – Go os.Stderr

  • InputStream in – STDIN – Go os.Stdin

  • PrintStream out – STDOUT – Go os.Stdout

Method Summary. No direct Go equivalent if not mentioned.
  • arraycopy(…) – Copy an array; Go operator: array[:] and copy(..) function

  • clearProperty(String key) – Empty system property

  • console() – Get access to the OS console

  • currentTimeMillis() – Get the current Epoch time; Go time.Now()

  • exit(…) – See the Runtime class; Go os.Exit(...)

  • gc() – See the Runtime class; Go runtime.GC()

  • getenv() – Get all Environment values; Go os.Environ()

  • getenv(…) – Get a single Environment value

  • getLogger(…) – Get a named logger ; Go log package

  • getProperties() – Get all properties

  • getProperty(…) – Get a named property

  • getSecurityManager() – Get a JVM security manager

  • identityHashCode(Object x) – Get an object’s identity; in Go, use the &x operator

  • lineSeparator() – Get an OS line separator (e.g., NL, CR+NL)

  • load(…), loadLibrary(…) – See the Runtime class

  • nanoTime() – Get elapsed time in nanoseconds; Go time package

  • runFinalization() – See the Runtime class

  • setErr(…) – Change STDERR

  • setIn(…) – Change STDIN

  • setOut(…) – Change STDOUT

  • setProperties(Properties props) – Set many system properties

  • setProperty(String key, String value) – Set the system property

  • setSecurityManager(…) – Set a JVM security manager

There are community implementations of properties. See github.com/magiconair/properties for an example which uses a Java property–like file format.

The Runtime class:
  • addShutdownHook(…) – Run a thread at the exit of JVM; no direct Go equivalent; Go can trap OS signals; Go can trap panics.

  • availableProcessors() – Get CPU (core) count; Go runtime.NumCPU().

  • exec(...) – Family of methods to launch external process; Go exec.Cmd.

  • exit(…) – Exit the JVM with cleanup; no Go equivalent; Go can approx. by using os.Exit().

  • freeMemory() – Get free memory available to JVM; Go runtime.MemStats.

  • gc() – Run a garbage collection; Go runtime.GC ().

  • getRuntime() – Get this class’s singleton; no Go equivalent.

  • halt(…) – Exit JVM with no cleanup; Go os.Exit(...).

  • load(…), loadLibrary​(…) – Load a foreign code library; no Go equivalent.

  • maxMemory()– Get maximum memory available to JVM; Go runtime.MemStats.

  • removeShutdownHook(…) – Remove the exit hook; no Go equivalent.

  • runFinalization() – Force Object finalization; no Go equivalent.

  • totalMemory() – Get memory used by JVM; Go runtime.MemStats.

  • version() – Get the JVM version; Go runtime.version().

Since Go is a complete executable made at build time, there is no need for loading system libraries.

Java IO Package

The JRE has some key classes in the java.io package. The following lists describe any Go environment equivalents.

Interface Summary
  • Closeable – Can be closed. Used by try with resources; no direct Go equivalent.

  • DataInput – Data can be read as a stream of binary encoded values. Some Go encoding libraries provide a similar function.

  • DataOutput – Data can be written as a stream of binary encoded values. Some Go encoding libraries provide a similar function.

  • Externalizable – Data can be read/written to a stream using non-standard encoding; no direct Go equivalent.

  • FileFilter – Select directory paths matching a filter callback; no direct Go equivalent.

  • FilenameFilter – Select file names matching a filter callback; no direct Go equivalent.

  • Flushable – Can flush (persist buffered data); some Go io package interfaces provide this operation.

  • ObjectInput – Can read Java serialized objects (superset of DataInput); no direct Go equivalent.

  • ObjectOutput – Can write Java serialized objects (superset of DataOutput); no direct Go equivalent.

  • Serializable – Declares a type as serializable by the default encoding; no direct Go equivalent.

  • Class Summary

  • BufferedInputStream – Input stream (on bytes) with buffer; the Go bufio package provides similar support.

  • BufferedOutputStream – Output stream (on bytes) with buffer; the Go bufio package provides similar support.

  • BufferedReader – Input writer (on characters) with buffer; the Go bufio package provides similar support.

  • BufferedWriter – Output writer (on characters) with buffer; the Go bufio package provides similar support.

  • ByteArrayInputStream – Read from byte[]; the Go io package provides similar support.

  • ByteArrayOutputStream – Write on byte[]; the Go io package provides similar support.

  • CharArrayReader – Write on char[]; the Go io package provides similar support.

  • CharArrayWriter – Write on char[]; the Go io package provides similar support.

  • Console – Abstraction of STDIN, STDOUT, and STDERR; the Go io package provides similar support.

  • DataInputStream – Read a stream of binary encoded values; some Go encoding libraries provide a similar function.

  • DataOutputStream – Write a stream of binary encoded values; some Go encoding libraries provide a similar function.

  • File – Access to a file (or directory); Go io and os packages provide similar support.

  • FileDescriptor – Access to host OS files; Go io and os packages provide similar support.

  • FileInputStream – Read bytes from a file; Go io and os packages provide similar support.

  • FileOutputStream – Write bytes to a file; Go io and os packages provide similar support.

  • FilePermission – Access file permissions; Go io and os packages provide similar support.

  • FileReader – Read characters from a file; Go io and os packages provide similar support.

  • FileWriter – Write characters to a file; Go io and os packages provide similar support.

  • InputStream – Read bytes; Go io and os packages provide similar support.

  • InputStreamReader – Convert byte input to character input; Go io and os packages provide similar support.

  • ObjectInputStream – Read serialized objects; no direct Go equivalent.

  • ObjectOutputStream – Write serialized objects; no direct Go equivalent.

  • OutputStream – Write bytes; Go io and os packages provide similar support.

  • OutputStreamWriter – Convert characters to bytes.

  • PrintStream – Formatted byte output; Go fmt, io, and os packages provide similar support.

  • PrintWriter – Formatted character output; Go fmt, io, and os packages provide similar support.

  • RandomAccessFile – A file that supports seeking; Go io and os packages provide similar support.

  • Reader – Read characters; Go fmt, io, and os packages provide similar support.

  • SequenceInputStream – Concatenate input streams; Go io and os packages provide similar support.

  • StreamTokenizer – Tokenize stream input; Go fmt, io, and os packages provide similar support.

  • StringReader – Read characters from a string; Go fmt, io, and os packages provide similar support.

  • Writer – Write characters; Go io and os packages provide similar support.

Java also has a NIO (new IO) package with more advanced file (e.g., monitor file changes) and directory services. This book will not cover them. The Go libraries have some functions comparable to those offered by a few of NIO classes.

Java Text Package

The JRE has some key classes in the java.text package. This package provides bidirectional iteration over text sequences and message formatting. The following lists describe any Go environment equivalents. Some Go extension libraries and community libraries provide similar support.

Interface Summary
  • AttributedCharacterIterator – Bidirectional iteration over attributed text sequences; no direct Go equivalent.

  • CharacterIterator – Bidirectional iteration over text sequences; no direct Go equivalent; utf8 and utf16 packages have some function.

Class Summary. Unless noted, Go has no direct equivalents.
  • Annotation – Annotation-like text attributes.

  • AttributedString – String with annotations.

  • Bidi – Provides bidirectional traversal rules.

  • BreakIterator – Iterates to different types of breaks (word, line, etc.).

  • ChoiceFormat – Helps to format messages with varying counts and plurals.

  • CollationElementIterator – Walks across characters in under locale rules.

  • CollationKey – Key for locale-based collation.

  • Collator – Base class for locale-based collation.

  • CompactNumberFormat – Decimal format that makes numbers smaller.

  • DateFormat – Formats dates and times; Go has a time package for a similar function.

  • DecimalFormat – Formats decimal numbers.

  • Format – Base class for various Format classes.

  • MessageFormat – Formats messages with substitutions.

  • Normalizer – Normalizes Unicode text to assist with collation.

  • NumberFormat – Base class for number formatters.

  • RuleBasedCollator – Rules table driver collator.

  • SimpleDateFormat – Date format with configurable structures for dates and times; Go has a time package for a similar function.

  • StringCharacterIterator – Iterates over characters in a string.

Note Go’s fmt package can be used to do some of the roles of the various Format types. Also, in Java String.format() and in Go fmt.Sprintf() can do much of what the formatters do.

Java Time Packages

The JRE has some key classes in the java.time package and its sub-packages. The following lists describe any Go environment equivalents.

Interface Summary. Go has the time package for some of these; mostly as functions, not types; only a small subset of this function is present in Go. Some Go extension libraries and community libraries provide similar support.
  • ChronoLocalDate – A Date in some Chronology

  • ChronoLocalDateTime<D extends ChronoLocalDate> – A Date Time (timestamp) in some Chronology

  • Chronology – A calendar system (say Gregorian)

  • ChronoPeriod – A time period

  • ChronoZonedDateTime<D extends ChronoLocalDate>> – A time zoned Date Time (timestamp) in some Chronology

  • Era – A bounded range in some Chronology (e.g., BCE)

  • Temporal – Of Time; following for manipulating dates and times

  • TemporalAccessor

  • TemporalAdjuster

  • TemporalAmount

  • TemporalField

  • TemporalQuery<R>

  • TemporalUnit

Class Summary. Go has the time package for some of the behaviors included as follows; mostly as functions, not types.
  • Clock – Access to dates and times

  • Duration – A span of time; Go has a Duration type

  • Instant – A moment in time

  • LocalDate – A date in the local time zone

  • LocalDateTime – A date and time (aka timestamp) in the local time zone

  • LocalTime – A time in the local time zone

  • MonthDay – A day in a month

  • OffsetDateTime – A date and time (aka timestamp) offset from UTC

  • OffsetTime – A time offset from UTC

  • Period – A duration in calendar units

  • Year – A duration in years

  • YearMonth – An instant at month resolution

  • ZonedDateTime – A DateTime in a time zone

  • DateTimeFormatter – Formats a Date Time

  • DateTimeFormatterBuilder – Makes a formatter

  • AbstractChronology – Base for Chronologies (calendar system)

  • HijrahChronology, HijrahDate, IsoChronology

  • JapaneseChronology, JapaneseDate, JapaneseEra

  • MinguoChronology, MinguoDate

  • ThaiBuddhistChronology, ThaiBuddhistDate

Java Util Packages

The JRE has some key classes in the java.util package and its sub-packages. The sub-packages deal with collections of objects, legacy dates, and time processing, concurrent (threaded) processing, and concurrent access to objects. The following lists describe any Go environment equivalents.

Interface Summary. Most have no direct Go equivalents. Much of this function is provided by Go built-in types. Some Go extension libraries and community libraries provide similar support.
  • Collection<E> – Iterate able collection of type E.

  • Comparator<T> – Compare two comparable objects of type T.

  • Deque<E> – Double-ended queue of type E; the Go slice is close.

  • Enumeration<E> – Supports forward iteration over a collection of type E.

  • EventListener – Formalize the type of an event listener (call back).

  • Formattable – Can be formatted.

  • Iterator<E> – Supports bidirectional iteration over a collection of type E.

  • List<E> – Indexable collection of type E; the Go slice is close.

  • Map<K,​V>, Map.Entry<K,​V> – Associative collection of type V with key K; the Go map is close.

  • Queue<E> – A queue (FIFO) of type E; the Go slice is close.

  • Set<E> – A set of type K; the Go map is close.

  • SortedMap<K,​V> – Map with sorted keys.

  • SortedSet<E> – Set with sorted elements.

Class Summary. Most have no direct Go equivalents.
  • AbstractCollection<E> – The following are base implementations of the type.

  • AbstractList<E>

  • AbstractMap<K,​V>

  • AbstractQueue<E>

  • AbstractSequentialList<E>

  • AbstractSet<E>

  • ArrayDeque<E> – Deque on an array.

  • ArrayList<E> – List on an array; Go has a slice type.

  • Arrays – Helpers for array access.

  • Base64.Decoder – Decode Base64 strings; Go has a base64 package.

  • Base64.Encoder – Encode Base64 strings; Go has a base64 package.

  • BitSet – Set of bits; Go has a bits package.

  • Calendar – A calendar; Go has a time package.

  • Collections – Helpers for collections.

  • Currency – A currency.

  • Date – A date; Go has a time package.

  • Dictionary<K,​V> – A basic map type; Go has a map type.

  • EnumMap<K extends Enum<K>,​V>

  • EnumSet<E extends Enum<E>>

  • EventListenerProxy<T extends EventListener>

  • EventObject

  • Formatter

  • GregorianCalendar – Western calendar.

  • HashMap<K,​V> – Default map type; Go has a map type.

  • HashSet<E> – Default set type.

  • Hashtable<K,​V> – Thread-safe HashMap.

  • IdentityHashMap<K,​V> – Map with Object identities as keys; Go has a map[uintptr] type.

  • LinkedHashMap<K,​V> – Map iterated in addition order.

  • LinkedHashSet<E> – Set iterated in addition order.

  • LinkedList<E> – List backed by a linked list.

  • Locale – Define locale-sensitive settings and behavior.

  • Objects – Helps for all reference types.

  • Optional<T> – A null-safe wrapper.

  • PriorityQueue<E> – List sorted by priority.

  • Properties – A key/value collection with a persistent form.

  • Scanner – Reads formatted input; Go fmt package.

  • SimpleTimeZone – A time zone implementation.

  • Stack<E> – List processed in LIFO order.

  • StringJoiner – String helper.

  • StringTokenizer – Simple string parser; Go fmt package.

  • Timer – Drive events (callbacks) at intervals.

  • TimerTask – Drive events (callbacks) at intervals.

  • TimeZone – Base for time zones.

  • TreeMap<K,​V> – Map sorted by keys.

  • TreeSet<E> – Set sorted by keys.

  • UUID – UUID type; available from third parties.

  • Vector<E> – Thread-safe ArrayList.

  • WeakHashMap<K,​V> – Map that does not prevent GC of keys.

  • Interface Summary

  • BlockingDeque<E> – Deque with multiple consumer threads.

  • BlockingQueue<E> – Queue with multiple consumer threads.

  • Callable<V> – A thread can call asynchronously.

  • ConcurrentMap<K,​V> – Thread-safe high concurrency map.

  • ConcurrentNavigableMap<K,​V> – Thread-safe high concurrency map.

  • Executor – Manager of multiple threads.

  • ExecutorService – Manages multiple threads.

  • Flow.Processor<T,​R> – Reactive programming flow processor.

  • Flow.Publisher<T> – Reactive programming flow publisher.

  • Flow.Subscriber<T> – Reactive programming flow subscriber.

  • Flow.Subscription – Reactive programming flow subscription.

  • Future<V> – Asynchronous task that can complete in the future.

  • Condition – Externalized Condition with lock; Go sync.Cond.

  • Lock – Lock access to critical section; Go sync.Mutex.

  • ReadWriteLock – Multiple read, single write Lock.

Class Summary. Partial or full implementations of the preceding interfaces. Names generally describe the function. Many have no direct Go equivalents. The LoadX and StoreX functions provide behavior like the Java volatile modifier.
  • AbstractExecutorService

  • ArrayBlockingQueue<E>

  • CompletableFuture<T>

  • ConcurrentHashMap<K,​V>

  • ConcurrentLinkedDeque<E>

  • ConcurrentLinkedQueue<E>

  • ConcurrentSkipListMap<K,​V>

  • ConcurrentSkipListSet<E>

  • CopyOnWriteArrayList<E>

  • CopyOnWriteArraySet<E>

  • CountDownLatch – Wait for count; Go sync.WaitGroup is similar.

  • CyclicBarrier – Allows multiple threads to reach synchronization points.

  • DelayQueue<E extends Delayed> – Queue of Delayed (enable at certain time).

  • Exchanger<V> – Allows threads to swap items.

  • Executors – Creates managers of multiple threads.

  • ForkJoinPool – Divide and conquer in multiple threads.

  • Future<V> – Asynchronous task that can complete in the future.

  • LinkedBlockingDeque<E>

  • LinkedBlockingQueue<E>

  • LinkedTransferQueue<E>

  • Phaser – Thread synchronization; enhanced CyclicBarrier or CountDownLatch.

  • PriorityBlockingQueue<E>

  • ScheduledThreadPoolExecutor

  • Semaphore – Basic controlled access to critical sessions; Go has a lock package.

  • SynchronousQueue<E>

  • ThreadPoolExecutor

  • AtomicBoolean – Atomic allows safe read-modify-write cycles across threads; Go has an async package.

  • AtomicInteger – Go has an async package.

  • AtomicIntegerArray

  • AtomicIntegerFieldUpdater<T>

  • AtomicLong – Go has an async package.

  • AtomicLongArray

  • AtomicLongFieldUpdater<T>

  • AtomicMarkableReference<V>

  • AtomicReference<V> – Go has an async package.

  • AtomicReferenceArray<E>

  • AtomicReferenceFieldUpdater<T,​V>

  • AtomicStampedReference<V>

  • DoubleAccumulator – Accumulators/adders support safe read-modify-write cycles across threads.

  • DoubleAdder – Go has an async package.

  • LongAccumulator – Go has an async package.

  • LongAdder– Go has an async package.

  • LockSupport – Locking helpers.

  • ReentrantLock – Lock implementation.

  • ReentrantReadWriteLock

Note locks (and synchronized access) in Java is reentrant; the same thread can acquire the lock multiple times. In Go, locks are not reentrant, and the same goroutine trying to reacquire a lock can block (deadlock) itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.106.100