Avoid Injecting Closable Resources · google/guice Wiki · GitHub



Avoid Injecting Closable Resources · google/guice Wiki · GitHub

There are a number of issues with this approach as it relates to resource management:

  • If multiple Client classes are constructed, multiple output streams are opened against the same file, and writes to the file may clash with eachother.
  • It's not clear which class has the responsibility of closing the FileOutputStream resource:
    • If the resource is created for the sole ownership of Client, then it makes sense for the client to close it.
    • However, if the resource is scoped (e.g.: you add @Singleton to the @Provides method), then suddenly it's not the responsibility of Client to close the resource. If one Client closes the stream, then all of the other users of that stream will be dealing with a closed resource. There needs to be some other 'resource manager' object that also gets that stream, and its closing functions are call in the right place. That can be tricky to do correctly.
  • If, for example, the construction of the other dependencies of Client fails (resulting in a ProvisionException), then the FileOutputStream that may have been constructed leaks and isn't properly closed, even if Client normally closes its resources correctly.

The preferred solution is to not inject closable resources, but instead, objects that can expose short-lived closable resources that are used as necessary. The following example uses Guava's CharSource as the resource manager object:


Read full article from Avoid Injecting Closable Resources · google/guice Wiki · GitHub


java - Javadoc @see or {@link}? - Stack Overflow



java - Javadoc @see or {@link}? - Stack Overflow

The functional differences are:

  • {@link} is an inline link and can be placed wherever you like
  • @see creates its own section

In my opinion, {@link} is best used when you literally use a class, field, constructor or method name in your description. The user will be able to click through to the javadoc of what you've linked.

I use the @see annotation in 2 cases:

  • Something is very relevant but not mentioned in the description.
  • I refer to the same thing multiple times in the description, and it is used as a replacement for multiple links to the same.

I based this opinion on randomly checking out documentation for a great variety of things in the


Read full article from java - Javadoc @see or {@link}? - Stack Overflow


Injection and inheritance - Google Groups



Injection and inheritance - Google Groups

I'm trying to find the best way to inject into an inheritance hierarchy.

The base class takes one "live" parameter ("name", not injectable) and a bunch of injected dependencies, "dep1", "dep2", etc. The most obvious solution is to use assisted injection:

public class Base {
  private Dep1 dep1;
  private String name;

  protected Base(String name, Dep1 dep1) {
    this.name = name;
    this.dep1 = dep1;
  }
}

public class A extends Base {
  public interface IFactory {
    A create(@Assisted("name") String name);
  }

  @Inject
  private A(String name, Dep1 dep1) {
    super(name, dep1);
  }
}

Two things bother me with this approach:
  1. It's a lot of boiler plate. Each new subclass needs to create its own factory, its own constructor with all the dependencies, call super with all these dependencies and add itself to the FactoryModuleBuilder.

  2. If I add a new dependency in the base class, I need to modify all the subclasses (add a parameter to their constructor and to their super() call).
I considered passing the injector as the sole dependency to the base class and let the base class do its own look ups:

public class Base {
  private Dep1 dep1;
  private String name;

  protected Base(String name, Injector inj) {
    this.name = name;
    this.dep1 = inj.getInstance(Dep1.class);
  }
}

public class A extends Base {
  public interface IFactory {
    A create(@Assisted("name") String name);
  }

  @Inject
  public A(String name, Injector inj) {
    super(name, inj);
  }

This addresses point 2: when a new dependency is added to the base class, only the base class needs to be modified, but it's still awkward to do these look ups manually (and injectMembers() doesn't work since we're in the constructor).

This still doesn't address point 1: there's still a lot of boiler plate involved for each subclass.

Is there a better way?

If not, can we discuss this as a potential new feature?

Read full article from Injection and inheritance - Google Groups


(22) Which is the correct way to say it: worth to do or worth doing? - Quora



(22) Which is the correct way to say it: worth to do or worth doing? - Quora

Something is worth doing, worth seeing, worth remembering, and so on. The whole expression "worth ____ing" behaves as an adjective.

E.g. That rule is worth remembering. That pie was not worth eating.

"Worth to do" is never part of a grammatically correct expression. What you may have heard is "It's worth it to do," and not noticed the "it," because it is unstressed.

"Worth it" is an idiomatic phrase that functions as an adjective meaning "worth some unspecified or implicit cost, discomfort, or effort.

Examples

That dish took a long time to cook, but the result was worth it! (worth the time it took)

This brand of shampoo is expensive but worth it. (worth the extra expense)

Now, there is a transformation in English under which

(gerund) is (adjective) becomes It's (adjective)(infinitive).

Under this transformation,

"Cleaning up after dinner is nice" becomes "It's nice to clean up after dinner."

"Cleaning up after dinner is useless" becomes "It's useless to clean up after dinner."

and

"Cleaning up after dinner is worth it" becomes "It's worth it to clean up after dinner."

This is how we end up with both "It's worth doing your homework," and "It's worth it to do your homework." But never, ever say, "It's worth to do your homework."


Read full article from (22) Which is the correct way to say it: worth to do or worth doing? - Quora


Selecting the JDK version the IDE will run under – IDEs Support (IntelliJ Platform) | JetBrains



Selecting the JDK version the IDE will run under – IDEs Support (IntelliJ Platform) | JetBrains

