Auto reload of configuration when any change happen

本文介绍如何使用 Java 7 中的 WatchService 特性来实现实时监听配置文件的变化,并自动刷新内存中的配置信息。文章通过具体实例展示了如何创建配置提供者以及配置更改监听器。

In this post, i am writing about a solution of very common problem. Every application has some configuration which is expected to be refreshed on every change in configuration file. Past approaches to solve this problem had consisted of having a Thread, which periodically poll for file change based on ‘last update time stamp’ of configuration file.

Now with java 7, things have changed. Java 7 has introduced an excellent feature: WatchService. I will try to give you a potential solution for above problem. This may not be the best implementation, but it will surely give a very good start for your solution. I bet !!

Sections in this post

1) A brief overview of WatchService
2) Writing our configuration provider
3) Introducing configuration change listener
4) Testing our code
5) Key notes

A brief overview of WatchService

A WatchService is JDKs internal service which watches for changes on registered objects. These registered objects are necessarily the instances of Watchable interface. When registering the watchable instance with WatchService, we need to specify the kind of change events we are interested in.

There are four type of events a of now: ENTRY_CREATEENTRY_DELETEENTRY_MODIFY and OVERFLOW. You can read about these events in provided links.

WatchService interface extends Closeable interface, means service can be closed as and when required. Normally, it should be done using JVM provided shut down hooks.

Writing our Configuration provider

A configuration provider is simply a wrapper for holding the set of properties in java,util.Properties instance. It also provides methods to get the configured properties using their KEY.

A sample implementation goes as below :

