What are the three types of loader?

08 Apr.,2024

 

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java ClassLoader is one of the crucial but rarely used components in project development. I have never extended ClassLoader in any of my projects. But, the idea of having my own ClassLoader that can customize the Java class loading is exciting. This article will provide an overview of Java ClassLoader and then move forward to create a custom class loader in Java.

We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, JVM creates the bytecode, which is platform and machine-independent. The bytecode is stored in a .class file. When we try to use a class, the ClassLoader loads it into the memory.

There are three types of built-in ClassLoader in Java.

  1. Bootstrap Class Loader – It loads JDK internal classes. It loads rt.jar and other core classes for example java.lang.* package classes.
  2. Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
  3. System Class Loader – This classloader loads classes from the current classpath. We can set classpath while invoking a program using -cp or -classpath command line option.

ClassLoader is hierarchical in loading a class into memory. Whenever a request is raised to load a class, it delegates it to the parent classloader. This is how uniqueness is maintained in the runtime environment. If the parent class loader doesn’t find the class then the class loader itself tries to load the class. Let’s understand this by executing the below java program.

package com.journaldev.classloader;

public class ClassLoaderTest {

    public static void main(String[] args) {

        System.out.println("class loader for HashMap: "
                + java.util.HashMap.class.getClassLoader());
        System.out.println("class loader for DNSNameService: "
                + sun.net.spi.nameservice.dns.DNSNameService.class
                        .getClassLoader());
        System.out.println("class loader for this class: "
                + ClassLoaderTest.class.getClassLoader());

        System.out.println(com.mysql.jdbc.Blob.class.getClassLoader());

    }

}

Output:

class loader for HashMap: null
class loader for DNSNameService: sun.misc.Launcher$ExtClassLoader@7c354093
class loader for this class: sun.misc.Launcher$AppClassLoader@64cbbe37
sun.misc.Launcher$AppClassLoader@64cbbe37

Let’s understand the working of class loaders from the above program output.

  • The java.util.HashMap ClassLoader is coming as null, which reflects Bootstrap ClassLoader. The DNSNameService class ClassLoader is ExtClassLoader. Since the class itself is in CLASSPATH, System ClassLoader loads it.
  • When we are trying to load HashMap, our System ClassLoader delegates it to the Extension ClassLoader. The extension class loader delegates it to the Bootstrap ClassLoader. The bootstrap class loader finds the HashMap class and loads it into the JVM memory.
  • The same process is followed for the DNSNameService class. But, the Bootstrap ClassLoader is not able to locate it since it’s in $JAVA_HOME/lib/ext/dnsns.jar. Hence, it gets loaded by Extensions Classloader.
  • The Blob class is included in the MySql JDBC Connector jar (mysql-connector-java-5.0.7-bin.jar), which is present in the build path of the project. It’s also getting loaded by the System Classloader.
  • The classes loaded by a child class loader have visibility into classes loaded by its parent class loaders. So classes loaded by System Classloader have visibility into classes loaded by Extensions and Bootstrap Classloader.
  • If there are sibling class loaders then they can’t access classes loaded by each other.

Java default ClassLoader can load classes from the local file system, which is good enough for most of the cases. But, if you are expecting a class at the runtime or from the FTP server or via third party web service at the time of loading the class, then you have to extend the existing class loader. For example, AppletViewers load the classes from a remote web server.

  • When JVM requests for a class, it invokes loadClass() function of the ClassLoader by passing the fully classified name of the Class.
  • The loadClass() function calls the findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the same class multiple times.
  • If the Class is not already loaded, then it will delegate the request to parent ClassLoader to load the class.
  • If the parent ClassLoader doesn’t find the class then it will invoke findClass() method to look for the classes in the file system.

We will create our own ClassLoader by extending the ClassLoader class and overriding the loadClass(String name) method. If the class name will start from com.journaldev then we will load it using our custom class loader or else we will invoke the parent ClassLoader loadClass() method to load the class.

This is our custom class loader with below methods.

  1. private byte[] loadClassFileData(String name): This method will read the class file from file system to byte array.
  2. private Class<?> getClass(String name): This method will call the loadClassFileData() function and by invoking the parent defineClass() method, it will generate the Class and return it.
  3. public Class<?> loadClass(String name): This method is responsible for loading the class. If the class name starts with com.journaldev (Our sample classes) then it will load it using getClass() method or else it will invoke the parent loadClass() function to load it.
  4. public CCLoader(ClassLoader parent): This is the constructor, which is responsible for setting the parent ClassLoader.
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
 