  1. Start the IDE, use Help | Find Action (Ctrl+Shift+A or Cmd+Shift+A on Mac), type "Switch IDE Boot JDK", press Enter.
  2. Switch IDE Boot JDK dialog appears. Select the version from the drop-down or click "…" entry to specify the custom location. This location has to point to the JDK installation home directory (like c:\Program Files (x86)\Java\jdk1.8.0_112 or /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/ or /usr/lib/jvm/open-jdk).
  3. Please note that using JetBrains Runtime is highly recommended for performance and stability reasons (it fixes many known OpenJDK and Oracle JDK bugs).
  4. Selected location is stored inside the idea.config.path\<product>.jdk file, should you need to revert to the default behavior in case of any problem (like when IDE no longer starts), delete this file or modify the installation path inside.


Read full article from Selecting the JDK version the IDE will run under – IDEs Support (IntelliJ Platform) | JetBrains


java - When to use a Singleton and when to use a static class - Software Engineering Stack Exchange



java - When to use a Singleton and when to use a static class - Software Engineering Stack Exchange

A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance. I've done similar things where a set of common utility functions that are used in multiple places in an application are grouped together into a single utility class.

A singleton is used when you do want an actual object (with its own internal state and everything), and you want to limit your system to exactly one instance of that object. This might be useful if you have some kind of shared resource, such as a database, an in-memory cache, or maybe some specialized piece of hardware like a robotic arm. Many parts of your program might want to use this resource and you might want to have all access to the resource go through a single point. A singleton isn't always the only way to handle these situations, but it's one of the few places I think a singleton might be a good choice.


Read full article from java - When to use a Singleton and when to use a static class - Software Engineering Stack Exchange


EqualsIncompatibleType



EqualsIncompatibleType

An equality test between objects with incompatible types always returns false

Severity
WARNING
Has Fix?
NO_FIX

The problem

Consider the following code:

String x = "42";  Integer y = 42;  if (x.equals(y)) {    System.out.println("What is this, Javascript?");  } else {    System.out.println("Types have meaning here.");  }  

We understand that any Integer will not be equal to any String. However, the signature of the equals method accepts any Object, so the compiler will happily allow us to pass an Integer to the equals method. However, it will always return false, which is probably not what we intended.

This check detects circumstances where the equals method is called when the two objects in question can never be equal to each other. We check the following equality methods:

  • java.lang.Object.equals(Object)
  • java.util.Objects.equals(Object, Object)
  • com.google.common.base.Objects.equal(Object, Object)

I'm trying to test to make sure my equals method works

Good! Many tests of equals methods neglect to test that equals on an unrelated object return false.

We recommend using Guava's EqualsTester to perform tests of your equals method. Simply give it a collection of objects of your class, broken into groups that should be equal to each other, and EqualsTester will ensure that:

  • Each object is equal to each other object in the same group as that object
  • Each object is equal to itself
  • Each object is unequal to all of the other objects not in the group
  • Each object is unequal to an unrelated object (Relevant to this check)
  • Each object is unequal to null
  • The hashCode of each object in a group is the same as the hash code of each other member of the group


Read full article from EqualsIncompatibleType


Why overloading a varargs method doesn't work for the primitive type and its object wrapper type?



Why overloading a varargs method doesn't work for the primitive type and its object wrapper type?

Example I does not compile. The error is "The method operation(String, Integer[]) is ambiguous for the type Program".

At compile time a vararg is converted to an array. In example I, 1 will be converted to an int array with 1 as the only element, something like int[] a={1}; with the autoboxing, 1 can also be converted to an Integer array, something like Integer [] b={1}; so if the Program class had only one operation() method, either method would work fine.

On the other hand, for method overloading to work, the compiler needs to figure out which method is the most-specific method. We already know that if the args are fixed, like in Example II:


Read full article from Why overloading a varargs method doesn't work for the primitive type and its object wrapper type?


Method Overloading and Ambiguity in Varargs in Java - GeeksforGeeks



Method Overloading and Ambiguity in Varargs in Java - GeeksforGeeks

Method Overloading in Varargs

Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. We can overload a method that takes a variable-length argument by following ways:

  • Case 1 – Methods with only Varargs parameters: In this case, Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error.

Read full article from Method Overloading and Ambiguity in Varargs in Java - GeeksforGeeks


Live Stream Encoding | TO THE NEW Blog



Live Stream Encoding | TO THE NEW Blog

In this blog, we have listed the steps to create a set-up using which we can capture live streaming from source camera & pass it to any streaming device which includes mobile, browser or smart-tv apps. Using this set-up, we can stream any live event like a conference, cricket match etc. 


Read full article from Live Stream Encoding | TO THE NEW Blog


Why is Generic Array Creation not Allowed in Java? | TO THE NEW Blog



Why is Generic Array Creation not Allowed in Java? | TO THE NEW Blog

To understand this topic let us directly start with an example.

List<Integer> arrayOfIntegerList[] = new ArrayList<>[10]; // compile time error !!

You will find that a simple statement like this will not even compile because the Java compiler does not allow this. To understand the reason, you first need to know two arrays are covariant and generics are invariant.

Covariant: It means you can assign subclass type array to its superclass array reference. For instance,

Object objectArray[] = new Integer[10]; // it will work fine

Invariant: It means you cannot assign subclass type generic to its super class generic reference because in generics any two distinct types are neither a subtype nor a supertype. For instance,

List<Object> objectList = new ArrayList<Integer>(); // won't compile

Because of this fundamental reason, arrays and generics do not fit well with each other.

Now let's get back to the actual question. If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.


Read full article from Why is Generic Array Creation not Allowed in Java? | TO THE NEW Blog


Fixing ugly Java APIs: read-only generic varargs - Christophe Beyls - Medium



Fixing ugly Java APIs: read-only generic varargs - Christophe Beyls - Medium

To sum it up, as soon as you want to put generic types in a Java array, you're on your own to guarantee the safety of your code and to prevent a ClassCastException from occurring at runtime. This is why collections should be preferred to arrays when dealing with generic types in Java. Changing the method signature to use a List<T> instead of T... would avoid compiler warnings and guarantee type safety at compile time:


Read full article from Fixing ugly Java APIs: read-only generic varargs - Christophe Beyls - Medium


The Complete Java Enums Tutorial with Examples - JavaBrahman



The Complete Java Enums Tutorial with Examples - JavaBrahman

All enum types are classes. When an enum type is compiled, then behind the scenes the compiler inserts a lot of boilerplate code which gives the enum type classes their 'special' nature. This boiler code provides features of a full blown class and object constants definitions based on just the enum definition. So, in effect the compiler is doing all the hard work involved in creating a type and its constants objects behind-the-scenes, and abstracting it all out as a simple enum type and constants definition. Thus, all a programmer needs to do is define a enum type and its constants, and the compiler does the rest automatically.


Read full article from The Complete Java Enums Tutorial with Examples - JavaBrahman


java - Static enum vs. Non-static enum - Stack Overflow



java - Static enum vs. Non-static enum - Stack Overflow

All enums are effectively static. If you have a nested enum, it is much the same as a static class.

All classes are lazily loaded (enums or otherwise) however when they are loaded they are loaded all at once. i.e. you can't have a few constants loaded but not others (except in the middle of class initialization)

Java allows certain modifiers to be implicit to avoid having to declare them all the time. This means that adding a modifier doesn't necessarily do anything other than provide a longer way of writing the same thing.

Default modifiers for

class field/method/nested class - package local, non-final, non-static

enum and nested enum - package local, final and static

interface field - public static final

interface method - public abstract

nested class in an interface - public static, non-final

Note: while static is optional for an enum it is always static. However, final cannot be set for an enum even though it is always notionally final (Technically you can have subclasses with overridden implementations for constants)

EDIT: The only place you need to use static with enum is with import static of an enum's value. Thank you @man910


Read full article from java - Static enum vs. Non-static enum - Stack Overflow


Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)



Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Because they are constants, the names of an enum type's fields are in uppercase letters.

In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:

public enum Day {      SUNDAY, MONDAY, TUESDAY, WEDNESDAY,      THURSDAY, FRIDAY, SATURDAY   }  

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.


Read full article from Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)


Using Google's Protocol Buffers With Java - DZone Java



Using Google's Protocol Buffers With Java - DZone Java

Effective Java, Third Edition was recently released, and I have been interested in identifying the updates to this classic Java development book, whose last edition only covered through Java 6. There are obviously completely new items in this edition that are closely related to Java 7, Java 8, and Java 9 such as Items 42 through 48 in Chapter 7 ("Lambdas and Streams"), Item 9 ("Prefer try-with-resources to try-finally"), and Item 55 ("Return optionals judiciously"). I was (very slightly) surprised to realize that the third edition of Effective Java had a new item not specifically driven by the new versions of Java, but that was instead was driven by developments in the software development world independent of the versions of Java. That item, Item 85 ("Prefer alternatives to Java Serialization") is what motivated me to write this introductory post on using Google's Protocol Buffers with Java.


Read full article from Using Google's Protocol Buffers With Java - DZone Java


Using Google's Protocol Buffers With Java - DZone Java



Using Google's Protocol Buffers With Java - DZone Java

In Item 85 of Effective Java, Third Edition, Josh Bloch emphasizes in bold text the following two assertions related to Java serialization:

  1. "The best way to avoid serialization exploits is to never deserialize anything."
  2. "There is no reason to use Java serialization in any new system you write."

After outlining the dangers of Java deserialization and making these bold statements, Bloch recommends that Java developers employ what he calls (to avoid confusion associated with the term "serialization" when discussing Java) "cross-platform structured-data representations." Bloch states that the leading offerings in this category are JSON (JavaScript Object Notation) and Protocol Buffers (protobuf). I found this mention of Protocol Buffers to be interesting because I've been reading about and playing with Protocol Buffers a bit lately. The use of JSON (even with Java) is exhaustively covered online. I feel like awareness of Protocol Buffers may be less among Java developers than awareness of JSON and so feel like a post on using Protocol Buffers with Java is warranted.


Read full article from Using Google's Protocol Buffers With Java - DZone Java


Binary Serialization with Google Protocol Buffers – grijjy blog



Binary Serialization with Google Protocol Buffers – grijjy blog

Google's Protocol Buffers are a flexible, compact and extensible mechanism for serializing structured data. We share our implementation that makes it easy to serialize Delphi records to a binary format that is 100% compatible with the Protocol Buffers specification.