package testWatchService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ApplicationConfiguration {
	private final static ApplicationConfiguration INSTANCE = new ApplicationConfiguration();

	public static ApplicationConfiguration getInstance() {
		return INSTANCE;
	}

	private static Properties configuration = new Properties();

	private static Properties getConfiguration() {
		return configuration;
	}

	public void initilize(final String file) {
		InputStream in = null;
		try {
			in = new FileInputStream(new File(file));
			configuration.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getConfiguration(final String key) {
		return (String) getConfiguration().get(key);
	}

	public String getConfigurationWithDefaultValue(final String key,
			final String defaultValue) {
		return (String) getConfiguration().getProperty(key, defaultValue);
	}
}

Introducing configuration change listener

Now when we have our basic wrapper for our in memory cache of configuration properties, we need a mechanism to reload this cache on run time, whenever configuration file stored in file system changes.

I have written a sample working code for your help:

package testWatchService;

import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class ConfigurationChangeListner implements Runnable {
	private String configFileName = null;
	private String fullFilePath = null;

	public ConfigurationChangeListner(final String filePath) {
		this.fullFilePath = filePath;
	}

	public void run() {
		try {
			register(this.fullFilePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void register(final String file) throws IOException {
		final int lastIndex = file.lastIndexOf("/");
		String dirPath = file.substring(0, lastIndex + 1);
		String fileName = file.substring(lastIndex + 1, file.length());
		this.configFileName = fileName;

		configurationChanged(file);
		startWatcher(dirPath, fileName);
	}

	private void startWatcher(String dirPath, String file) throws IOException {
		final WatchService watchService = FileSystems.getDefault()
				.newWatchService();
		Path path = Paths.get(dirPath);
		path.register(watchService, ENTRY_MODIFY);

		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				try {
					watchService.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		WatchKey key = null;
		while (true) {
			try {
				key = watchService.take();
				for (WatchEvent< ?> event : key.pollEvents()) {
					if (event.context().toString().equals(configFileName)) {
						configurationChanged(dirPath + file);
					}
				}
				boolean reset = key.reset();
				if (!reset) {
					System.out.println("Could not reset the watch key.");
					break;
				}
			} catch (Exception e) {
				System.out.println("InterruptedException: " + e.getMessage());
			}
		}
	}

	public void configurationChanged(final String file) {
		System.out.println("Refreshing the configuration.");
		ApplicationConfiguration.getInstance().initilize(file);
	}
}

Above class is created using a thread which will be listening to configuration properties file changes using WatchService.
Once, it detects any modification in file, it simply refresh the in memory cache of configuration.

The constructor of above listener takes only one parameter i.e. fully qualified path of monitored configuration file. Listener class is notified immediately when configuration file is changed in file system.

This listener class  then call ApplicationConfiguration.getInstance().initilize(file); to reload in memory cache.

Testing our code

Now, when we are ready with our classes, we will test them.

First of all, store a test.properties file with following content in c:/Lokesh/temp folder.

TEST_KEY=TEST_VALUE

Now, test above classes using below code.

package testWatchService;

public class ConfigChangeTest {
	private static final String FILE_PATH = "C:/Lokesh/temp/test.properties";

	public static void main(String[] args) {
		ConfigurationChangeListner listner = new ConfigurationChangeListner(
				FILE_PATH);
		try {
			new Thread(listner).start();
			while (true) {
				Thread.sleep(2000l);
				System.out.println(ApplicationConfiguration.getInstance()
						.getConfiguration("TEST_KEY"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output of above program (Change the TEST_VALUE to TEST_VALUE1 and TEST_VALUE2 using any file editor and save) ::

Refreshing the configuration.

TEST_VALUE

TEST_VALUE

TEST_VALUE

Refreshing the configuration.

TEST_VALUE1

Refreshing the configuration.

TEST_VALUE2

Above outputs show that every time we make any change to property file, properties loaded are refreshed and new property value is available to use. Good work done so far !!

Key notes

1) If you are using java 7 in your new project, and you are not using old fashioned methods to reload your properties, you are not doing it rightly.

2) WatchService provides two methods take() and poll(). While take() method wait for next change to happen and until it is blocked, poll() immediately check for change event.

If nothing changed from last poll() call, it will return null. poll() method does not block the execution, so should be called in a Thread with some sleep time.

Happy Learning !!

/* * Copyright (c) 2020 - 2025 Renesas Electronics Corporation and/or its affiliates * * SPDX-License-Identifier: BSD-3-Clause */ /*******************************************************************************************************************//** * @ingroup RENESAS_TRANSFER_INTERFACES * @defgroup TRANSFER_API Transfer Interface * * @brief Interface for data transfer functions. * * @section TRANSFER_API_SUMMARY Summary * The transfer interface supports background data transfer (no CPU intervention). * * * @{ **********************************************************************************************************************/ #ifndef R_TRANSFER_API_H #define R_TRANSFER_API_H /*********************************************************************************************************************** * Includes **********************************************************************************************************************/ /* Common error codes and definitions. */ #include "bsp_api.h" /* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ FSP_HEADER /********************************************************************************************************************** * Macro definitions **********************************************************************************************************************/ #define TRANSFER_SETTINGS_MODE_BITS (30U) #define TRANSFER_SETTINGS_SIZE_BITS (28U) #define TRANSFER_SETTINGS_SRC_ADDR_BITS (26U) #define TRANSFER_SETTINGS_CHAIN_MODE_BITS (22U) #define TRANSFER_SETTINGS_IRQ_BITS (21U) #define TRANSFER_SETTINGS_REPEAT_AREA_BITS (20U) #define TRANSFER_SETTINGS_DEST_ADDR_BITS (18U) /********************************************************************************************************************** * Typedef definitions **********************************************************************************************************************/ /** Transfer control block. Allocate an instance specific control block to pass into the transfer API calls. */ typedef void transfer_ctrl_t; #ifndef BSP_OVERRIDE_TRANSFER_MODE_T /** Transfer mode describes what will happen when a transfer request occurs. */ typedef enum e_transfer_mode { /** In normal mode, each transfer request causes a transfer of @ref transfer_size_t from the source pointer to * the destination pointer. The transfer length is decremented and the source and address pointers are * updated according to @ref transfer_addr_mode_t. After the transfer length reaches 0, transfer requests * will not cause any further transfers. */ TRANSFER_MODE_NORMAL = 0, /** Repeat mode is like normal mode, except that when the transfer length reaches 0, the pointer to the * repeat area and the transfer length will be reset to their initial values. If DMAC is used, the * transfer repeats only transfer_info_t::num_blocks times. After the transfer repeats * transfer_info_t::num_blocks times, transfer requests will not cause any further transfers. If DTC is * used, the transfer repeats continuously (no limit to the number of repeat transfers). */ TRANSFER_MODE_REPEAT = 1, /** In block mode, each transfer request causes transfer_info_t::length transfers of @ref transfer_size_t. * After each individual transfer, the source and destination pointers are updated according to * @ref transfer_addr_mode_t. After the block transfer is complete, transfer_info_t::num_blocks is * decremented. After the transfer_info_t::num_blocks reaches 0, transfer requests will not cause any * further transfers. */ TRANSFER_MODE_BLOCK = 2, /** In addition to block mode features, repeat-block mode supports a ring buffer of blocks and offsets * within a block (to split blocks into arrays of their first data, second data, etc.) */ TRANSFER_MODE_REPEAT_BLOCK = 3 } transfer_mode_t; #endif #ifndef BSP_OVERRIDE_TRANSFER_SIZE_T /** Transfer size specifies the size of each individual transfer. * Total transfer length = transfer_size_t * transfer_length_t */ typedef enum e_transfer_size { TRANSFER_SIZE_1_BYTE = 0, ///< Each transfer transfers a 8-bit value TRANSFER_SIZE_2_BYTE = 1, ///< Each transfer transfers a 16-bit value TRANSFER_SIZE_4_BYTE = 2, ///< Each transfer transfers a 32-bit value TRANSFER_SIZE_8_BYTE = 3 ///< Each transfer transfers a 64-bit value } transfer_size_t; #endif #ifndef BSP_OVERRIDE_TRANSFER_ADDR_MODE_T /** Address mode specifies whether to modify (increment or decrement) pointer after each transfer. */ typedef enum e_transfer_addr_mode { /** Address pointer remains fixed after each transfer. */ TRANSFER_ADDR_MODE_FIXED = 0, /** Offset is added to the address pointer after each transfer. */ TRANSFER_ADDR_MODE_OFFSET = 1, /** Address pointer is incremented by associated @ref transfer_size_t after each transfer. */ TRANSFER_ADDR_MODE_INCREMENTED = 2, /** Address pointer is decremented by associated @ref transfer_size_t after each transfer. */ TRANSFER_ADDR_MODE_DECREMENTED = 3 } transfer_addr_mode_t; #endif #ifndef BSP_OVERRIDE_TRANSFER_REPEAT_AREA_T /** Repeat area options (source or destination). In @ref TRANSFER_MODE_REPEAT, the selected pointer returns to its * original value after transfer_info_t::length transfers. In @ref TRANSFER_MODE_BLOCK and @ref TRANSFER_MODE_REPEAT_BLOCK, * the selected pointer returns to its original value after each transfer. */ typedef enum e_transfer_repeat_area { /** Destination area repeated in @ref TRANSFER_MODE_REPEAT or @ref TRANSFER_MODE_BLOCK or @ref TRANSFER_MODE_REPEAT_BLOCK. */ TRANSFER_REPEAT_AREA_DESTINATION = 0, /** Source area repeated in @ref TRANSFER_MODE_REPEAT or @ref TRANSFER_MODE_BLOCK or @ref TRANSFER_MODE_REPEAT_BLOCK. */ TRANSFER_REPEAT_AREA_SOURCE = 1 } transfer_repeat_area_t; #endif #ifndef BSP_OVERRIDE_TRANSFER_CHAIN_MODE_T /** Chain transfer mode options. * @note Only applies for DTC. */ typedef enum e_transfer_chain_mode { /** Chain mode not used. */ TRANSFER_CHAIN_MODE_DISABLED = 0, /** Switch to next transfer after a single transfer from this @ref transfer_info_t. */ TRANSFER_CHAIN_MODE_EACH = 2, /** Complete the entire transfer defined in this @ref transfer_info_t before chaining to next transfer. */ TRANSFER_CHAIN_MODE_END = 3 } transfer_chain_mode_t; #endif #ifndef BSP_OVERRIDE_TRANSFER_IRQ_T /** Interrupt options. */ typedef enum e_transfer_irq { /** Interrupt occurs only after last transfer. If this transfer is chained to a subsequent transfer, * the interrupt will occur only after subsequent chained transfer(s) are complete. * @warning DTC triggers the interrupt of the activation source. Choosing TRANSFER_IRQ_END with DTC will * prevent activation source interrupts until the transfer is complete. */ TRANSFER_IRQ_END = 0, /** Interrupt occurs after each transfer. * @note Not available in all HAL drivers. See HAL driver for details. */ TRANSFER_IRQ_EACH = 1 } transfer_irq_t; #endif #ifndef BSP_OVERRIDE_TRANSFER_CALLBACK_ARGS_T /** Callback function parameter data. */ typedef struct st_transfer_callback_args_t { void const * p_context; ///< Placeholder for user data. Set in @ref transfer_api_t::open function in ::transfer_cfg_t. } transfer_callback_args_t; #endif /** Driver specific information. */ typedef struct st_transfer_properties { uint32_t block_count_max; ///< Maximum number of blocks uint32_t block_count_remaining; ///< Number of blocks remaining uint32_t transfer_length_max; ///< Maximum number of transfers uint32_t transfer_length_remaining; ///< Number of transfers remaining } transfer_properties_t; #ifndef BSP_OVERRIDE_TRANSFER_INFO_T /** This structure specifies the properties of the transfer. * @warning When using DTC, this structure corresponds to the descriptor block registers required by the DTC. * The following components may be modified by the driver: p_src, p_dest, num_blocks, and length. * @warning When using DTC, do NOT reuse this structure to configure multiple transfers. Each transfer must * have a unique transfer_info_t. * @warning When using DTC, this structure must not be allocated in a temporary location. Any instance of this * structure must remain in scope until the transfer it is used for is closed. * @note When using DTC, consider placing instances of this structure in a protected section of memory. */ typedef struct st_transfer_info { union { struct { uint32_t : 16; uint32_t : 2; /** Select what happens to destination pointer after each transfer. */ transfer_addr_mode_t dest_addr_mode : 2; /** Select to repeat source or destination area, unused in @ref TRANSFER_MODE_NORMAL. */ transfer_repeat_area_t repeat_area : 1; /** Select if interrupts should occur after each individual transfer or after the completion of all planned * transfers. */ transfer_irq_t irq : 1; /** Select when the chain transfer ends. */ transfer_chain_mode_t chain_mode : 2; uint32_t : 2; /** Select what happens to source pointer after each transfer. */ transfer_addr_mode_t src_addr_mode : 2; /** Select number of bytes to transfer at once. @see transfer_info_t::length. */ transfer_size_t size : 2; /** Select mode from @ref transfer_mode_t. */ transfer_mode_t mode : 2; } transfer_settings_word_b; uint32_t transfer_settings_word; }; void const * volatile p_src; ///< Source pointer void * volatile p_dest; ///< Destination pointer /** Number of blocks to transfer when using @ref TRANSFER_MODE_BLOCK (both DTC an DMAC) or * @ref TRANSFER_MODE_REPEAT (DMAC only) or * @ref TRANSFER_MODE_REPEAT_BLOCK (DMAC only), unused in other modes. */ volatile uint16_t num_blocks; /** Length of each transfer. Range limited for @ref TRANSFER_MODE_BLOCK, @ref TRANSFER_MODE_REPEAT, * and @ref TRANSFER_MODE_REPEAT_BLOCK * see HAL driver for details. */ volatile uint16_t length; } transfer_info_t; #endif /** Driver configuration set in @ref transfer_api_t::open. All elements except p_extend are required and must be * initialized. */ typedef struct st_transfer_cfg { /** Pointer to transfer configuration options. If using chain transfer (DTC only), this can be a pointer to * an array of chained transfers that will be completed in order. */ transfer_info_t * p_info; void const * p_extend; ///< Extension parameter for hardware specific settings. } transfer_cfg_t; /** Select whether to start single or repeated transfer with software start. */ typedef enum e_transfer_start_mode { TRANSFER_START_MODE_SINGLE = 0, ///< Software start triggers single transfer. TRANSFER_START_MODE_REPEAT = 1 ///< Software start transfer continues until transfer is complete. } transfer_start_mode_t; /** Transfer functions implemented at the HAL layer will follow this API. */ typedef struct st_transfer_api { /** Initial configuration. * * @param[in,out] p_ctrl Pointer to control block. Must be declared by user. Elements set here. * @param[in] p_cfg Pointer to configuration structure. All elements of this structure * must be set by user. */ fsp_err_t (* open)(transfer_ctrl_t * const p_ctrl, transfer_cfg_t const * const p_cfg); /** Reconfigure the transfer. * Enable the transfer if p_info is valid. * * @param[in,out] p_ctrl Pointer to control block. Must be declared by user. Elements set here. * @param[in] p_info Pointer to a new transfer info structure. */ fsp_err_t (* reconfigure)(transfer_ctrl_t * const p_ctrl, transfer_info_t * p_info); /** Reset source address pointer, destination address pointer, and/or length, keeping all other settings the same. * Enable the transfer if p_src, p_dest, and length are valid. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. * @param[in] p_src Pointer to source. Set to NULL if source pointer should not change. * @param[in] p_dest Pointer to destination. Set to NULL if destination pointer should not change. * @param[in] num_transfers Transfer length in normal mode or number of blocks in block mode. In DMAC only, * resets number of repeats (initially stored in transfer_info_t::num_blocks) in * repeat mode. Not used in repeat mode for DTC. */ fsp_err_t (* reset)(transfer_ctrl_t * const p_ctrl, void const * p_src, void * p_dest, uint16_t const num_transfers); /** Enable transfer. Transfers occur after the activation source event (or when * @ref transfer_api_t::softwareStart is called if no peripheral event is chosen as activation source). * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. */ fsp_err_t (* enable)(transfer_ctrl_t * const p_ctrl); /** Disable transfer. Transfers do not occur after the activation source event (or when * @ref transfer_api_t::softwareStart is called if no peripheral event is chosen as the DMAC activation source). * @note If a transfer is in progress, it will be completed. Subsequent transfer requests do not cause a * transfer. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. */ fsp_err_t (* disable)(transfer_ctrl_t * const p_ctrl); /** Start transfer in software. * @warning Only works if no peripheral event is chosen as the DMAC activation source. * @note Not supported for DTC. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. * @param[in] mode Select mode from @ref transfer_start_mode_t. */ fsp_err_t (* softwareStart)(transfer_ctrl_t * const p_ctrl, transfer_start_mode_t mode); /** Stop transfer in software. The transfer will stop after completion of the current transfer. * @note Not supported for DTC. * @note Only applies for transfers started with TRANSFER_START_MODE_REPEAT. * @warning Only works if no peripheral event is chosen as the DMAC activation source. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. */ fsp_err_t (* softwareStop)(transfer_ctrl_t * const p_ctrl); /** Provides information about this transfer. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. * @param[out] p_properties Driver specific information. */ fsp_err_t (* infoGet)(transfer_ctrl_t * const p_ctrl, transfer_properties_t * const p_properties); /** Releases hardware lock. This allows a transfer to be reconfigured using @ref transfer_api_t::open. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. */ fsp_err_t (* close)(transfer_ctrl_t * const p_ctrl); /** To update next transfer information without interruption during transfer. * Allow further transfer continuation. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. * @param[in] p_src Pointer to source. Set to NULL if source pointer should not change. * @param[in] p_dest Pointer to destination. Set to NULL if destination pointer should not change. * @param[in] num_transfers Transfer length in normal mode or block mode. */ fsp_err_t (* reload)(transfer_ctrl_t * const p_ctrl, void const * p_src, void * p_dest, uint32_t const num_transfers); /** Specify callback function and optional context pointer and working memory pointer. * * @param[in] p_ctrl Control block set in @ref transfer_api_t::open call for this transfer. * @param[in] p_callback Callback function to register * @param[in] p_context Pointer to send to callback function * @param[in] p_callback_memory Pointer to volatile memory where callback structure can be allocated. * Callback arguments allocated here are only valid during the callback. */ fsp_err_t (* callbackSet)(transfer_ctrl_t * const p_ctrl, void (* p_callback)(transfer_callback_args_t *), void const * const p_context, transfer_callback_args_t * const p_callback_memory); } transfer_api_t; /** This structure encompasses everything that is needed to use an instance of this interface. */ typedef struct st_transfer_instance { transfer_ctrl_t * p_ctrl; ///< Pointer to the control structure for this instance transfer_cfg_t const * p_cfg; ///< Pointer to the configuration structure for this instance transfer_api_t const * p_api; ///< Pointer to the API structure for this instance } transfer_instance_t; /* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ FSP_FOOTER #endif /*******************************************************************************************************************//** * @} (end defgroup TRANSFER_API) **********************************************************************************************************************/ 这里存在 // 标准函数原型应类似: fsp_err_t R_TRANSFER_Open( transfer_ctrl_t * const p_ctrl, transfer_cfg_t const * const p_cfg);
07-04
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值