/**
 * Our Custom ClassLoader to load the classes. Any class in the com.journaldev
 * package will be loaded using this ClassLoader. For other classes, it will delegate the request to its Parent ClassLoader.
 *
 */
public class CCLoader extends ClassLoader {
 
    /**
     * This constructor is used to set the parent ClassLoader
     */
    public CCLoader(ClassLoader parent) {
        super(parent);
    }
 
    /**
     * Loads the class from the file system. The class file should be located in
     * the file system. The name should be relative to get the file location
     *
     * @param name
     *            Fully Classified name of the class, for example, com.journaldev.Foo
     */
    private Class getClass(String name) throws ClassNotFoundException {
        String file = name.replace('.', File.separatorChar) + ".class";
        byte[] b = null;
        try {
            // This loads the byte code data from the file
            b = loadClassFileData(file);
            // defineClass is inherited from the ClassLoader class
            // that converts byte array into a Class. defineClass is Final
            // so we cannot override it
            Class c = defineClass(name, b, 0, b.length);
            resolveClass(c);
            return c;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * Every request for a class passes through this method. If the class is in
     * com.journaldev package, we will use this classloader or else delegate the
     * request to parent classloader.
     *
     *
     * @param name
     *            Full class name
     */
    @Override
    public Class loadClass(String name) throws ClassNotFoundException {
        System.out.println("Loading Class '" + name + "'");
        if (name.startsWith("com.journaldev")) {
            System.out.println("Loading Class using CCLoader");
            return getClass(name);
        }
        return super.loadClass(name);
    }
 
    /**
     * Reads the file (.class) into a byte array. The file should be
     * accessible as a resource and make sure that it's not in Classpath to avoid
     * any confusion.
     *
     * @param name
     *            Filename
     * @return Byte array read from the file
     * @throws IOException
     *             if an exception comes in reading the file
     */
    private byte[] loadClassFileData(String name) throws IOException {
        InputStream stream = getClass().getClassLoader().getResourceAsStream(
                name);
        int size = stream.available();
        byte buff[] = new byte[size];
        DataInputStream in = new DataInputStream(stream);
        in.readFully(buff);
        in.close();
        return buff;
    }
}

This is our test class with the main function. We are creating an instance of our ClassLoader and loading sample classes using its loadClass() method. After loading the class, we are using Java Reflection API to invoke its methods.

import java.lang.reflect.Method;
 
public class CCRun {
 
    public static void main(String args[]) throws Exception {
        String progClass = args[0];
        String progArgs[] = new String[args.length - 1];
        System.arraycopy(args, 1, progArgs, 0, progArgs.length);

        CCLoader ccl = new CCLoader(CCRun.class.getClassLoader());
        Class clas = ccl.loadClass(progClass);
        Class mainArgType[] = { (new String[0]).getClass() };
        Method main = clas.getMethod("main", mainArgType);
        Object argsArray[] = { progArgs };
        main.invoke(null, argsArray);

        // Below method is used to check that the Foo is getting loaded
        // by our custom class loader i.e CCLoader
        Method printCL = clas.getMethod("printCL", null);
        printCL.invoke(null, new Object[0]);
    }
 
}

These are our test classes that are getting loaded by our custom classloader. They have a printCL() method, which is getting invoked to print the ClassLoader information. Foo class will be loaded by our custom class loader. Foo uses Bar class, so Bar class will also be loaded by our custom class loader.

package com.journaldev.cl;
 
public class Foo {
    static public void main(String args[]) throws Exception {
        System.out.println("Foo Constructor >>> " + args[0] + " " + args[1]);
        Bar bar = new Bar(args[0], args[1]);
        bar.printCL();
    }
 
    public static void printCL() {
        System.out.println("Foo ClassLoader: "+Foo.class.getClassLoader());
    }
}
package com.journaldev.cl;
 
public class Bar {
 
    public Bar(String a, String b) {
        System.out.println("Bar Constructor >>> " + a + " " + b);
    }
 
    public void printCL() {
        System.out.println("Bar ClassLoader: "+Bar.class.getClassLoader());
    }
}

First of all, we will compile all the classes through the command line. After that, we will run the CCRun class by passing three arguments. The first argument is the fully classified name for Foo class that will get loaded by our class loader. Other two arguments are passed along to the Foo class main function and Bar constructor. The execution steps and the output will be like below.

$ javac -cp . com/journaldev/cl/Foo.java
$ javac -cp . com/journaldev/cl/Bar.java
$ javac CCLoader.java
$ javac CCRun.java
CCRun.java:18: warning: non-varargs call of varargs method with inexact argument type for last parameter;
cast to java.lang.Class<?> for a varargs call
cast to java.lang.Class<?>[] for a non-varargs call and to suppress this warning
Method printCL = clas.getMethod("printCL", null);
^
1 warning
$ java CCRun com.journaldev.cl.Foo 1212 1313
Loading Class 'com.journaldev.cl.Foo'
Loading Class using CCLoader
Loading Class 'java.lang.Object'
Loading Class 'java.lang.String'
Loading Class 'java.lang.Exception'
Loading Class 'java.lang.System'
Loading Class 'java.lang.StringBuilder'
Loading Class 'java.io.PrintStream'
Foo Constructor >>> 1212 1313
Loading Class 'com.journaldev.cl.Bar'
Loading Class using CCLoader
Bar Constructor >>> 1212 1313
Loading Class 'java.lang.Class'
Bar ClassLoader: CCLoader@71f6f0bf
Foo ClassLoader: CCLoader@71f6f0bf
$

If you look at the output, it’s trying to load com.journaldev.cl.Foo class. Since it’s extending java.lang.Object class, it’s trying to load Object class first. So the request is coming to CCLoader loadClass method, which is delegating it to the parent class. So the parent class loaders are loading the Object, String, and other java classes. Our ClassLoader is only loading Foo and Bar class from the file system. It’s clear from the output of the printCL() function. We can change the loadClassFileData() functionality to read the byte array from FTP Server or by invoking any third party service to get the class byte array on the fly. I hope that the article will be useful in understanding Java ClassLoader working and how we can extend it to do a lot more than just taking it from the file system.

We can make our custom class loader as the default one when JVM starts by using Java Options. For example, I will run the ClassLoaderTest program once again after providing the java classloader option.

$ javac -cp .:../lib/mysql-connector-java-5.0.7-bin.jar com/journaldev/classloader/ClassLoaderTest.java
$ java -cp .:../lib/mysql-connector-java-5.0.7-bin.jar -Djava.system.class.loader=CCLoader com.journaldev.classloader.ClassLoaderTest
Loading Class 'com.journaldev.classloader.ClassLoaderTest'
Loading Class using CCLoader
Loading Class 'java.lang.Object'
Loading Class 'java.lang.String'
Loading Class 'java.lang.System'
Loading Class 'java.lang.StringBuilder'
Loading Class 'java.util.HashMap'
Loading Class 'java.lang.Class'
Loading Class 'java.io.PrintStream'
class loader for HashMap: null
Loading Class 'sun.net.spi.nameservice.dns.DNSNameService'
class loader for DNSNameService: sun.misc.Launcher$ExtClassLoader@24480457
class loader for this class: CCLoader@38503429
Loading Class 'com.mysql.jdbc.Blob'
sun.misc.Launcher$AppClassLoader@2f94ca6c
$

The CCLoader is loading the ClassLoaderTest class because its in com.journaldev package.

You can download the ClassLoader example code from our GitHub Repository.

Heavy equipment machine

For the Australian rock band, see Front End Loader

John Deere Front end loaders CAD model tracing of a tractor mounted loader mechanism CAD model tracing of a skid loader mechanism

A loader is a heavy equipment machine used in construction to move or load materials such as soil, rock, sand, demolition debris, etc. into or onto another type of machinery (such as a dump truck, conveyor belt, feed-hopper, or railroad car).

There are many types of loader, which, depending on design and application, are variously called a bucket loader, end loader, front loader, front-end loader, payloader, high lift, scoop, shovel dozer, skid-steer, skip loader, tractor loader or wheel loader.

Description

[

edit

]

Loader removing snow in Jyväskylä, Finland

A loader is a type of tractor, usually wheeled, sometimes on tracks, that has a front-mounted wide bucket connected to the end of two booms (arms) to scoop up loose material from the ground, such as dirt, sand or gravel, and move it from one place to another without pushing the material across the ground. A loader is commonly used to move a stockpiled material from ground level and deposit it into an awaiting dump truck or into an open trench excavation.

The loader assembly may be a removable attachment or permanently mounted. Often the bucket can be replaced with other devices or tools—for example, many can mount forks to lift heavy pallets or shipping containers, and a hydraulically opening "clamshell" bucket allows a loader to act as a light dozer or scraper. The bucket can also be augmented with devices like a bale grappler for handling large bales of hay or straw.

Large loaders, such as the Kawasaki 95ZV-2, John Deere 844K, ACR 700K Compact Wheel Loader, Caterpillar 950H, Volvo L120E, Case 921E, or Hitachi ZW310 usually have only a front bucket and are called front loaders, whereas small loader tractors are often also equipped with a small backhoe and are called backhoe loaders or loader backhoes or JCBs, after the company that first claimed to have invented them. Other companies like CASE in America and Whitlock in the UK had been manufacturing excavator loaders well before JCB.

A Cat 908M at a landscape supply store in San Marcos.

The largest loader in the world is LeTourneau L-2350. Currently these large loaders are in production in the Longview, Texas facility. The L-2350 uses a diesel-electric propulsion system similar to that used in a locomotive.[1] Each rubber tired wheel is driven by its own independent electric motor.

Loaders are used mainly for loading materials into trucks, laying pipe, clearing rubble, and digging. A loader is not the most efficient machine for digging as it cannot dig very deep below the level of its wheels, like a backhoe or an excavator can. The capacity of a loader bucket can be anywhere from 0.5 to 36 m3[2] depending upon the size of the machine and its application. The front loader's bucket capacity is generally much bigger than a bucket capacity of a backhoe loader.

Traction chains on a wheel loader

Unlike most bulldozers, most loaders are wheeled and not tracked, although track loaders are common. They are successful where sharp-edged materials in construction debris would damage rubber wheels, or where the ground is soft and muddy. Wheels provide better mobility and speed and do not damage paved roads as much as tracks, but provide less traction.

In construction areas loaders are also used to transport building materials such as bricks, pipe, metal bars, and digging tools over short distances.

Front-loaders are commonly used to remove snow especially from sidewalks, parking lots, and other areas too small for using snowplows and other heavy equipment. They are sometimes used as snowplows with a snowplow attachment but commonly have a bucket or snow basket, which can also be used to load snow into the rear compartment of a snowplow or dump truck.

High-tip buckets are suitable for light materials such as chip, peat and light gravel and when the bucket is emptied from a height.

Close-up of articulated steering apparatus

Unlike backhoes or standard tractors fitted with a front bucket, many large loaders do not use automotive steering mechanisms. Instead, they steer by a hydraulically actuated pivot point set exactly between the front and rear axles. This is referred to as "articulated steering" and allows the front axle to be solid, allowing it to carry greater weight. Articulated steering provides better maneuverability for a given wheelbase. Since the front wheels and attachment rotate on the same axis, the operator is able to "steer" his load in an arc after positioning the machine, which can be useful. The tradeoff is that when the machine is "twisted" to one side and a heavy load is lifted high, it has a greater risk of turning over to the "wide" side.

Front end loader grapple

Front loaders gained popularity during the last two decades, especially in urban engineering projects and small earthmoving works. Heavy equipment manufacturers offer a wide range of loader sizes and duties.

The term "loader" is also used in the debris removal field to describe the boom on a grapple truck.

Major components

[

edit

]

The major components included in a loader are the engine (diesel in almost all cases), the hydraulic components (such as pumps, motors and valves) and the transmission components (gearbox, axles, wheels/tracks, pumps, motors, etc.). The engine runs both the hydraulics and the transmission, and these in turn move the front attachment (a bucket, forks, sweeper, etc.) to manipulate the material being handled, and the wheels or tracks to move the machine around the jobsite.

Wheel loaders

[

edit

]

The first wheel loader was invented by Volvo Construction Equipment in 1954, it was called H10.[3] Back then it was based on a tractor and had a rear wheel drive. Today wheel loaders are articulated and the rear and front wheels are the same dimensions.

Armored wheel loaders

[

edit

]

Armored wheel loader of the Israeli Defense Forces

The Israeli Combat Engineering Corps uses armored Caterpillar 966 wheel loaders for construction and combat engineering missions in militarily occupied territories such as the West Bank. They are often seen building or removing road blocks and building bases and fortifications. Since 2005, they have also been used to demolish small houses. The Israel Defense Forces added armor plating to the loader to protect it against rocks, stones, molotov cocktails, and light gunfire.

Rio de Janeiro's police elite squad Batalhão de Operações Policiais Especiais (BOPE) has acquired one wheel loader designed for military use to open routes and make way for the police in Rio de Janeiro's slums, which are controlled, and blocked, by drug dealers.[4]

Several if not most countries have similar equipment. The Dutch armed forces for instance use models like the Werklust WG18Edef, which weighs 15 tons, 2 more than the corresponding unarmored civilian model. In addition, the Dutch military previously used extra armor modules covering most of the window surface with steel for extra protection. These were however not popular with the crews due to low visibility.

The Turkish Army and Turkish Police use remote controlled armored wheel loader Tosun during the building of the Syria–Turkey barrier, the Operation Euphrates Shield, Operation Idlib Shield) and Operation Olive Branch.[5]

Tractor front loaders

[

edit

]

A New Holland T5070 tractor with a Quicke Q35 front-loader attachment in Switzerland

These loaders are a popular addition to tractors from 40 to 150 kW (50 to 200 hp). Its current 'drive-in' form was originally designed and developed in 1958 by a Swedish company named Ålö when they launched their Quicke loader.[6] Tractor loaders were developed to perform a multitude of farming tasks, and are popular due to their relatively low cost (compared to Telehandler) and high versatility. Tractor loaders can be fitted with many attachments such as hydraulic grabs and spikes to assist with bale and silage handling, forks for pallet work, and buckets for more general farm activities. Industrial tractor loaders equipped with box graders are marketed to contractors as skip loaders.[7]

Compact front end loaders

[

edit

]

Abram Dietrich Thiessen of Eyebrow Saskatchewan in the 1940s built the first quick attach front end loader.

Semi-curved compact loader on a John Deere compact utility tractor Visibility comparison of different loader designs

Front-end loaders (FELs) are popular additions to compact utility tractors and farm tractors. Compact utility tractors, also called CUTs, are small tractors, typically with 10 to 40 kW (18 to 50 hp) and used primarily for grounds maintenance and landscape chores.[citation needed] There are 2 primary designs of compact tractor FELs, the traditional dogleg designed style and the curved arm style.

John Deere manufactures a semi-curved loader design that does not feature the one piece curved arm, but also is not of the traditional two piece design. New Holland introduced a compact loader with a one piece curved arm on its compact utility tractors, similar one piece curved arm loaders are now available on compact tractors on many brands including Case IH/Farmall, and some Montana and Kioti tractors. Kubota markets traditional loader designs on most of its compact tractors but now features a semi-curved loader design similar to the John Deere loader design on several of its small tractors.

While the front-end loaders on CUT size tractors are capable of many tasks, given their relatively small size and low capacities when compared to commercial loaders, the compact loaders can be made more useful with some simple options. A toothbar is commonly added to the front edge of a loader bucket to aid with digging. Some loaders are equipped with a quick coupler, otherwise known as a quick attach (QA) system. The QA system allows the bucket to be removed easily and other tools to be added in its place. Common additions include a set of pallet forks for lifting pallets of goods or a bale spear for lifting hay bales.

LHD (Load, Haul, Dump machine) is also a front end loader but meant to be used for mine compact conditions, can handle various range of loads with varying size of buckets, and can be driven with electric motors as well as diesel engines.[8]

Skid loaders and track loaders

[

edit

]

A skid loader is a small loader utilizing four wheels with hydraulic drive that directs power to either, or both, sides of the vehicle. Very similar in appearance and design is the track loader, which utilizes a continuous track on either side of the vehicle instead of the wheels. Since the expiration of Bobcat's patent on its quick-connect system, newer tractor models are standardizing that popular format for front end attachments.[citation needed]

Swingloaders

[

edit

]

A swingloader is a rigid frame loader with a swinging boom. The Swingloader was invented in 1953 by German manufacturer Ahlmann with the AR1 model. The boom can swing 180 degrees or more. The loader is able to lift on all sides and dump off on all sides. Swingloaders are often used by the railroad industry to lay rail. Like other loaders many attachments can be attached to the boom such as magnets, forks, and buckets. Smaller swingloaders can be used in farming applications for loading out. A swinging boom is advantageous where space is limited as stability, mobility and space management are greatly increased over their articulated counterparts.

[

edit

]

Notable manufacturers

[

edit

]

Notable loader manufacturers include (by country):

See also

[

edit

]

References

[

edit

]


What are the three types of loader?

Loader (equipment)