Want to go straight to the source? You can find it on GitHub in our GrijjyFoundation repository in the single unit Grijjy.ProtocolBuffers.

Protocol Buffers?

In Google's own words: "Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler."

You can use it is a binary interchange format to send data over the wire, to communicate with 3rd party applications that support Protocol Buffers, or even to create a light weight but extensible file format.


Read full article from Binary Serialization with Google Protocol Buffers – grijjy blog


FluentAssertions and code formatting



FluentAssertions and code formatting

Recently I was playing with FluentAssertions library. I was really amazed by the beautiful error messages generated by FluentAssertions. For example, for this failing test:


Read full article from FluentAssertions and code formatting


How null's are handled in switch statement in C#, Java and JavaScript



How null's are handled in switch statement in C#, Java and JavaScript

In Java null's may show up in switch statement when we switch on primitive type wrappers like Integer or on String or on enum type. In that case Java will throw NullPointerException as is demonstrated by program:


Read full article from How null's are handled in switch statement in C#, Java and JavaScript


2 Best Chinese PinYin Input Method in Ubuntu 16.04 | UbuntuHandbook



2 Best Chinese PinYin Input Method in Ubuntu 16.04 | UbuntuHandbook

As a Chinese user, I have never used iBus PinYin in Ubuntu. For me, one of the first things to do after a new Ubuntu installation is to install a Input Method.

As I know, there are two best Chinese IM for Ubuntu:

  • Fcitx – A flexible Input Method framework
  • Sougou PinYin – the most popular Chinese IM.

Install and Setup Fcitx:

Fcitx is an open-source and powerful IM framework that provides: Google PinYin, ShuangPin, SunPinYin, Wubi, ZhengMa, Hong Kong and TaiWan Traditional Chinese input methods, and more.


Read full article from 2 Best Chinese PinYin Input Method in Ubuntu 16.04 | UbuntuHandbook


Ubuntu 10-17 Chinese input methods: Fcitx and IBus Pinyin, Chewing and more :: Pinyin Joe



Ubuntu 10-17 Chinese input methods: Fcitx and IBus Pinyin, Chewing and more :: Pinyin Joe

Before I show how to activate input methods, I should list and describe them. You will find many available immediately after installing the fcitx or IBus frameworks. Others can be added later. (For input method problems in Ubuntu 13.10 and 14.xx, please see the FAQ on that topic.)

Ubuntu 10.04 and 10.10 input methodsIBus Pinyin iconThe Pinyin input method supports Simplified and Traditional characters in the mainland standard GB encoding. This IME seems similar to Google Pinyin (and less like Sogou Pinyin now that the apostrophes are gone).

SunPinyin IME iconThe SunPinyin input method was added as an alternative PRC IME beginning with Ubuntu 11.10. Developed at Sun Microsystems and now an open source project also adopted by the FIT folks, it is SLM (statistical language model) based and may be more accurate. I find it a bit more mature than some. But it too violates Pinyin parsing rules by inserting spaces between Pinyin as you type...and does it yet again by placing no space between "Sun" and "Pinyin" in the name.

Chewing IME iconThe Chewing input method offers Zhuyin ("chew-ing", get it?) and Hanyu Pinyin keyboards. Chewing is similar to Microsoft's New Phonetic / Bopomofo IME, but it's more 酷. :-) Long available for Traditional characters in the SCIM and IBus frameworks, in fcitx it can be used for Simplified characters as well.


Read full article from Ubuntu 10-17 Chinese input methods: Fcitx and IBus Pinyin, Chewing and more :: Pinyin Joe


ubuntu安装和卸载ibus和fcitx - 生气的代码的个人空间 - OSCHINA



ubuntu安装和卸载ibus和fcitx - 生气的代码的个人空间 - OSCHINA

3.安装fcitx

    (1)安装fcitx输入法框架:

sudo apt-get install fcitx

    (2)安装输入法:

sudo apt-get install fcitx-pinyin

    当然,也可以安装谷歌输入法(fcitx-googlepinyin)或是搜狐输入法(fcitx-sougupinyin)等。

    (3)配置fcitx,终端输入:

sudo  gedit ~/.bashrc

    然后添加内容并保存:

export XMODIFIERS="@im=fcitx"

    然后在终端继续输入(注意有2个点,2个点之间用空格分隔):


Read full article from ubuntu安装和卸载ibus和fcitx - 生气的代码的个人空间 - OSCHINA


How to remove ibus from Ubuntu 14.04 (Trusty Tahr)



How to remove ibus from Ubuntu 14.04 (Trusty Tahr)

To remove just ibus package itself from Ubuntu 14.04 (Trusty Tahr) execute on terminal:

sudo apt-get remove ibus

Uninstall ibus and it's dependent packages

To remove the ibus package and any other dependant package which are no longer needed from Ubuntu Trusty.

sudo apt-get remove --auto-remove ibus

Purging ibus

If you also want to delete configuration and/or data files of ibus from Ubuntu Trusty then this will work:

sudo apt-get purge ibus

To delete configuration and/or data files of ibus and it's dependencies from Ubuntu Trusty then execute:

sudo apt-get purge --auto-remove ibus

More information about apt-get remove

Advanced Package Tool, or APT, is a free software user interface that works with core libraries to handle the installation and removal of software on Debian, Ubuntu and other Linux distributions. APT simplifies the process of managing software on Unix-like computer systems by automating the retrieval, configuration and installation of software packages, either from precompiled files or by compiling source code.

apt-get is the command-line tool for handling packages, and may be considered the user's "back-end" to other tools using the APT library.

apt-get remove is identical to install except that packages are removed instead of installed. Note that removing a package leaves its configuration files on the system. If a plus sign is appended to the package name (with no intervening space), the identified package will be installed instead of removed.


Read full article from How to remove ibus from Ubuntu 14.04 (Trusty Tahr)


X Input Methods



X Input Methods

For entering text in CJK languages, simple keyboard typing is not adequate. Instead there are programs that run and handle the conversion of keystrokes to characters these programs are called input methods.

I have tested FontForge with two freely available input methods (as well as one can who speaks neither Chinese, Japanese nor Korean) kinput2 (for Japanese) and xcin (for Chinese).

There is reasonably good (English) documentation on installing and using kinput2 on the mozilla site, and at suse, kinput2 has the interesting complexity that it requires yet another server to be running, generally either cannaserver or jserver. It looks to me as though it might be possible to use a chinese or korean jserver with kinput2 but I have not tried this.

There is good Chinese and English documentation on xcin at the xcin site in Taiwan (english is not the default here, but it is available about 3 lines down).

One of the most difficult problems I had in installing these was finding the appropriate locales. I could not find them in my RedHat 7.3 distribution, nor could I find any RedHad rpms containing them. There is a good supply of Mandrake locale rpms (named locales-zh* for chinese, locales-jp* for japanese, etc.) but Mandrake stores them in a different directory so after installing them I had to copy them from /usr/share/locales to /usr/lib/locales. The SUSE docs imply that the current SUSE distribution ships with these locales.


Read full article from X Input Methods


[JDK-6506617] Keyboard-lock in swing program on Linux box - Java Bug System



[JDK-6506617] Keyboard-lock in swing program on Linux box - Java Bug System

FULL PRODUCT VERSION :
java version "1.6.0"
Java(TM) SE Runtime Environment (build 1.6.0-b105)
Java HotSpot(TM) Client VM (build 1.6.0-b105, mixed mode, sharing)

java version "1.5.0_10"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
Java HotSpot(TM) Client VM (build 1.5.0_10-b03, mixed mode, sharing)

ADDITIONAL OS VERSION INFORMATION :
RHEL 4 - Linux 2.6.9-42.ELsmp #1 SMP Wed Jul 12 23:27:17 EDT 2006 i686 i686 i386 GNU/Linux
Red Flag 5 - Linux 2.6.9-11.19AXsmp #1 SMP Fri Aug 5 05:28:32 EDT 2005 i686 i686 i386 GNU/Linux

EXTRA RELEVANT SYSTEM CONFIGURATION :
gnome-desktop-2.8.0-5
kdebase-3.2.1-62AX.i386. kdelibs-3.2.1-44AX.i386.


A DESCRIPTION OF THE PROBLEM :
Run some swing program, keyboard is locked after some opterations, then it don't respond any key event.

Here is a demo program, no multi-thread, no event-dispatching thread problem. It always can be reproduced on RHEL 4 and Red Flag 5.


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Run the program I post, follow the steps in "about":

1 - press Alt+N to navigate next, and don't release keys untill there are no more next page, then try Alt+B to navigate back and also don't release keys untill page 0, repeat Alt+N and Alt+B again and again, keyboard will be locked during navigating.

2 - press Alt+A in main window, it will popup an about dialog, then press down space key and don't release, the about dialog will be closed and opened again and again, keyboard will be locked sooner or later.

Read full article from [JDK-6506617] Keyboard-lock in swing program on Linux box - Java Bug System


grep - How to kill all process with given name? - Unix & Linux Stack Exchange



grep - How to kill all process with given name? - Unix & Linux Stack Exchange

The problem is that ps -A | grep <application_name> | xargs -n1 returns output like this

19440  ?  00:00:11  <application_name>  21630  ?  00:00:00  <application_name>  22694  ?  00:00:00  <application_name>  

You can use awk to a get first a column of ps output.

ps -A | grep <application_name> | awk '{print $1}' | xargs -n1  

Will return list of PIDs

19440  21630  22694  

And adding kill -9 $1 you have a command which kills all PIDs

ps -A | grep <application_name> | awk '{print $1}' | xargs kill -9 $1  

Read full article from grep - How to kill all process with given name? - Unix & Linux Stack Exchange


Catch Leak If You Can! - Paulina Szklarska - Medium



Catch Leak If You Can! - Paulina Szklarska - Medium

We have an inner class inside activity. In this inner class, we make some action delayed by 10 minutes. How long does the activity outside inner class lives? At least as long as the inner class. This is caused by a fact that inner class has a full access to the top-level class, including fields and methods (and context!). So what will happen if we run Handler delayed by 10 minutes inside inner class and close the InnerClassLeakActivity? Well, as long as the Handler lives, InnerClass must also live, and InnerClassLeakActivity also. So we'll have a memory leak for 10 minutes. It doesn't sound very bad, but imagine you have some repeating task in that Handler and your activity has a lot of heavy resources (images). This may end pretty bad.

What would be a fix for that? Using static nested class. It has its own lifecycle, independent from top-level class and thus doesn't cause potential memory leaks. To summarize:

  • don't make non-static nested classes that may live longer than Activity
  • try to replace non-static nested class with inner class


Read full article from Catch Leak If You Can! - Paulina Szklarska - Medium


Java Enum Examples | Novixys Software Dev Blog



Java Enum Examples | Novixys Software Dev Blog

Java has provided native enum types from version 1.5 onwards. Some issues arise with the use of enums in java code which this article attempts to address.

2. Enum Abstract Method

An enum type can have abstract methods just like a class. Each enum constant needs to implement the abstract method. An example follows:


Read full article from Java Enum Examples | Novixys Software Dev Blog


Switching between Online and Offline Services in Angular – 11th Hour



Switching between Online and Offline Services in Angular – 11th Hour

While working on angular applications, sometime you want your application to work both in online and offline mode. As the name says, the online mode is, the application can connect to the network, where the offline mode is, the application can't connect to the network.

Please note that a Service Worker implementation is needed to work an application offline. Explaining a service worker is beyond the scope of this blog, so we are'nt going to discuss it over here.

Here, we're going to see the codebase of an application, which works both Online and Offline. When the application is online, the data is sent to the backend, while in the offline mode, the data is sent to Indexed DB. The application itself recognizes the working mode also.

So, before each service request is being initiated, our application recognize which mode currently the application is running in, and decide which service (Offline or Online) os being called.


Read full article from Switching between Online and Offline Services in Angular – 11th Hour


Java Enum and Abstract Methods – 11th Hour



Java Enum and Abstract Methods – 11th Hour

I have found a useful tip while I was digging around the internet for a java business code. I am telling about using abstract methods inside an enum is very useful for implementing your business logic.

Before clear it up with examples about enum, let me tell few words about it.
An enum is a different type of class. The Java Language Specification says "There are two kinds of class declarations: normal class declarations and enum declarations. The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type".

An enum type is a subclass of java.Lang.Enum. An enum cannot extend anything else, but still it can implement other interfaces. Public or protected modifiers can only be used with a top-level enum declaration, but all access modifiers can be used with nested enum declarations. Also an enum type provides final methods like name, compareTo, hashCode etc. We can also use as well as override toString() method in an enum.

No more no less. You can read the documentation here. Also you could get the Java Language Specification about enum from here.

Now come to an example. This is my Country enum. You can find an abstract method getCurrency() inside enum. If an abstract method is declared inside enum, it must be overridden in all the enum constant bodies.


Read full article from Java Enum and Abstract Methods – 11th Hour


Guide to Google's Guava BiMap | Baeldung



Guide to Google's Guava BiMap | Baeldung

In this tutorial, we'll show how to use the Google Guava's BiMap interface and its multiple implementations.

A BiMap (or "bidirectional map") is a special kind of a map which maintains an inverse view of the map while ensuring that no duplicate values are present and a value can always be used safely to get the key back.

The basic implementation of BiMap is HashBiMap where internally it makes use of two Maps, one for the key to value mapping and the other for the value to key mapping.


Read full article from Guide to Google's Guava BiMap | Baeldung


java - Why is this such use of generic and wildcard not allowed? - Stack Overflow



java - Why is this such use of generic and wildcard not allowed? - Stack Overflow

List<? super Apple> means a List you can add an Apple to (and since Jonathan is an Apple, you can put Jonathans into a List of that type as well).

It can be List<Apple>, List<Fruit> or List<Object>, but not List<Jonathan>, since you cannot put arbitrary Apples into List<Jonathan>. As you can see, in this case ? can be an Apple or any of its superclasses.

List<? extends Apple> means a List you can get an Apple from. It can be List<Apple> or List<Jonathan>, but not List<Fruit>, since List<Fruit> is not guaranteed to contain only Apples.

This explanation is known as "producer - extends, consumer - super" rule: if parameter acts as a consumer of elements, it should be declared with super, and vice versa.


Read full article from java - Why is this such use of generic and wildcard not allowed? - Stack Overflow


为什么说“除非深思熟虑,尽量使用 notifyAll()”?



为什么说"除非深思熟虑,尽量使用 notifyAll()"?

当做多线程同步时,等待-通知机制是我们比较常用的一种选择,而 Java 中,等待-通知机制有多种实现,我们接触最早也是最熟悉的,应该就是 Java 语言内置的 synchronized 配合 wait()、notify()、notifyAll() 这三个方法来实现。

如何利用 synchronized 实现等待-通知机制,我想大家都比较熟悉,就无需多说了。notify()notifyAll() 都可以唤醒等待的线程,但是应该使用 notify() 还是 notifyAll() 就比较有争议了。

一种比较流行的说法就是,除非深思熟虑,否则尽量使用 notifyAll()

我们今天就这个问题,来讨论一下这两个方法如何选择。

二. 等待-通知机制

2.1 什么是等待通知机制

在此之前,先来聊聊什么是等待-通知机制,以及它能解决什么问题?

在使用并发编程时,利用多线程来提高任务的执行效率,但是每个线程在执行时,都有一些先决条件需要被满足。例如生产者消费者模式下,消费者线程能够执行的先决条件,就是生产者产生了一个待消费的数据。


Read full article from 为什么说"除非深思熟虑,尽量使用 notifyAll()"?


如何让Java应用成为杀不死的小强?(下篇)



如何让Java应用成为杀不死的小强?(下篇)

各位坐稳扶好,我们要开车了。不过在开车之前,我们还是例行回顾一下上期分享的要点。


经过前两期的铺垫及烧脑的分享,我们大概对「如何实现 Java 应用进程的状态监控,如果被监控的进程 down 掉,是否有机制能启动起来?」问题本身有了一个新的认识,那这期我们不妨拿出攻城狮的绝招 Ctrl + C、Ctrl + V,从 Resin 源码中摘取一二,稍微简单实践一下。



按照图示,咱们先演示一下实践效果吧,首先找到并运行程序入口 MonitorApp,日志输出如下。


此时我们不妨在控制台输入 jps 命令,看一看效果。


18830 MonitorApp

18831 Resin


发现成功启动了 MonitorApp、Resin 两个进程,和 Resin 应用服务器是一模一样的,如果我们把进程号为 18831 的 kill 掉,会是什么效果?发现控制台日志输出又多了一些,貌似丫鬟 Resin 又被重新给启动了。


Read full article from 如何让Java应用成为杀不死的小强?(下篇)


分布式金融的基础设施:如何驱动主流采用?



分布式金融的基础设施:如何驱动主流采用?

金融和科技结合之后,一直向更高效更低成本以及服务更多人的方向发展。从一开始金融公司的信息化到2008年之后出现真正的金融科技企业如Lenging Club等,到后来涌现更多互联网金融公司,开展基于互联网的保险、基金销售以及P2P网络借贷服务。

互联网金融给很多人带来回报,比如给理财方带来更高的收益,让很多原来无法获得贷款的用户获得了贷款服务。但同时出现了不少问题,比如P2P借贷的过高利息无法持续,尤其是小额借贷利息过高,借款人在多个平台借贷,拆东墙补西墙,行业风控走向失控,最后的结果是发生很多暴雷事件。当然,传统的金融并不比金融科技问题小,例如2008年由于次级抵押贷款引发全球金融危机。

而区块链的到来,给予金融科技一次跃迁的机会。例如比特币是一个没有任何中心主体发行的加密货币,它有透明的发行计划和发行量,在价值存储方面已经获得不少人认可。这是人类历史上第一个分布式的加密货币,给未来金融世界带来更多的选择和可能性。


Read full article from 分布式金融的基础设施:如何驱动主流采用?


并发面试必备系列之并发基础与内存模型 - 知乎



并发面试必备系列之并发基础与内存模型 - 知乎

《Awesome Interviews》 归纳的常见面试题中,无论前后端,并发与异步的相关知识都是面试的中重中之重,本系列即对于面试中常见的并发知识再进行回顾总结;你也可以前往 《Awesome Interviews》,在实际的面试题考校中了解自己的掌握程度。也可以前往《Java 实战》、《Go 实战》等了解具体编程语言中的并发编程的相关知识。

随着硬件性能的迅猛发展与大数据时代的来临,为了让代码运行得更快,单纯依靠更快的硬件已无法满足要求,并行和分布式计算是现代应用程序的主要内容;我们需要利用多个核心或多台机器来加速应用程序或大规模运行它们,并发编程日益成为编程中不可忽略的重要组成部分。

简单定义来看,如果执行单元的逻辑控制流在时间上重叠,那它们就是并发(Concurrent)的;由此定义可扩展到非常广泛的概念,其向下依赖于操作系统、存储等,与分布式系统、微服务等,而又会具体落地于 Java 并发编程、Go 并发编程、JavaScript 异步编程等领域。云计算承诺在所有维度上(内存、计算、存储等)实现无限的可扩展性,并发编程及其相关理论也是我们构建大规模分布式应用的基础。


Read full article from 并发面试必备系列之并发基础与内存模型 - 知乎


一篇文章深入gradle(上篇):依赖机制



一篇文章深入gradle(上篇):依赖机制

Hello,各位朋友们,小笨鸟又和你们见面啦。不同于网上泛泛而谈的入门文章只停留在"怎么用"的层次,本篇文章从源码角度去理解gradle。当然,如果你没有看过我的前一篇文章《一篇文章基本看懂gradle》,还是建议你先看一下,本篇文章的很多知识点会在上篇文章的基础上展开。

本篇文章会比较深入,需要费一些脑筋和精力才能理解。建议跟着我的行文思路一步一步理解。本文的篇幅会比较长。阅读大概需要花费半个小时。阅读本文将会了解:

  • gradle构建Lifecycle

  • gradle Extension和Plugin

  • gradle依赖实现,Configuration

其中gradle依赖将会是本文的重点。本来之前还想把artifact也讲解到,但是发现篇幅已经很长了,所以就一篇文章拆成两篇吧。

gradle构建Lifecycle

Lifecycle的概念我们在上一篇文章讲Project的时候也讲到过。在这篇文章中,我们会再简单讲一讲作为引入。


Read full article from 一篇文章深入gradle(上篇):依赖机制


一行代码完成 Java的 Execl 读写--easyexecl



一行代码完成 Java的 Execl 读写--easyexecl

最近我在 Github 上查找一个可以快速开发 Execl 导入导出工具,偶然发现由阿里开发 easyexecl 开源项目,尝试使用后感觉这款工具挺不错的,分享一下我的 easyexecl 案例使用。

1、easyexecl 简介
一般在项目可能会涉及到 Execl 导入和导出,通常我们都是使用 Apache POI 或者 jxl。但他们都存在一个严重的问题就是非常的耗内存,POI 有一套 SAX 模式的 API 可以一定程度的解决一些内存溢出的问题,但 POI 依旧存在一些缺陷,比如 07 版 Excel 解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。而 easyexcel 重写了 POI 对 07 版 Excel 的解析,能够原本一个 3M 的 Execl 用 POI SAX 依然需要 100M 左右内存降低到 KB 级别,并且再大的 Excel 不会出现内存溢出,03 版依赖 POI 的 SAX 模式。在上层做了模型转换的封装,使用起来更加方便。

Read full article from 一行代码完成 Java的 Execl 读写--easyexecl


并发扣款一致性,幂等性问题,这个话题还没聊完!!!



并发扣款一致性,幂等性问题,这个话题还没聊完!!!

并发扣款,如何保证数据的一致性?》,分享了同一个用户并发扣款时,有一定概率出现数据不一致,可以使用CAS乐观锁的方式,在不降低吞吐量,并且只有少量修改的情况下,保证数据的一致性。


文章发布不到24小时,就有近200的评论。

 
其中,问的比较多的是ABA问题,这个问题已经在《并发扣款一致性优化,CAS下ABA问题,这个话题还没聊完!!!》中扩展。
 
其次,问的比较多的是作业题,为什么一定要用select&set的方式进行余额写回

UPDATE t_yue SET money=$new_money WHERE uid=$uid AND money=$old_money;

 
为什么不能采用直接扣减的方法:

UPDATE t_yue SET money=money-$diff WHERE uid=$uid;

 
很人说,在并发情况下,会将money扣成负数

Read full article from 并发扣款一致性,幂等性问题,这个话题还没聊完!!!


锁优化的简单思路



锁优化的简单思路

在多核时代,多线程对系统的性能提升有着巨大的作用,但是多线程对系统也相应的产生了额外的开销,线程本身的数据、线程的调度、线程的申请释放等都对系统的产生额外的负担,锁是在高并发的环境下为了保证数据的正确性而产生的同步手段,为了进一步提升性能,我们就需要对锁进行优化。

锁的优化思路有:从减小锁的持有时间、锁的粒度的优化、锁分离、锁消除、无锁等等。

一、减小锁的持有时间

减小锁的持有时间是为了降低锁的冲突的可能性,提高体系的并发能力。

  • 1.1、只在必要时进行同步加锁操作


Read full article from 锁优化的简单思路


jdk13快来了,jdk8的这几点应该看看!



jdk13快来了,jdk8的这几点应该看看!

jdk8虽然出现很久了,但是可能我们还是有很多人并不太熟悉,本文主要就是介绍说明一些jdk8相关的内容。
主要会讲解:
  • lambda表达式
  • 方法引用
  • 默认方法
  • Stream
  • 用Optional取代null
  • 新的日志和时间
  • CompletableFuture
  • 去除了永久代(PermGen) 被元空间(Metaspace)代替


Read full article from jdk13快来了,jdk8的这几点应该看看!


给Java程序员的20个链表面试题



给Java程序员的20个链表面试题

数据结构在程序面试中极其重要。链表则是对数组数据结构进行的补充,是另一种常见的数据结构。和数组相似的是,链表也是线性数据结构,并以线性方式储存元素。


但是,和数组不同的是,链表不将元素储存在连续的位置;相反,其元素分散在内存中的各个地方,并以节点进行相互连接。


链表不过是一个节点的列表,其中每一个节点都包含存储的值和下一个节点的位置。


正是因为其结构,在链表中添加与删除元素变得尤为简单,比起创建数组,它只需要简单的更改链接。但是搜索难度很大,且通常需要增加等同的时间成本(随着数据量的增大)才能在一个单一链表内找到某个元素。


此文章给出了更多数组与链表数据结构之间的差异:http://javarevisited.blogspot.sg/2013/07/difference-between-array-and-linked-list-java.html


Read full article from 给Java程序员的20个链表面试题


给Java程序员的20个链表面试题



给Java程序员的20个链表面试题

今天,本文将详细介绍编程面试中常见的链表问题。


什么是链表?


数据结构在程序面试中极其重要。链表则是对数组数据结构进行的补充,是另一种常见的数据结构。和数组相似的是,链表也是线性数据结构,并以线性方式储存元素。


但是,和数组不同的是,链表不将元素储存在连续的位置;相反,其元素分散在内存中的各个地方,并以节点进行相互连接。


链表不过是一个节点的列表,其中每一个节点都包含存储的值和下一个节点的位置。


正是因为其结构,在链表中添加与删除元素变得尤为简单,比起创建数组,它只需要简单的更改链接。但是搜索难度很大,且通常需要增加等同的时间成本(随着数据量的增大)才能在一个单一链表内找到某个元素。


Read full article from 给Java程序员的20个链表面试题


Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts